blob: 65b683e7ca873d3a9838c87df87d06265e0b99ec [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"
Chandler Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000020#include "llvm/Analysis/GlobalsModRef.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");
Chad Rosier1a4bc112016-04-22 18:47:21 +000043STATISTIC(NumCSECVP, "Number of compare instructions CVP'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 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000102 }
103
Michael Ilseman336cb792012-10-09 16:57:38 +0000104 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
105 Value *LHS = CI->getOperand(0);
106 Value *RHS = CI->getOperand(1);
107 CmpInst::Predicate Pred = CI->getPredicate();
108 if (Inst->getOperand(0) > Inst->getOperand(1)) {
109 std::swap(LHS, RHS);
110 Pred = CI->getSwappedPredicate();
111 }
112 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
113 }
114
115 if (CastInst *CI = dyn_cast<CastInst>(Inst))
116 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
117
118 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
119 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
120 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
121
122 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
123 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
124 IVI->getOperand(1),
125 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
126
127 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
128 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
129 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000130 isa<ShuffleVectorInst>(Inst)) &&
131 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000132
Chris Lattner02a97762011-01-03 01:10:08 +0000133 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000134 return hash_combine(
135 Inst->getOpcode(),
136 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000137}
138
Chris Lattner79d83062011-01-03 02:20:48 +0000139bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000140 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
141
142 if (LHS.isSentinel() || RHS.isSentinel())
143 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000144
Chandler Carruth7253bba2015-01-24 11:33:55 +0000145 if (LHSI->getOpcode() != RHSI->getOpcode())
146 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000147 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000148 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000149
150 // If we're not strictly identical, we still might be a commutable instruction
151 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
152 if (!LHSBinOp->isCommutative())
153 return false;
154
Chandler Carruth7253bba2015-01-24 11:33:55 +0000155 assert(isa<BinaryOperator>(RHSI) &&
156 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000157 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
158
Michael Ilseman336cb792012-10-09 16:57:38 +0000159 // Commuted equality
160 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000161 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000162 }
163 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000164 assert(isa<CmpInst>(RHSI) &&
165 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000166 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
167 // Commuted equality
168 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000169 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
170 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000171 }
172
173 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000174}
175
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000176//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000177// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000178//===----------------------------------------------------------------------===//
179
180namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000181/// \brief Struct representing the available call values in the scoped hash
182/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000183struct CallValue {
184 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000185
Chandler Carruth7253bba2015-01-24 11:33:55 +0000186 CallValue(Instruction *I) : Inst(I) {
187 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
188 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000189
Chandler Carruth7253bba2015-01-24 11:33:55 +0000190 bool isSentinel() const {
191 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
192 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
193 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000194
Chandler Carruth7253bba2015-01-24 11:33:55 +0000195 static bool canHandle(Instruction *Inst) {
196 // Don't value number anything that returns void.
197 if (Inst->getType()->isVoidTy())
198 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000199
Chandler Carruth7253bba2015-01-24 11:33:55 +0000200 CallInst *CI = dyn_cast<CallInst>(Inst);
201 if (!CI || !CI->onlyReadsMemory())
202 return false;
203 return true;
204 }
205};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000206}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000207
208namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000209template <> struct DenseMapInfo<CallValue> {
210 static inline CallValue getEmptyKey() {
211 return DenseMapInfo<Instruction *>::getEmptyKey();
212 }
213 static inline CallValue getTombstoneKey() {
214 return DenseMapInfo<Instruction *>::getTombstoneKey();
215 }
216 static unsigned getHashValue(CallValue Val);
217 static bool isEqual(CallValue LHS, CallValue RHS);
218};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000219}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000220
Chris Lattner92bb0f92011-01-03 03:41:27 +0000221unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000222 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000223 // Hash all of the operands as pointers and mix in the opcode.
224 return hash_combine(
225 Inst->getOpcode(),
226 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000227}
228
Chris Lattner92bb0f92011-01-03 03:41:27 +0000229bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000230 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000231 if (LHS.isSentinel() || RHS.isSentinel())
232 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000233 return LHSI->isIdenticalTo(RHSI);
234}
235
Chris Lattner79d83062011-01-03 02:20:48 +0000236//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000237// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000238//===----------------------------------------------------------------------===//
239
Chris Lattner18ae5432011-01-02 23:04:14 +0000240namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000241/// \brief A simple and fast domtree-based CSE pass.
242///
243/// This pass does a simple depth-first walk over the dominator tree,
244/// eliminating trivially redundant instructions and using instsimplify to
245/// canonicalize things as it goes. It is intended to be fast and catch obvious
246/// cases so that instcombine and other passes are more effective. It is
247/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000248class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000249public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000250 const TargetLibraryInfo &TLI;
251 const TargetTransformInfo &TTI;
252 DominatorTree &DT;
253 AssumptionCache &AC;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000254 typedef RecyclingAllocator<
255 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
256 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000257 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000258
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000259 /// \brief A scoped hash table of the current values of all of our simple
260 /// scalar expressions.
261 ///
262 /// As we walk down the domtree, we look to see if instructions are in this:
263 /// if so, we replace them with what we find, otherwise we insert them so
264 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000265 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000266
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000267 /// A scoped hash table of the current values of previously encounted memory
268 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000269 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000270 /// This allows us to get efficient access to dominating loads or stores when
271 /// we have a fully redundant load. In addition to the most recent load, we
272 /// keep track of a generation count of the read, which is compared against
273 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000274 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000275 /// CSE loads with other loads that have no intervening store. Ordering
276 /// events (such as fences or atomic instructions) increment the generation
277 /// count as well; essentially, we model these as writes to all possible
278 /// locations. Note that atomic and/or volatile loads and stores can be
279 /// present the table; it is the responsibility of the consumer to inspect
280 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000281 struct LoadValue {
Philip Reames32b55182016-05-06 01:13:58 +0000282 Instruction *DefInst;
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000283 unsigned Generation;
284 int MatchingId;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000285 bool IsAtomic;
286 LoadValue()
Philip Reames32b55182016-05-06 01:13:58 +0000287 : DefInst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {}
Geoff Berry5ae272c2016-04-28 15:22:37 +0000288 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000289 bool IsAtomic)
Philip Reames32b55182016-05-06 01:13:58 +0000290 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000291 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000292 };
293 typedef RecyclingAllocator<BumpPtrAllocator,
294 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000295 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000296 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
297 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000298 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000299
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000300 /// \brief A scoped hash table of the current values of read-only call
301 /// values.
302 ///
303 /// It uses the same generation count as loads.
Geoff Berry2f64c202016-05-13 17:54:58 +0000304 typedef ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>
305 CallHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000306 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000307
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000308 /// \brief This is the current generation of the memory value.
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000309 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000310
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000311 /// \brief Set up the EarlyCSE runner for a particular function.
Benjamin Kramer6db33382015-10-15 15:08:58 +0000312 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
313 DominatorTree &DT, AssumptionCache &AC)
314 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000315
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000316 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000317
318private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000319 // Almost a POD, but needs to call the constructors for the scoped hash
320 // tables so that a new scope gets pushed on. These are RAII so that the
321 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000322 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000323 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000324 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
325 CallHTType &AvailableCalls)
326 : Scope(AvailableValues), LoadScope(AvailableLoads),
327 CallScope(AvailableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000328
Chandler Carruth7253bba2015-01-24 11:33:55 +0000329 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000330 NodeScope(const NodeScope &) = delete;
331 void operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000332
333 ScopedHTType::ScopeTy Scope;
334 LoadHTType::ScopeTy LoadScope;
335 CallHTType::ScopeTy CallScope;
336 };
337
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000338 // Contains all the needed information to create a stack for doing a depth
339 // first tranversal of the tree. This includes scopes for values, loads, and
340 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000341 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000342 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000343 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000344 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
345 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
Chandler Carruth7253bba2015-01-24 11:33:55 +0000346 DomTreeNode::iterator child, DomTreeNode::iterator end)
347 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000348 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000349 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000350
351 // Accessors.
352 unsigned currentGeneration() { return CurrentGeneration; }
353 unsigned childGeneration() { return ChildGeneration; }
354 void childGeneration(unsigned generation) { ChildGeneration = generation; }
355 DomTreeNode *node() { return Node; }
356 DomTreeNode::iterator childIter() { return ChildIter; }
357 DomTreeNode *nextChild() {
358 DomTreeNode *child = *ChildIter;
359 ++ChildIter;
360 return child;
361 }
362 DomTreeNode::iterator end() { return EndIter; }
363 bool isProcessed() { return Processed; }
364 void process() { Processed = true; }
365
Chandler Carruth7253bba2015-01-24 11:33:55 +0000366 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000367 StackNode(const StackNode &) = delete;
368 void operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000369
370 // Members.
371 unsigned CurrentGeneration;
372 unsigned ChildGeneration;
373 DomTreeNode *Node;
374 DomTreeNode::iterator ChildIter;
375 DomTreeNode::iterator EndIter;
376 NodeScope Scopes;
377 bool Processed;
378 };
379
Chad Rosierf9327d62015-01-26 22:51:15 +0000380 /// \brief Wrapper class to handle memory instructions, including loads,
381 /// stores and intrinsic loads and stores defined by the target.
382 class ParseMemoryInst {
383 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000384 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Philip Reames9e5e2d62015-12-07 22:41:23 +0000385 : IsTargetMemInst(false), Inst(Inst) {
386 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
387 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
388 IsTargetMemInst = true;
389 }
390 bool isLoad() const {
391 if (IsTargetMemInst) return Info.ReadMem;
392 return isa<LoadInst>(Inst);
393 }
394 bool isStore() const {
395 if (IsTargetMemInst) return Info.WriteMem;
396 return isa<StoreInst>(Inst);
397 }
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000398 bool isAtomic() const {
399 if (IsTargetMemInst) {
400 assert(Info.IsSimple && "need to refine IsSimple in TTI");
401 return false;
402 }
403 return Inst->isAtomic();
404 }
405 bool isUnordered() const {
406 if (IsTargetMemInst) {
407 assert(Info.IsSimple && "need to refine IsSimple in TTI");
408 return true;
409 }
410 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
411 return LI->isUnordered();
412 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
413 return SI->isUnordered();
414 }
415 // Conservative answer
416 return !Inst->isAtomic();
417 }
418
419 bool isVolatile() const {
420 if (IsTargetMemInst) {
421 assert(Info.IsSimple && "need to refine IsSimple in TTI");
422 return false;
423 }
424 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
425 return LI->isVolatile();
426 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
427 return SI->isVolatile();
428 }
429 // Conservative answer
430 return true;
431 }
432
Junmo Park80440eb2016-02-18 10:09:20 +0000433
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000434 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000435 return (getPointerOperand() == Inst.getPointerOperand() &&
436 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000437 }
Philip Reames9e5e2d62015-12-07 22:41:23 +0000438 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000439
Chad Rosierf9327d62015-01-26 22:51:15 +0000440 // For regular (non-intrinsic) loads/stores, this is set to -1. For
441 // intrinsic loads/stores, the id is retrieved from the corresponding
442 // field in the MemIntrinsicInfo structure. That field contains
443 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000444 int getMatchingId() const {
445 if (IsTargetMemInst) return Info.MatchingId;
446 return -1;
447 }
448 Value *getPointerOperand() const {
449 if (IsTargetMemInst) return Info.PtrVal;
450 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
451 return LI->getPointerOperand();
452 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
453 return SI->getPointerOperand();
454 }
455 return nullptr;
456 }
457 bool mayReadFromMemory() const {
458 if (IsTargetMemInst) return Info.ReadMem;
459 return Inst->mayReadFromMemory();
460 }
461 bool mayWriteToMemory() const {
462 if (IsTargetMemInst) return Info.WriteMem;
463 return Inst->mayWriteToMemory();
464 }
465
466 private:
467 bool IsTargetMemInst;
468 MemIntrinsicInfo Info;
469 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000470 };
471
Chris Lattner18ae5432011-01-02 23:04:14 +0000472 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000473
Chad Rosierf9327d62015-01-26 22:51:15 +0000474 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
475 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
476 return LI;
477 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
478 return SI->getValueOperand();
479 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000480 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
481 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000482 }
Chris Lattner704541b2011-01-02 21:47:05 +0000483};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000484}
Chris Lattner704541b2011-01-02 21:47:05 +0000485
Chris Lattner18ae5432011-01-02 23:04:14 +0000486bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000487 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000488 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000489
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000490 // If this block has a single predecessor, then the predecessor is the parent
491 // of the domtree node and all of the live out memory values are still current
492 // in this block. If this block has multiple predecessors, then they could
493 // have invalidated the live-out memory values of our parent value. For now,
494 // just be conservative and invalidate memory if this block has multiple
495 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000496 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000497 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000498
Philip Reames7c78ef72015-05-22 23:53:24 +0000499 // If this node has a single predecessor which ends in a conditional branch,
500 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000501 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000502 // which reaches this block where the condition might hold a different
503 // value. Since we're adding this to the scoped hash table (like any other
504 // def), it will have been popped if we encounter a future merge block.
505 if (BasicBlock *Pred = BB->getSinglePredecessor())
506 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
507 if (BI->isConditional())
508 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
509 if (SimpleValue::canHandle(CondInst)) {
510 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
511 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
512 ConstantInt::getTrue(BB->getContext()) :
513 ConstantInt::getFalse(BB->getContext());
514 AvailableValues.insert(CondInst, ConditionalConstant);
515 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
516 << CondInst->getName() << "' as " << *ConditionalConstant
517 << " in " << BB->getName() << "\n");
Chad Rosier1a4bc112016-04-22 18:47:21 +0000518 // Replace all dominated uses with the known value.
519 if (unsigned Count =
520 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
521 BasicBlockEdge(Pred, BB))) {
522 Changed = true;
523 NumCSECVP = NumCSECVP + Count;
524 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000525 }
526
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000527 /// LastStore - Keep track of the last non-volatile store that we saw... for
528 /// as long as there in no instruction that reads memory. If we see a store
529 /// to the same location, we delete the dead store. This zaps trivial dead
530 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000531 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000532
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000533 const DataLayout &DL = BB->getModule()->getDataLayout();
Chris Lattner18ae5432011-01-02 23:04:14 +0000534
535 // See if any instructions in the block can be eliminated. If so, do it. If
536 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000537 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000538 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000539
Chris Lattner18ae5432011-01-02 23:04:14 +0000540 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000541 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000542 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000543 Inst->eraseFromParent();
544 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000545 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000546 continue;
547 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000548
Hal Finkel1e16fa32014-11-03 20:21:32 +0000549 // Skip assume intrinsics, they don't really have side effects (although
550 // they're marked as such to ensure preservation of control dependencies),
551 // and this pass will not disturb any of the assumption's control
552 // dependencies.
553 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
554 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
555 continue;
556 }
557
Sanjoy Dasee81b232016-04-29 21:52:58 +0000558 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000559 if (auto *CondI =
560 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Sanjoy Dasee81b232016-04-29 21:52:58 +0000561 // The condition we're on guarding here is true for all dominated
562 // locations.
563 if (SimpleValue::canHandle(CondI))
564 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
565 }
566
567 // Guard intrinsics read all memory, but don't write any memory.
568 // Accordingly, don't update the generation but consume the last store (to
569 // avoid an incorrect DSE).
570 LastStore = nullptr;
571 continue;
572 }
573
Chris Lattner18ae5432011-01-02 23:04:14 +0000574 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
575 // its simpler value.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000576 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000577 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000578 Inst->replaceAllUsesWith(V);
579 Inst->eraseFromParent();
580 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000581 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000582 continue;
583 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000584
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000585 // If this is a simple instruction that we can value number, process it.
586 if (SimpleValue::canHandle(Inst)) {
587 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000588 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000589 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000590 if (auto *I = dyn_cast<Instruction>(V))
591 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000592 Inst->replaceAllUsesWith(V);
593 Inst->eraseFromParent();
594 Changed = true;
595 ++NumCSE;
596 continue;
597 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000598
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000599 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000600 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000601 continue;
602 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000603
Chad Rosierf9327d62015-01-26 22:51:15 +0000604 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000605 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000606 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000607 // (conservatively) we can't peak past the ordering implied by this
608 // operation, but we can add this load to our set of available values
609 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000610 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000611 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000612 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000613
Chris Lattner92bb0f92011-01-03 03:41:27 +0000614 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000615 // generation, replace this instruction.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000616 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +0000617 if (InVal.DefInst != nullptr && InVal.Generation == CurrentGeneration &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000618 InVal.MatchingId == MemInst.getMatchingId() &&
619 // We don't yet handle removing loads with ordering of any kind.
620 !MemInst.isVolatile() && MemInst.isUnordered() &&
621 // We can't replace an atomic load with one which isn't also atomic.
622 InVal.IsAtomic >= MemInst.isAtomic()) {
Philip Reames32b55182016-05-06 01:13:58 +0000623 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000624 if (Op != nullptr) {
625 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Philip Reames32b55182016-05-06 01:13:58 +0000626 << " to: " << *InVal.DefInst << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000627 if (!Inst->use_empty())
628 Inst->replaceAllUsesWith(Op);
629 Inst->eraseFromParent();
630 Changed = true;
631 ++NumCSELoad;
632 continue;
633 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000634 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000635
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000636 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000637 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000638 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000639 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
640 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +0000641 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000642 continue;
643 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000644
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000645 // If this instruction may read from memory, forget LastStore.
Chad Rosierf9327d62015-01-26 22:51:15 +0000646 // Load/store intrinsics will indicate both a read and a write to
647 // memory. The target may override this (e.g. so that a store intrinsic
648 // does not read from memory, and thus will be treated the same as a
649 // regular store for commoning purposes).
650 if (Inst->mayReadFromMemory() &&
651 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000652 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000653
Chris Lattner92bb0f92011-01-03 03:41:27 +0000654 // If this is a read-only call, process it.
655 if (CallValue::canHandle(Inst)) {
656 // If we have an available version of this call, and if it is the right
657 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +0000658 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +0000659 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000660 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
661 << " to: " << *InVal.first << '\n');
662 if (!Inst->use_empty())
663 Inst->replaceAllUsesWith(InVal.first);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000664 Inst->eraseFromParent();
665 Changed = true;
666 ++NumCSECall;
667 continue;
668 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000669
Chris Lattner92bb0f92011-01-03 03:41:27 +0000670 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000671 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +0000672 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000673 continue;
674 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000675
Philip Reamesdfd890d2015-08-27 01:32:33 +0000676 // A release fence requires that all stores complete before it, but does
677 // not prevent the reordering of following loads 'before' the fence. As a
678 // result, we don't need to consider it as writing to memory and don't need
679 // to advance the generation. We do need to prevent DSE across the fence,
680 // but that's handled above.
681 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000682 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000683 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
684 continue;
685 }
686
Philip Reamesae1f265b2015-12-16 01:01:30 +0000687 // write back DSE - If we write back the same value we just loaded from
688 // the same location and haven't passed any intervening writes or ordering
689 // operations, we can remove the write. The primary benefit is in allowing
690 // the available load table to remain valid and value forward past where
691 // the store originally was.
692 if (MemInst.isValid() && MemInst.isStore()) {
693 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +0000694 if (InVal.DefInst &&
695 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +0000696 InVal.Generation == CurrentGeneration &&
697 InVal.MatchingId == MemInst.getMatchingId() &&
698 // We don't yet handle removing stores with ordering of any kind.
699 !MemInst.isVolatile() && MemInst.isUnordered()) {
700 assert((!LastStore ||
701 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
702 MemInst.getPointerOperand()) &&
703 "can't have an intervening store!");
704 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
705 Inst->eraseFromParent();
706 Changed = true;
707 ++NumDSE;
708 // We can avoid incrementing the generation count since we were able
709 // to eliminate this store.
710 continue;
711 }
712 }
713
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000714 // Okay, this isn't something we can CSE at all. Check to see if it is
715 // something that could modify memory. If so, our available memory values
716 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000717 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000718 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000719
Chad Rosierf9327d62015-01-26 22:51:15 +0000720 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000721 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000722 // location with no intervening loads. Delete the earlier store.
723 // At the moment, we don't remove ordered stores, but do remove
724 // unordered atomic stores. There's no special requirement (for
725 // unordered atomics) about removing atomic stores only in favor of
726 // other atomic stores since we we're going to execute the non-atomic
727 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000728 if (LastStore) {
729 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000730 assert(LastStoreMemInst.isUnordered() &&
731 !LastStoreMemInst.isVolatile() &&
732 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000733 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
734 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
735 << " due to: " << *Inst << '\n');
736 LastStore->eraseFromParent();
737 Changed = true;
738 ++NumDSE;
739 LastStore = nullptr;
740 }
Philip Reames018dbf12014-11-18 17:46:32 +0000741 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000742 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000743
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000744 // Okay, we just invalidated anything we knew about loaded values. Try
745 // to salvage *something* by remembering that the stored value is a live
746 // version of the pointer. It is safe to forward from volatile stores
747 // to non-volatile loads, so we don't have to check for volatility of
748 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000749 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000750 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000751 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
752 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +0000753
Philip Reames15145fb2015-12-17 18:50:50 +0000754 // Remember that this was the last unordered store we saw for DSE. We
755 // don't yet handle DSE on ordered or volatile stores since we don't
756 // have a good way to model the ordering requirement for following
757 // passes once the store is removed. We could insert a fence, but
758 // since fences are slightly stronger than stores in their ordering,
759 // it's not clear this is a profitable transform. Another option would
760 // be to merge the ordering with that of the post dominating store.
761 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000762 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000763 else
764 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000765 }
766 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000767 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000768
Chris Lattner18ae5432011-01-02 23:04:14 +0000769 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000770}
Chris Lattner18ae5432011-01-02 23:04:14 +0000771
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000772bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000773 // Note, deque is being used here because there is significant performance
774 // gains over vector when the container becomes very large due to the
775 // specific access patterns. For more information see the mailing list
776 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000777 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000778 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000779
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000780 bool Changed = false;
781
782 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000783 nodesToProcess.push_back(new StackNode(
784 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000785 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000786
787 // Save the current generation.
788 unsigned LiveOutGeneration = CurrentGeneration;
789
790 // Process the stack.
791 while (!nodesToProcess.empty()) {
792 // Grab the first item off the stack. Set the current generation, remove
793 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000794 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000795
796 // Initialize class members.
797 CurrentGeneration = NodeToProcess->currentGeneration();
798
799 // Check if the node needs to be processed.
800 if (!NodeToProcess->isProcessed()) {
801 // Process the node.
802 Changed |= processNode(NodeToProcess->node());
803 NodeToProcess->childGeneration(CurrentGeneration);
804 NodeToProcess->process();
805 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
806 // Push the next child onto the stack.
807 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000808 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000809 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
810 NodeToProcess->childGeneration(), child, child->begin(),
811 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000812 } else {
813 // It has been processed, and there are no more children to process,
814 // so delete it and pop it off the stack.
815 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000816 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000817 }
818 } // while (!nodes...)
819
820 // Reset the current generation.
821 CurrentGeneration = LiveOutGeneration;
822
823 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000824}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000825
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000826PreservedAnalyses EarlyCSEPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000827 AnalysisManager<Function> &AM) {
828 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
829 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
830 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
831 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000832
Benjamin Kramer6db33382015-10-15 15:08:58 +0000833 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000834
835 if (!CSE.run())
836 return PreservedAnalyses::all();
837
838 // CSE preserves the dominator tree because it doesn't mutate the CFG.
839 // FIXME: Bundle this with other CFG-preservation.
840 PreservedAnalyses PA;
841 PA.preserve<DominatorTreeAnalysis>();
842 return PA;
843}
844
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000845namespace {
846/// \brief A simple and fast domtree-based CSE pass.
847///
848/// This pass does a simple depth-first walk over the dominator tree,
849/// eliminating trivially redundant instructions and using instsimplify to
850/// canonicalize things as it goes. It is intended to be fast and catch obvious
851/// cases so that instcombine and other passes are more effective. It is
852/// expected that a later pass of GVN will catch the interesting/hard cases.
853class EarlyCSELegacyPass : public FunctionPass {
854public:
855 static char ID;
856
857 EarlyCSELegacyPass() : FunctionPass(ID) {
858 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
859 }
860
861 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000862 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000863 return false;
864
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000865 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000866 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000867 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
868 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
869
Benjamin Kramer6db33382015-10-15 15:08:58 +0000870 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000871
872 return CSE.run();
873 }
874
875 void getAnalysisUsage(AnalysisUsage &AU) const override {
876 AU.addRequired<AssumptionCacheTracker>();
877 AU.addRequired<DominatorTreeWrapperPass>();
878 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000879 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000880 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000881 AU.setPreservesCFG();
882 }
883};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000884}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000885
886char EarlyCSELegacyPass::ID = 0;
887
888FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
889
890INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
891 false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000892INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000893INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
894INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
895INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
896INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)