blob: c5c9b2c185d63ff40fd88a95a1ca7ef4fc5c4b5b [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"
Davide Italiano0dc47782017-06-14 19:29:53 +000018#include "llvm/ADT/SetVector.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000019#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000020#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000021#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000023#include "llvm/Analysis/MemorySSA.h"
24#include "llvm/Analysis/MemorySSAUpdater.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
Chad Rosierf9327d62015-01-26 22:51:15 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000030#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Pass.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000036#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Transforms/Utils/Local.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000038#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000039using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000040using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000041
Chandler Carruth964daaa2014-04-22 02:55:47 +000042#define DEBUG_TYPE "early-cse"
43
Chris Lattner4cb36542011-01-03 03:28:23 +000044STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
45STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000046STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000047STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
48STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000049STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000050
Chris Lattner79d83062011-01-03 02:20:48 +000051//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000052// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000053//===----------------------------------------------------------------------===//
54
Chris Lattner704541b2011-01-02 21:47:05 +000055namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +000056/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000057struct SimpleValue {
58 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000059
Chandler Carruth7253bba2015-01-24 11:33:55 +000060 SimpleValue(Instruction *I) : Inst(I) {
61 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
62 }
Nadav Rotem465834c2012-07-24 10:51:42 +000063
Chandler Carruth7253bba2015-01-24 11:33:55 +000064 bool isSentinel() const {
65 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
66 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
67 }
Nadav Rotem465834c2012-07-24 10:51:42 +000068
Chandler Carruth7253bba2015-01-24 11:33:55 +000069 static bool canHandle(Instruction *Inst) {
70 // This can only handle non-void readnone functions.
71 if (CallInst *CI = dyn_cast<CallInst>(Inst))
72 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
73 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
74 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
75 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
76 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
77 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
78 }
79};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000080}
Chris Lattner18ae5432011-01-02 23:04:14 +000081
82namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +000083template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +000084 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000085 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000086 }
Chris Lattner79d83062011-01-03 02:20:48 +000087 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000088 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000089 }
Chris Lattner79d83062011-01-03 02:20:48 +000090 static unsigned getHashValue(SimpleValue Val);
91 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000092};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000093}
Chris Lattner18ae5432011-01-02 23:04:14 +000094
Chris Lattner79d83062011-01-03 02:20:48 +000095unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000096 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000097 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +000098 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +000099 Value *LHS = BinOp->getOperand(0);
100 Value *RHS = BinOp->getOperand(1);
101 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
102 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000103
Michael Ilseman336cb792012-10-09 16:57:38 +0000104 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000105 }
106
Michael Ilseman336cb792012-10-09 16:57:38 +0000107 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
108 Value *LHS = CI->getOperand(0);
109 Value *RHS = CI->getOperand(1);
110 CmpInst::Predicate Pred = CI->getPredicate();
111 if (Inst->getOperand(0) > Inst->getOperand(1)) {
112 std::swap(LHS, RHS);
113 Pred = CI->getSwappedPredicate();
114 }
115 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
116 }
117
118 if (CastInst *CI = dyn_cast<CastInst>(Inst))
119 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
120
121 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
122 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
123 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
124
125 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
126 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
127 IVI->getOperand(1),
128 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
129
130 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
131 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
132 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000133 isa<ShuffleVectorInst>(Inst)) &&
134 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000135
Chris Lattner02a97762011-01-03 01:10:08 +0000136 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000137 return hash_combine(
138 Inst->getOpcode(),
139 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000140}
141
Chris Lattner79d83062011-01-03 02:20:48 +0000142bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000143 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
144
145 if (LHS.isSentinel() || RHS.isSentinel())
146 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000147
Chandler Carruth7253bba2015-01-24 11:33:55 +0000148 if (LHSI->getOpcode() != RHSI->getOpcode())
149 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000150 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000151 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000152
153 // If we're not strictly identical, we still might be a commutable instruction
154 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
155 if (!LHSBinOp->isCommutative())
156 return false;
157
Chandler Carruth7253bba2015-01-24 11:33:55 +0000158 assert(isa<BinaryOperator>(RHSI) &&
159 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000160 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
161
Michael Ilseman336cb792012-10-09 16:57:38 +0000162 // Commuted equality
163 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000164 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000165 }
166 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000167 assert(isa<CmpInst>(RHSI) &&
168 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000169 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
170 // Commuted equality
171 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000172 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
173 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000174 }
175
176 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000177}
178
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000179//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000180// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000181//===----------------------------------------------------------------------===//
182
183namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000184/// \brief Struct representing the available call values in the scoped hash
185/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000186struct CallValue {
187 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000188
Chandler Carruth7253bba2015-01-24 11:33:55 +0000189 CallValue(Instruction *I) : Inst(I) {
190 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
191 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000192
Chandler Carruth7253bba2015-01-24 11:33:55 +0000193 bool isSentinel() const {
194 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
195 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
196 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000197
Chandler Carruth7253bba2015-01-24 11:33:55 +0000198 static bool canHandle(Instruction *Inst) {
199 // Don't value number anything that returns void.
200 if (Inst->getType()->isVoidTy())
201 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000202
Chandler Carruth7253bba2015-01-24 11:33:55 +0000203 CallInst *CI = dyn_cast<CallInst>(Inst);
204 if (!CI || !CI->onlyReadsMemory())
205 return false;
206 return true;
207 }
208};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000209}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000210
211namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000212template <> struct DenseMapInfo<CallValue> {
213 static inline CallValue getEmptyKey() {
214 return DenseMapInfo<Instruction *>::getEmptyKey();
215 }
216 static inline CallValue getTombstoneKey() {
217 return DenseMapInfo<Instruction *>::getTombstoneKey();
218 }
219 static unsigned getHashValue(CallValue Val);
220 static bool isEqual(CallValue LHS, CallValue RHS);
221};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000223
Chris Lattner92bb0f92011-01-03 03:41:27 +0000224unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000225 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000226 // Hash all of the operands as pointers and mix in the opcode.
227 return hash_combine(
228 Inst->getOpcode(),
229 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000230}
231
Chris Lattner92bb0f92011-01-03 03:41:27 +0000232bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000233 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000234 if (LHS.isSentinel() || RHS.isSentinel())
235 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000236 return LHSI->isIdenticalTo(RHSI);
237}
238
Chris Lattner79d83062011-01-03 02:20:48 +0000239//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000240// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000241//===----------------------------------------------------------------------===//
242
Chris Lattner18ae5432011-01-02 23:04:14 +0000243namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000244/// \brief A simple and fast domtree-based CSE pass.
245///
246/// This pass does a simple depth-first walk over the dominator tree,
247/// eliminating trivially redundant instructions and using instsimplify to
248/// canonicalize things as it goes. It is intended to be fast and catch obvious
249/// cases so that instcombine and other passes are more effective. It is
250/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000251class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000252public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000253 const TargetLibraryInfo &TLI;
254 const TargetTransformInfo &TTI;
255 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000256 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000257 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000258 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000259 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000260 typedef RecyclingAllocator<
261 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
262 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000263 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000264
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000265 /// \brief A scoped hash table of the current values of all of our simple
266 /// scalar expressions.
267 ///
268 /// As we walk down the domtree, we look to see if instructions are in this:
269 /// if so, we replace them with what we find, otherwise we insert them so
270 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000271 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000272
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000273 /// A scoped hash table of the current values of previously encounted memory
274 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000275 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000276 /// This allows us to get efficient access to dominating loads or stores when
277 /// we have a fully redundant load. In addition to the most recent load, we
278 /// keep track of a generation count of the read, which is compared against
279 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000280 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000281 /// CSE loads with other loads that have no intervening store. Ordering
282 /// events (such as fences or atomic instructions) increment the generation
283 /// count as well; essentially, we model these as writes to all possible
284 /// locations. Note that atomic and/or volatile loads and stores can be
285 /// present the table; it is the responsibility of the consumer to inspect
286 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000287 struct LoadValue {
Philip Reames32b55182016-05-06 01:13:58 +0000288 Instruction *DefInst;
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000289 unsigned Generation;
290 int MatchingId;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000291 bool IsAtomic;
Sanjoy Das07c65212016-06-16 20:47:57 +0000292 bool IsInvariant;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000293 LoadValue()
Sanjoy Das07c65212016-06-16 20:47:57 +0000294 : DefInst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false),
295 IsInvariant(false) {}
Geoff Berry5ae272c2016-04-28 15:22:37 +0000296 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Sanjoy Das07c65212016-06-16 20:47:57 +0000297 bool IsAtomic, bool IsInvariant)
298 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
299 IsAtomic(IsAtomic), IsInvariant(IsInvariant) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000300 };
301 typedef RecyclingAllocator<BumpPtrAllocator,
302 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000303 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000304 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
305 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000306 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000307
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000308 /// \brief A scoped hash table of the current values of read-only call
309 /// values.
310 ///
311 /// It uses the same generation count as loads.
Geoff Berry2f64c202016-05-13 17:54:58 +0000312 typedef ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>
313 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.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000320 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
321 const TargetTransformInfo &TTI, DominatorTree &DT,
322 AssumptionCache &AC, MemorySSA *MSSA)
323 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000324 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)), CurrentGeneration(0) {
325 }
Chris Lattner704541b2011-01-02 21:47:05 +0000326
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000327 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000328
329private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000330 // Almost a POD, but needs to call the constructors for the scoped hash
331 // tables so that a new scope gets pushed on. These are RAII so that the
332 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000333 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000334 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000335 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
336 CallHTType &AvailableCalls)
337 : Scope(AvailableValues), LoadScope(AvailableLoads),
338 CallScope(AvailableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000339
Chandler Carruth7253bba2015-01-24 11:33:55 +0000340 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000341 NodeScope(const NodeScope &) = delete;
342 void operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000343
344 ScopedHTType::ScopeTy Scope;
345 LoadHTType::ScopeTy LoadScope;
346 CallHTType::ScopeTy CallScope;
347 };
348
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000349 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000350 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000351 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000352 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000353 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000354 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000355 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
356 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
Chandler Carruth7253bba2015-01-24 11:33:55 +0000357 DomTreeNode::iterator child, DomTreeNode::iterator end)
358 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000359 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000360 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000361
362 // Accessors.
363 unsigned currentGeneration() { return CurrentGeneration; }
364 unsigned childGeneration() { return ChildGeneration; }
365 void childGeneration(unsigned generation) { ChildGeneration = generation; }
366 DomTreeNode *node() { return Node; }
367 DomTreeNode::iterator childIter() { return ChildIter; }
368 DomTreeNode *nextChild() {
369 DomTreeNode *child = *ChildIter;
370 ++ChildIter;
371 return child;
372 }
373 DomTreeNode::iterator end() { return EndIter; }
374 bool isProcessed() { return Processed; }
375 void process() { Processed = true; }
376
Chandler Carruth7253bba2015-01-24 11:33:55 +0000377 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000378 StackNode(const StackNode &) = delete;
379 void operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000380
381 // Members.
382 unsigned CurrentGeneration;
383 unsigned ChildGeneration;
384 DomTreeNode *Node;
385 DomTreeNode::iterator ChildIter;
386 DomTreeNode::iterator EndIter;
387 NodeScope Scopes;
388 bool Processed;
389 };
390
Chad Rosierf9327d62015-01-26 22:51:15 +0000391 /// \brief Wrapper class to handle memory instructions, including loads,
392 /// stores and intrinsic loads and stores defined by the target.
393 class ParseMemoryInst {
394 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000395 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Philip Reames9e5e2d62015-12-07 22:41:23 +0000396 : IsTargetMemInst(false), Inst(Inst) {
397 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000398 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000399 IsTargetMemInst = true;
400 }
401 bool isLoad() const {
402 if (IsTargetMemInst) return Info.ReadMem;
403 return isa<LoadInst>(Inst);
404 }
405 bool isStore() const {
406 if (IsTargetMemInst) return Info.WriteMem;
407 return isa<StoreInst>(Inst);
408 }
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000409 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000410 if (IsTargetMemInst)
411 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000412 return Inst->isAtomic();
413 }
414 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000415 if (IsTargetMemInst)
416 return Info.isUnordered();
417
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000418 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 {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000428 if (IsTargetMemInst)
429 return Info.IsVolatile;
430
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000431 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
432 return LI->isVolatile();
433 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
434 return SI->isVolatile();
435 }
436 // Conservative answer
437 return true;
438 }
439
Sanjoy Das07c65212016-06-16 20:47:57 +0000440 bool isInvariantLoad() const {
441 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000442 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000443 return false;
444 }
Junmo Park80440eb2016-02-18 10:09:20 +0000445
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000446 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000447 return (getPointerOperand() == Inst.getPointerOperand() &&
448 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000449 }
Philip Reames9e5e2d62015-12-07 22:41:23 +0000450 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000451
Chad Rosierf9327d62015-01-26 22:51:15 +0000452 // For regular (non-intrinsic) loads/stores, this is set to -1. For
453 // intrinsic loads/stores, the id is retrieved from the corresponding
454 // field in the MemIntrinsicInfo structure. That field contains
455 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000456 int getMatchingId() const {
457 if (IsTargetMemInst) return Info.MatchingId;
458 return -1;
459 }
460 Value *getPointerOperand() const {
461 if (IsTargetMemInst) return Info.PtrVal;
462 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
463 return LI->getPointerOperand();
464 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
465 return SI->getPointerOperand();
466 }
467 return nullptr;
468 }
469 bool mayReadFromMemory() const {
470 if (IsTargetMemInst) return Info.ReadMem;
471 return Inst->mayReadFromMemory();
472 }
473 bool mayWriteToMemory() const {
474 if (IsTargetMemInst) return Info.WriteMem;
475 return Inst->mayWriteToMemory();
476 }
477
478 private:
479 bool IsTargetMemInst;
480 MemIntrinsicInfo Info;
481 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000482 };
483
Chris Lattner18ae5432011-01-02 23:04:14 +0000484 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000485
Chad Rosierf9327d62015-01-26 22:51:15 +0000486 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000487 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000488 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000489 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000490 return SI->getValueOperand();
491 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000492 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
493 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000494 }
Geoff Berry8d846052016-08-31 19:24:10 +0000495
496 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
497 Instruction *EarlierInst, Instruction *LaterInst);
498
499 void removeMSSA(Instruction *Inst) {
500 if (!MSSA)
501 return;
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000502 // Removing a store here can leave MemorySSA in an unoptimized state by
503 // creating MemoryPhis that have identical arguments and by creating
Geoff Berry68154682016-10-24 15:54:00 +0000504 // MemoryUses whose defining access is not an actual clobber. We handle the
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000505 // phi case eagerly here. The non-optimized MemoryUse case is lazily
506 // updated by MemorySSA getClobberingMemoryAccess.
Geoff Berry68154682016-10-24 15:54:00 +0000507 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst)) {
508 // Optimize MemoryPhi nodes that may become redundant by having all the
509 // same input values once MA is removed.
Davide Italiano0dc47782017-06-14 19:29:53 +0000510 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
Geoff Berry68154682016-10-24 15:54:00 +0000511 SmallVector<MemoryAccess *, 8> WorkQueue;
512 WorkQueue.push_back(MA);
513 // Process MemoryPhi nodes in FIFO order using a ever-growing vector since
514 // we shouldn't be processing that many phis and this will avoid an
515 // allocation in almost all cases.
516 for (unsigned I = 0; I < WorkQueue.size(); ++I) {
517 MemoryAccess *WI = WorkQueue[I];
518
519 for (auto *U : WI->users())
520 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U))
Davide Italiano0dc47782017-06-14 19:29:53 +0000521 PhisToCheck.insert(MP);
Geoff Berry68154682016-10-24 15:54:00 +0000522
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000523 MSSAUpdater->removeMemoryAccess(WI);
Geoff Berry68154682016-10-24 15:54:00 +0000524
525 for (MemoryPhi *MP : PhisToCheck) {
526 MemoryAccess *FirstIn = MP->getIncomingValue(0);
527 if (all_of(MP->incoming_values(),
528 [=](Use &In) { return In == FirstIn; }))
529 WorkQueue.push_back(MP);
530 }
531 PhisToCheck.clear();
532 }
533 }
Geoff Berry8d846052016-08-31 19:24:10 +0000534 }
Chris Lattner704541b2011-01-02 21:47:05 +0000535};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000536}
Chris Lattner704541b2011-01-02 21:47:05 +0000537
Geoff Berry68154682016-10-24 15:54:00 +0000538/// Determine if the memory referenced by LaterInst is from the same heap
539/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000540/// This is currently called in two scenarios:
541///
542/// load p
543/// ...
544/// load p
545///
546/// and
547///
548/// x = load p
549/// ...
550/// store x, p
551///
552/// in both cases we want to verify that there are no possible writes to the
553/// memory referenced by p between the earlier and later instruction.
554bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
555 unsigned LaterGeneration,
556 Instruction *EarlierInst,
557 Instruction *LaterInst) {
558 // Check the simple memory generation tracking first.
559 if (EarlierGeneration == LaterGeneration)
560 return true;
561
562 if (!MSSA)
563 return false;
564
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000565 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
566 // read/write memory, then we can safely return true here.
567 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
568 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
569 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
570 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
571 // with the default optimization pipeline.
572 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
573 if (!EarlierMA)
574 return true;
575 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
576 if (!LaterMA)
577 return true;
578
Geoff Berry8d846052016-08-31 19:24:10 +0000579 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
580 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
581 // EarlierInst and LaterInst and neither can any other write that potentially
582 // clobbers LaterInst.
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000583 MemoryAccess *LaterDef =
584 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000585 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000586}
587
Chris Lattner18ae5432011-01-02 23:04:14 +0000588bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000589 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000590 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000591
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000592 // If this block has a single predecessor, then the predecessor is the parent
593 // of the domtree node and all of the live out memory values are still current
594 // in this block. If this block has multiple predecessors, then they could
595 // have invalidated the live-out memory values of our parent value. For now,
596 // just be conservative and invalidate memory if this block has multiple
597 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000598 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000599 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000600
Philip Reames7c78ef72015-05-22 23:53:24 +0000601 // If this node has a single predecessor which ends in a conditional branch,
602 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000603 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000604 // which reaches this block where the condition might hold a different
605 // value. Since we're adding this to the scoped hash table (like any other
606 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000607 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
608 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
609 if (BI && BI->isConditional()) {
610 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
611 if (CondInst && SimpleValue::canHandle(CondInst)) {
612 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
613 auto *TorF = (BI->getSuccessor(0) == BB)
614 ? ConstantInt::getTrue(BB->getContext())
615 : ConstantInt::getFalse(BB->getContext());
616 AvailableValues.insert(CondInst, TorF);
617 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
618 << CondInst->getName() << "' as " << *TorF << " in "
619 << BB->getName() << "\n");
620 // Replace all dominated uses with the known value.
621 if (unsigned Count = replaceDominatedUsesWith(
622 CondInst, TorF, DT, BasicBlockEdge(Pred, BB))) {
623 Changed = true;
Craig Topper48187cf2017-05-17 23:22:10 +0000624 NumCSECVP += Count;
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000625 }
626 }
627 }
628 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000629
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000630 /// LastStore - Keep track of the last non-volatile store that we saw... for
631 /// as long as there in no instruction that reads memory. If we see a store
632 /// to the same location, we delete the dead store. This zaps trivial dead
633 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000634 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000635
Chris Lattner18ae5432011-01-02 23:04:14 +0000636 // See if any instructions in the block can be eliminated. If so, do it. If
637 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000638 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000639 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000640
Chris Lattner18ae5432011-01-02 23:04:14 +0000641 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000642 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000643 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000644 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000645 Inst->eraseFromParent();
646 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000647 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000648 continue;
649 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000650
Hal Finkel1e16fa32014-11-03 20:21:32 +0000651 // Skip assume intrinsics, they don't really have side effects (although
652 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000653 // and this pass will not bother with its removal. However, we should mark
654 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000655 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000656 auto *CondI =
657 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
658 if (CondI && SimpleValue::canHandle(CondI)) {
659 DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst << '\n');
660 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
661 } else
662 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000663 continue;
664 }
665
Anna Thomasb2d12b82016-08-09 20:00:47 +0000666 // Skip invariant.start intrinsics since they only read memory, and we can
667 // forward values across it. Also, we dont need to consume the last store
668 // since the semantics of invariant.start allow us to perform DSE of the
669 // last store, if there was a store following invariant.start. Consider:
670 //
671 // store 30, i8* p
672 // invariant.start(p)
673 // store 40, i8* p
674 // We can DSE the store to 30, since the store 40 to invariant location p
675 // causes undefined behaviour.
676 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>()))
677 continue;
678
Sanjoy Dasee81b232016-04-29 21:52:58 +0000679 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000680 if (auto *CondI =
681 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000682 if (SimpleValue::canHandle(CondI)) {
683 // Do we already know the actual value of this condition?
684 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
685 // Is the condition known to be true?
686 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000687 cast<ConstantInt>(KnownCond)->isOne()) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000688 DEBUG(dbgs() << "EarlyCSE removing guard: " << *Inst << '\n');
689 removeMSSA(Inst);
690 Inst->eraseFromParent();
691 Changed = true;
692 continue;
693 } else
694 // Use the known value if it wasn't true.
695 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
696 }
697 // The condition we're on guarding here is true for all dominated
698 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000699 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000700 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000701 }
702
703 // Guard intrinsics read all memory, but don't write any memory.
704 // Accordingly, don't update the generation but consume the last store (to
705 // avoid an incorrect DSE).
706 LastStore = nullptr;
707 continue;
708 }
709
Chris Lattner18ae5432011-01-02 23:04:14 +0000710 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
711 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000712 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000713 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
David Majnemer130b9f92016-07-29 05:39:21 +0000714 bool Killed = false;
David Majnemerb8da3a22016-06-25 00:04:10 +0000715 if (!Inst->use_empty()) {
716 Inst->replaceAllUsesWith(V);
717 Changed = true;
718 }
719 if (isInstructionTriviallyDead(Inst, &TLI)) {
Geoff Berry8d846052016-08-31 19:24:10 +0000720 removeMSSA(Inst);
David Majnemerb8da3a22016-06-25 00:04:10 +0000721 Inst->eraseFromParent();
722 Changed = true;
David Majnemer130b9f92016-07-29 05:39:21 +0000723 Killed = true;
David Majnemerb8da3a22016-06-25 00:04:10 +0000724 }
David Majnemer130b9f92016-07-29 05:39:21 +0000725 if (Changed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000726 ++NumSimplify;
David Majnemer130b9f92016-07-29 05:39:21 +0000727 if (Killed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000728 continue;
Chris Lattner18ae5432011-01-02 23:04:14 +0000729 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000730
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000731 // If this is a simple instruction that we can value number, process it.
732 if (SimpleValue::canHandle(Inst)) {
733 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000734 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000735 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000736 if (auto *I = dyn_cast<Instruction>(V))
737 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000738 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000739 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000740 Inst->eraseFromParent();
741 Changed = true;
742 ++NumCSE;
743 continue;
744 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000745
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000746 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000747 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000748 continue;
749 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000750
Chad Rosierf9327d62015-01-26 22:51:15 +0000751 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000752 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000753 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000754 // (conservatively) we can't peak past the ordering implied by this
755 // operation, but we can add this load to our set of available values
756 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000757 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000758 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000759 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000760
Chris Lattner92bb0f92011-01-03 03:41:27 +0000761 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000762 // generation or the load is known to be from an invariant location,
763 // replace this instruction.
764 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000765 // If either the dominating load or the current load are invariant, then
766 // we can assume the current load loads the same value as the dominating
767 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000768 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000769 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000770 InVal.MatchingId == MemInst.getMatchingId() &&
771 // We don't yet handle removing loads with ordering of any kind.
772 !MemInst.isVolatile() && MemInst.isUnordered() &&
773 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000774 InVal.IsAtomic >= MemInst.isAtomic() &&
775 (InVal.IsInvariant || MemInst.isInvariantLoad() ||
776 isSameMemGeneration(InVal.Generation, CurrentGeneration,
777 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000778 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000779 if (Op != nullptr) {
780 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Philip Reames32b55182016-05-06 01:13:58 +0000781 << " to: " << *InVal.DefInst << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000782 if (!Inst->use_empty())
783 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +0000784 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +0000785 Inst->eraseFromParent();
786 Changed = true;
787 ++NumCSELoad;
788 continue;
789 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000790 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000791
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000792 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000793 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000794 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000795 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das07c65212016-06-16 20:47:57 +0000796 MemInst.isAtomic(), MemInst.isInvariantLoad()));
Craig Topperf40110f2014-04-25 05:29:35 +0000797 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000798 continue;
799 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000800
Sanjoy Das6de072a2017-01-17 20:15:47 +0000801 // If this instruction may read from memory or throw (and potentially read
802 // from memory in the exception handler), forget LastStore. Load/store
803 // intrinsics will indicate both a read and a write to memory. The target
804 // may override this (e.g. so that a store intrinsic does not read from
805 // memory, and thus will be treated the same as a regular store for
806 // commoning purposes).
807 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +0000808 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000809 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000810
Chris Lattner92bb0f92011-01-03 03:41:27 +0000811 // If this is a read-only call, process it.
812 if (CallValue::canHandle(Inst)) {
813 // If we have an available version of this call, and if it is the right
814 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +0000815 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000816 if (InVal.first != nullptr &&
817 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
818 Inst)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000819 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
820 << " to: " << *InVal.first << '\n');
821 if (!Inst->use_empty())
822 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +0000823 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000824 Inst->eraseFromParent();
825 Changed = true;
826 ++NumCSECall;
827 continue;
828 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000829
Chris Lattner92bb0f92011-01-03 03:41:27 +0000830 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000831 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +0000832 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000833 continue;
834 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000835
Philip Reamesdfd890d2015-08-27 01:32:33 +0000836 // A release fence requires that all stores complete before it, but does
837 // not prevent the reordering of following loads 'before' the fence. As a
838 // result, we don't need to consider it as writing to memory and don't need
839 // to advance the generation. We do need to prevent DSE across the fence,
840 // but that's handled above.
841 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000842 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000843 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
844 continue;
845 }
846
Philip Reamesae1f265b2015-12-16 01:01:30 +0000847 // write back DSE - If we write back the same value we just loaded from
848 // the same location and haven't passed any intervening writes or ordering
849 // operations, we can remove the write. The primary benefit is in allowing
850 // the available load table to remain valid and value forward past where
851 // the store originally was.
852 if (MemInst.isValid() && MemInst.isStore()) {
853 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +0000854 if (InVal.DefInst &&
855 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +0000856 InVal.MatchingId == MemInst.getMatchingId() &&
857 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +0000858 !MemInst.isVolatile() && MemInst.isUnordered() &&
859 isSameMemGeneration(InVal.Generation, CurrentGeneration,
860 InVal.DefInst, Inst)) {
861 // It is okay to have a LastStore to a different pointer here if MemorySSA
862 // tells us that the load and store are from the same memory generation.
863 // In that case, LastStore should keep its present value since we're
864 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +0000865 assert((!LastStore ||
866 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +0000867 MemInst.getPointerOperand() ||
868 MSSA) &&
869 "can't have an intervening store if not using MemorySSA!");
Philip Reamesae1f265b2015-12-16 01:01:30 +0000870 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000871 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +0000872 Inst->eraseFromParent();
873 Changed = true;
874 ++NumDSE;
875 // We can avoid incrementing the generation count since we were able
876 // to eliminate this store.
877 continue;
878 }
879 }
880
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000881 // Okay, this isn't something we can CSE at all. Check to see if it is
882 // something that could modify memory. If so, our available memory values
883 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000884 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000885 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000886
Chad Rosierf9327d62015-01-26 22:51:15 +0000887 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000888 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000889 // location with no intervening loads. Delete the earlier store.
890 // At the moment, we don't remove ordered stores, but do remove
891 // unordered atomic stores. There's no special requirement (for
892 // unordered atomics) about removing atomic stores only in favor of
893 // other atomic stores since we we're going to execute the non-atomic
894 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000895 if (LastStore) {
896 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000897 assert(LastStoreMemInst.isUnordered() &&
898 !LastStoreMemInst.isVolatile() &&
899 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000900 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
901 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
902 << " due to: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000903 removeMSSA(LastStore);
Chad Rosierf9327d62015-01-26 22:51:15 +0000904 LastStore->eraseFromParent();
905 Changed = true;
906 ++NumDSE;
907 LastStore = nullptr;
908 }
Philip Reames018dbf12014-11-18 17:46:32 +0000909 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000910 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000911
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000912 // Okay, we just invalidated anything we knew about loaded values. Try
913 // to salvage *something* by remembering that the stored value is a live
914 // version of the pointer. It is safe to forward from volatile stores
915 // to non-volatile loads, so we don't have to check for volatility of
916 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000917 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000918 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000919 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000920 MemInst.isAtomic(), /*IsInvariant=*/false));
Nadav Rotem465834c2012-07-24 10:51:42 +0000921
Philip Reames15145fb2015-12-17 18:50:50 +0000922 // Remember that this was the last unordered store we saw for DSE. We
923 // don't yet handle DSE on ordered or volatile stores since we don't
924 // have a good way to model the ordering requirement for following
925 // passes once the store is removed. We could insert a fence, but
926 // since fences are slightly stronger than stores in their ordering,
927 // it's not clear this is a profitable transform. Another option would
928 // be to merge the ordering with that of the post dominating store.
929 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000930 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000931 else
932 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000933 }
934 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000935 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000936
Chris Lattner18ae5432011-01-02 23:04:14 +0000937 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000938}
Chris Lattner18ae5432011-01-02 23:04:14 +0000939
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000940bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000941 // Note, deque is being used here because there is significant performance
942 // gains over vector when the container becomes very large due to the
943 // specific access patterns. For more information see the mailing list
944 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000945 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000946 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000947
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000948 bool Changed = false;
949
950 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000951 nodesToProcess.push_back(new StackNode(
952 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000953 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000954
955 // Save the current generation.
956 unsigned LiveOutGeneration = CurrentGeneration;
957
958 // Process the stack.
959 while (!nodesToProcess.empty()) {
960 // Grab the first item off the stack. Set the current generation, remove
961 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000962 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000963
964 // Initialize class members.
965 CurrentGeneration = NodeToProcess->currentGeneration();
966
967 // Check if the node needs to be processed.
968 if (!NodeToProcess->isProcessed()) {
969 // Process the node.
970 Changed |= processNode(NodeToProcess->node());
971 NodeToProcess->childGeneration(CurrentGeneration);
972 NodeToProcess->process();
973 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
974 // Push the next child onto the stack.
975 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000976 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000977 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
978 NodeToProcess->childGeneration(), child, child->begin(),
979 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000980 } else {
981 // It has been processed, and there are no more children to process,
982 // so delete it and pop it off the stack.
983 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000984 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000985 }
986 } // while (!nodes...)
987
988 // Reset the current generation.
989 CurrentGeneration = LiveOutGeneration;
990
991 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000992}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000993
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000994PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000995 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000996 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
997 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
998 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000999 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001000 auto *MSSA =
1001 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001002
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001003 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001004
1005 if (!CSE.run())
1006 return PreservedAnalyses::all();
1007
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001008 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001009 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001010 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001011 if (UseMemorySSA)
1012 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001013 return PA;
1014}
1015
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001016namespace {
1017/// \brief A simple and fast domtree-based CSE pass.
1018///
1019/// This pass does a simple depth-first walk over the dominator tree,
1020/// eliminating trivially redundant instructions and using instsimplify to
1021/// canonicalize things as it goes. It is intended to be fast and catch obvious
1022/// cases so that instcombine and other passes are more effective. It is
1023/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001024template<bool UseMemorySSA>
1025class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001026public:
1027 static char ID;
1028
Geoff Berry8d846052016-08-31 19:24:10 +00001029 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1030 if (UseMemorySSA)
1031 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1032 else
1033 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001034 }
1035
1036 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001037 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001038 return false;
1039
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001040 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001041 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001042 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001043 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001044 auto *MSSA =
1045 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001046
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001047 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001048
1049 return CSE.run();
1050 }
1051
1052 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001053 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001054 AU.addRequired<DominatorTreeWrapperPass>();
1055 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001056 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001057 if (UseMemorySSA) {
1058 AU.addRequired<MemorySSAWrapperPass>();
1059 AU.addPreserved<MemorySSAWrapperPass>();
1060 }
James Molloyefbba722015-09-10 10:22:12 +00001061 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001062 AU.setPreservesCFG();
1063 }
1064};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001065}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001066
Geoff Berry8d846052016-08-31 19:24:10 +00001067using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001068
Geoff Berry8d846052016-08-31 19:24:10 +00001069template<>
1070char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001071
1072INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1073 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001074INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001075INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001076INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1077INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1078INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001079
1080using EarlyCSEMemSSALegacyPass =
1081 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1082
1083template<>
1084char EarlyCSEMemSSALegacyPass::ID = 0;
1085
1086FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1087 if (UseMemorySSA)
1088 return new EarlyCSEMemSSALegacyPass();
1089 else
1090 return new EarlyCSELegacyPass();
1091}
1092
1093INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1094 "Early CSE w/ MemorySSA", false, false)
1095INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001096INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001097INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1098INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1099INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1100INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1101 "Early CSE w/ MemorySSA", false, false)