blob: 7fd77a082b822e5ad134451bd4e70c363783b915 [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
565 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
566 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
567 // EarlierInst and LaterInst and neither can any other write that potentially
568 // clobbers LaterInst.
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000569 MemoryAccess *LaterDef =
570 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
Geoff Berry8d846052016-08-31 19:24:10 +0000571 return MSSA->dominates(LaterDef, MSSA->getMemoryAccess(EarlierInst));
572}
573
Chris Lattner18ae5432011-01-02 23:04:14 +0000574bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000575 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000576 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000577
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000578 // If this block has a single predecessor, then the predecessor is the parent
579 // of the domtree node and all of the live out memory values are still current
580 // in this block. If this block has multiple predecessors, then they could
581 // have invalidated the live-out memory values of our parent value. For now,
582 // just be conservative and invalidate memory if this block has multiple
583 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000584 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000585 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000586
Philip Reames7c78ef72015-05-22 23:53:24 +0000587 // If this node has a single predecessor which ends in a conditional branch,
588 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000589 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000590 // which reaches this block where the condition might hold a different
591 // value. Since we're adding this to the scoped hash table (like any other
592 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000593 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
594 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
595 if (BI && BI->isConditional()) {
596 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
597 if (CondInst && SimpleValue::canHandle(CondInst)) {
598 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
599 auto *TorF = (BI->getSuccessor(0) == BB)
600 ? ConstantInt::getTrue(BB->getContext())
601 : ConstantInt::getFalse(BB->getContext());
602 AvailableValues.insert(CondInst, TorF);
603 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
604 << CondInst->getName() << "' as " << *TorF << " in "
605 << BB->getName() << "\n");
606 // Replace all dominated uses with the known value.
607 if (unsigned Count = replaceDominatedUsesWith(
608 CondInst, TorF, DT, BasicBlockEdge(Pred, BB))) {
609 Changed = true;
Craig Topper48187cf2017-05-17 23:22:10 +0000610 NumCSECVP += Count;
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000611 }
612 }
613 }
614 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000615
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000616 /// LastStore - Keep track of the last non-volatile store that we saw... for
617 /// as long as there in no instruction that reads memory. If we see a store
618 /// to the same location, we delete the dead store. This zaps trivial dead
619 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000620 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000621
Chris Lattner18ae5432011-01-02 23:04:14 +0000622 // See if any instructions in the block can be eliminated. If so, do it. If
623 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000624 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000625 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000626
Chris Lattner18ae5432011-01-02 23:04:14 +0000627 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000628 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000629 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000630 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000631 Inst->eraseFromParent();
632 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000633 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000634 continue;
635 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000636
Hal Finkel1e16fa32014-11-03 20:21:32 +0000637 // Skip assume intrinsics, they don't really have side effects (although
638 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000639 // and this pass will not bother with its removal. However, we should mark
640 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000641 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000642 auto *CondI =
643 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
644 if (CondI && SimpleValue::canHandle(CondI)) {
645 DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst << '\n');
646 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
647 } else
648 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000649 continue;
650 }
651
Anna Thomasb2d12b82016-08-09 20:00:47 +0000652 // Skip invariant.start intrinsics since they only read memory, and we can
653 // forward values across it. Also, we dont need to consume the last store
654 // since the semantics of invariant.start allow us to perform DSE of the
655 // last store, if there was a store following invariant.start. Consider:
656 //
657 // store 30, i8* p
658 // invariant.start(p)
659 // store 40, i8* p
660 // We can DSE the store to 30, since the store 40 to invariant location p
661 // causes undefined behaviour.
662 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>()))
663 continue;
664
Sanjoy Dasee81b232016-04-29 21:52:58 +0000665 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000666 if (auto *CondI =
667 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000668 if (SimpleValue::canHandle(CondI)) {
669 // Do we already know the actual value of this condition?
670 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
671 // Is the condition known to be true?
672 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000673 cast<ConstantInt>(KnownCond)->isOne()) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000674 DEBUG(dbgs() << "EarlyCSE removing guard: " << *Inst << '\n');
675 removeMSSA(Inst);
676 Inst->eraseFromParent();
677 Changed = true;
678 continue;
679 } else
680 // Use the known value if it wasn't true.
681 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
682 }
683 // The condition we're on guarding here is true for all dominated
684 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000685 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000686 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000687 }
688
689 // Guard intrinsics read all memory, but don't write any memory.
690 // Accordingly, don't update the generation but consume the last store (to
691 // avoid an incorrect DSE).
692 LastStore = nullptr;
693 continue;
694 }
695
Chris Lattner18ae5432011-01-02 23:04:14 +0000696 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
697 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000698 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000699 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
David Majnemer130b9f92016-07-29 05:39:21 +0000700 bool Killed = false;
David Majnemerb8da3a22016-06-25 00:04:10 +0000701 if (!Inst->use_empty()) {
702 Inst->replaceAllUsesWith(V);
703 Changed = true;
704 }
705 if (isInstructionTriviallyDead(Inst, &TLI)) {
Geoff Berry8d846052016-08-31 19:24:10 +0000706 removeMSSA(Inst);
David Majnemerb8da3a22016-06-25 00:04:10 +0000707 Inst->eraseFromParent();
708 Changed = true;
David Majnemer130b9f92016-07-29 05:39:21 +0000709 Killed = true;
David Majnemerb8da3a22016-06-25 00:04:10 +0000710 }
David Majnemer130b9f92016-07-29 05:39:21 +0000711 if (Changed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000712 ++NumSimplify;
David Majnemer130b9f92016-07-29 05:39:21 +0000713 if (Killed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000714 continue;
Chris Lattner18ae5432011-01-02 23:04:14 +0000715 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000716
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000717 // If this is a simple instruction that we can value number, process it.
718 if (SimpleValue::canHandle(Inst)) {
719 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000720 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000721 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000722 if (auto *I = dyn_cast<Instruction>(V))
723 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000724 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000725 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000726 Inst->eraseFromParent();
727 Changed = true;
728 ++NumCSE;
729 continue;
730 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000731
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000732 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000733 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000734 continue;
735 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000736
Chad Rosierf9327d62015-01-26 22:51:15 +0000737 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000738 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000739 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000740 // (conservatively) we can't peak past the ordering implied by this
741 // operation, but we can add this load to our set of available values
742 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000743 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000744 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000745 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000746
Chris Lattner92bb0f92011-01-03 03:41:27 +0000747 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000748 // generation or the load is known to be from an invariant location,
749 // replace this instruction.
750 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000751 // If either the dominating load or the current load are invariant, then
752 // we can assume the current load loads the same value as the dominating
753 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000754 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000755 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000756 InVal.MatchingId == MemInst.getMatchingId() &&
757 // We don't yet handle removing loads with ordering of any kind.
758 !MemInst.isVolatile() && MemInst.isUnordered() &&
759 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000760 InVal.IsAtomic >= MemInst.isAtomic() &&
761 (InVal.IsInvariant || MemInst.isInvariantLoad() ||
762 isSameMemGeneration(InVal.Generation, CurrentGeneration,
763 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000764 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000765 if (Op != nullptr) {
766 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Philip Reames32b55182016-05-06 01:13:58 +0000767 << " to: " << *InVal.DefInst << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000768 if (!Inst->use_empty())
769 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +0000770 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +0000771 Inst->eraseFromParent();
772 Changed = true;
773 ++NumCSELoad;
774 continue;
775 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000776 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000777
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000778 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000779 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000780 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000781 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das07c65212016-06-16 20:47:57 +0000782 MemInst.isAtomic(), MemInst.isInvariantLoad()));
Craig Topperf40110f2014-04-25 05:29:35 +0000783 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000784 continue;
785 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000786
Sanjoy Das6de072a2017-01-17 20:15:47 +0000787 // If this instruction may read from memory or throw (and potentially read
788 // from memory in the exception handler), forget LastStore. Load/store
789 // intrinsics will indicate both a read and a write to memory. The target
790 // may override this (e.g. so that a store intrinsic does not read from
791 // memory, and thus will be treated the same as a regular store for
792 // commoning purposes).
793 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +0000794 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000795 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000796
Chris Lattner92bb0f92011-01-03 03:41:27 +0000797 // If this is a read-only call, process it.
798 if (CallValue::canHandle(Inst)) {
799 // If we have an available version of this call, and if it is the right
800 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +0000801 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000802 if (InVal.first != nullptr &&
803 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
804 Inst)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000805 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
806 << " to: " << *InVal.first << '\n');
807 if (!Inst->use_empty())
808 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +0000809 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000810 Inst->eraseFromParent();
811 Changed = true;
812 ++NumCSECall;
813 continue;
814 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000815
Chris Lattner92bb0f92011-01-03 03:41:27 +0000816 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000817 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +0000818 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000819 continue;
820 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000821
Philip Reamesdfd890d2015-08-27 01:32:33 +0000822 // A release fence requires that all stores complete before it, but does
823 // not prevent the reordering of following loads 'before' the fence. As a
824 // result, we don't need to consider it as writing to memory and don't need
825 // to advance the generation. We do need to prevent DSE across the fence,
826 // but that's handled above.
827 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000828 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000829 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
830 continue;
831 }
832
Philip Reamesae1f265b2015-12-16 01:01:30 +0000833 // write back DSE - If we write back the same value we just loaded from
834 // the same location and haven't passed any intervening writes or ordering
835 // operations, we can remove the write. The primary benefit is in allowing
836 // the available load table to remain valid and value forward past where
837 // the store originally was.
838 if (MemInst.isValid() && MemInst.isStore()) {
839 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +0000840 if (InVal.DefInst &&
841 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +0000842 InVal.MatchingId == MemInst.getMatchingId() &&
843 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +0000844 !MemInst.isVolatile() && MemInst.isUnordered() &&
845 isSameMemGeneration(InVal.Generation, CurrentGeneration,
846 InVal.DefInst, Inst)) {
847 // It is okay to have a LastStore to a different pointer here if MemorySSA
848 // tells us that the load and store are from the same memory generation.
849 // In that case, LastStore should keep its present value since we're
850 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +0000851 assert((!LastStore ||
852 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +0000853 MemInst.getPointerOperand() ||
854 MSSA) &&
855 "can't have an intervening store if not using MemorySSA!");
Philip Reamesae1f265b2015-12-16 01:01:30 +0000856 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000857 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +0000858 Inst->eraseFromParent();
859 Changed = true;
860 ++NumDSE;
861 // We can avoid incrementing the generation count since we were able
862 // to eliminate this store.
863 continue;
864 }
865 }
866
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000867 // Okay, this isn't something we can CSE at all. Check to see if it is
868 // something that could modify memory. If so, our available memory values
869 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000870 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000871 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000872
Chad Rosierf9327d62015-01-26 22:51:15 +0000873 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000874 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000875 // location with no intervening loads. Delete the earlier store.
876 // At the moment, we don't remove ordered stores, but do remove
877 // unordered atomic stores. There's no special requirement (for
878 // unordered atomics) about removing atomic stores only in favor of
879 // other atomic stores since we we're going to execute the non-atomic
880 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000881 if (LastStore) {
882 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000883 assert(LastStoreMemInst.isUnordered() &&
884 !LastStoreMemInst.isVolatile() &&
885 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000886 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
887 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
888 << " due to: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000889 removeMSSA(LastStore);
Chad Rosierf9327d62015-01-26 22:51:15 +0000890 LastStore->eraseFromParent();
891 Changed = true;
892 ++NumDSE;
893 LastStore = nullptr;
894 }
Philip Reames018dbf12014-11-18 17:46:32 +0000895 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000896 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000897
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000898 // Okay, we just invalidated anything we knew about loaded values. Try
899 // to salvage *something* by remembering that the stored value is a live
900 // version of the pointer. It is safe to forward from volatile stores
901 // to non-volatile loads, so we don't have to check for volatility of
902 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000903 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000904 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000905 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000906 MemInst.isAtomic(), /*IsInvariant=*/false));
Nadav Rotem465834c2012-07-24 10:51:42 +0000907
Philip Reames15145fb2015-12-17 18:50:50 +0000908 // Remember that this was the last unordered store we saw for DSE. We
909 // don't yet handle DSE on ordered or volatile stores since we don't
910 // have a good way to model the ordering requirement for following
911 // passes once the store is removed. We could insert a fence, but
912 // since fences are slightly stronger than stores in their ordering,
913 // it's not clear this is a profitable transform. Another option would
914 // be to merge the ordering with that of the post dominating store.
915 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000916 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000917 else
918 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000919 }
920 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000921 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000922
Chris Lattner18ae5432011-01-02 23:04:14 +0000923 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000924}
Chris Lattner18ae5432011-01-02 23:04:14 +0000925
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000926bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000927 // Note, deque is being used here because there is significant performance
928 // gains over vector when the container becomes very large due to the
929 // specific access patterns. For more information see the mailing list
930 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000931 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000932 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000933
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000934 bool Changed = false;
935
936 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000937 nodesToProcess.push_back(new StackNode(
938 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000939 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000940
941 // Save the current generation.
942 unsigned LiveOutGeneration = CurrentGeneration;
943
944 // Process the stack.
945 while (!nodesToProcess.empty()) {
946 // Grab the first item off the stack. Set the current generation, remove
947 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000948 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000949
950 // Initialize class members.
951 CurrentGeneration = NodeToProcess->currentGeneration();
952
953 // Check if the node needs to be processed.
954 if (!NodeToProcess->isProcessed()) {
955 // Process the node.
956 Changed |= processNode(NodeToProcess->node());
957 NodeToProcess->childGeneration(CurrentGeneration);
958 NodeToProcess->process();
959 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
960 // Push the next child onto the stack.
961 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000962 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000963 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
964 NodeToProcess->childGeneration(), child, child->begin(),
965 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000966 } else {
967 // It has been processed, and there are no more children to process,
968 // so delete it and pop it off the stack.
969 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000970 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000971 }
972 } // while (!nodes...)
973
974 // Reset the current generation.
975 CurrentGeneration = LiveOutGeneration;
976
977 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000978}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000979
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000980PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000981 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000982 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
983 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
984 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000985 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +0000986 auto *MSSA =
987 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000988
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000989 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000990
991 if (!CSE.run())
992 return PreservedAnalyses::all();
993
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000994 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000995 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +0000996 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +0000997 if (UseMemorySSA)
998 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000999 return PA;
1000}
1001
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001002namespace {
1003/// \brief A simple and fast domtree-based CSE pass.
1004///
1005/// This pass does a simple depth-first walk over the dominator tree,
1006/// eliminating trivially redundant instructions and using instsimplify to
1007/// canonicalize things as it goes. It is intended to be fast and catch obvious
1008/// cases so that instcombine and other passes are more effective. It is
1009/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001010template<bool UseMemorySSA>
1011class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001012public:
1013 static char ID;
1014
Geoff Berry8d846052016-08-31 19:24:10 +00001015 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1016 if (UseMemorySSA)
1017 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1018 else
1019 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001020 }
1021
1022 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001023 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001024 return false;
1025
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001026 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001027 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001028 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001029 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001030 auto *MSSA =
1031 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001032
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001033 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001034
1035 return CSE.run();
1036 }
1037
1038 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001039 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001040 AU.addRequired<DominatorTreeWrapperPass>();
1041 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001042 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001043 if (UseMemorySSA) {
1044 AU.addRequired<MemorySSAWrapperPass>();
1045 AU.addPreserved<MemorySSAWrapperPass>();
1046 }
James Molloyefbba722015-09-10 10:22:12 +00001047 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001048 AU.setPreservesCFG();
1049 }
1050};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001051}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001052
Geoff Berry8d846052016-08-31 19:24:10 +00001053using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001054
Geoff Berry8d846052016-08-31 19:24:10 +00001055template<>
1056char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001057
1058INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1059 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001060INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001061INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001062INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1063INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1064INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001065
1066using EarlyCSEMemSSALegacyPass =
1067 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1068
1069template<>
1070char EarlyCSEMemSSALegacyPass::ID = 0;
1071
1072FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1073 if (UseMemorySSA)
1074 return new EarlyCSEMemSSALegacyPass();
1075 else
1076 return new EarlyCSELegacyPass();
1077}
1078
1079INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1080 "Early CSE w/ MemorySSA", false, false)
1081INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001082INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001083INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1084INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1085INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1086INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1087 "Early CSE w/ MemorySSA", false, false)