blob: 829f310b6fb005bb8e911a81c4a503f3395dbbf4 [file] [log] [blame]
Chris Lattner704541b2011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner704541b2011-01-02 21:47:05 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs a simple dominator tree walk that eliminates trivially
10// redundant instructions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthe8c686a2015-02-01 10:51:23 +000014#include "llvm/Transforms/Scalar/EarlyCSE.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000015#include "llvm/ADT/DenseMapInfo.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000016#include "llvm/ADT/Hashing.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000017#include "llvm/ADT/STLExtras.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000018#include "llvm/ADT/ScopedHashTable.h"
Davide Italiano0dc47782017-06-14 19:29:53 +000019#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000020#include "llvm/ADT/SmallVector.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000021#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000023#include "llvm/Analysis/GlobalsModRef.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000024#include "llvm/Analysis/GuardUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/InstructionSimplify.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000026#include "llvm/Analysis/MemorySSA.h"
27#include "llvm/Analysis/MemorySSAUpdater.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
Chad Rosierf9327d62015-01-26 22:51:15 +000029#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000030#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel3c7a35d2017-12-13 21:58:15 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000032#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000036#include "llvm/IR/Function.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000040#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000041#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/PassManager.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000044#include "llvm/IR/PatternMatch.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000045#include "llvm/IR/Type.h"
46#include "llvm/IR/Use.h"
47#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Pass.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000049#include "llvm/Support/Allocator.h"
50#include "llvm/Support/AtomicOrdering.h"
51#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000052#include "llvm/Support/Debug.h"
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000053#include "llvm/Support/DebugCounter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000056#include "llvm/Transforms/Scalar.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000057#include "llvm/Transforms/Utils/GuardUtils.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000058#include <cassert>
Lenny Maiorani9eefc812014-09-20 13:29:20 +000059#include <deque>
Eugene Zelenko3b879392017-10-13 21:17:07 +000060#include <memory>
61#include <utility>
62
Chris Lattner704541b2011-01-02 21:47:05 +000063using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000064using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000065
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "early-cse"
67
Chris Lattner4cb36542011-01-03 03:28:23 +000068STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
69STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000070STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000071STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
72STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000073STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000074
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000075DEBUG_COUNTER(CSECounter, "early-cse",
76 "Controls which instructions are removed");
77
Alina Sbirlea383ccfb2019-02-15 22:47:54 +000078static cl::opt<unsigned> EarlyCSEMssaOptCap(
79 "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
80 cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
81 "for faster compile. Caps the MemorySSA clobbering calls."));
82
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +000083static cl::opt<bool> EarlyCSEDebugHash(
84 "earlycse-debug-hash", cl::init(false), cl::Hidden,
85 cl::desc("Perform extra assertion checking to verify that SimpleValue's hash "
86 "function is well-behaved w.r.t. its isEqual predicate"));
87
Chris Lattner79d83062011-01-03 02:20:48 +000088//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000089// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000090//===----------------------------------------------------------------------===//
91
Chris Lattner704541b2011-01-02 21:47:05 +000092namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +000093
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000094/// Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000095struct SimpleValue {
96 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000097
Chandler Carruth7253bba2015-01-24 11:33:55 +000098 SimpleValue(Instruction *I) : Inst(I) {
99 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
100 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000101
Chandler Carruth7253bba2015-01-24 11:33:55 +0000102 bool isSentinel() const {
103 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
104 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
105 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000106
Chandler Carruth7253bba2015-01-24 11:33:55 +0000107 static bool canHandle(Instruction *Inst) {
108 // This can only handle non-void readnone functions.
109 if (CallInst *CI = dyn_cast<CallInst>(Inst))
110 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
Cameron McInally303b6db2019-08-07 14:34:41 +0000111 return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
112 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
113 isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
114 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
115 isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
116 isa<InsertValueInst>(Inst);
Chandler Carruth7253bba2015-01-24 11:33:55 +0000117 }
118};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000119
120} // end anonymous namespace
Chris Lattner18ae5432011-01-02 23:04:14 +0000121
122namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000123
Chandler Carruth7253bba2015-01-24 11:33:55 +0000124template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +0000125 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000126 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000127 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000128
Chris Lattner79d83062011-01-03 02:20:48 +0000129 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000130 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000131 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000132
Chris Lattner79d83062011-01-03 02:20:48 +0000133 static unsigned getHashValue(SimpleValue Val);
134 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +0000135};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000136
137} // end namespace llvm
Chris Lattner18ae5432011-01-02 23:04:14 +0000138
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000139/// Match a 'select' including an optional 'not's of the condition.
140static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
141 Value *&B,
142 SelectPatternFlavor &Flavor) {
143 // Return false if V is not even a select.
144 if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
145 return false;
146
147 // Look through a 'not' of the condition operand by swapping A/B.
148 Value *CondNot;
149 if (match(Cond, m_Not(m_Value(CondNot)))) {
150 Cond = CondNot;
151 std::swap(A, B);
Sanjay Patele08783e2019-04-16 20:41:20 +0000152 }
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000153
154 // Set flavor if we find a match, or set it to unknown otherwise; in
155 // either case, return true to indicate that this is a select we can
156 // process.
157 if (auto *CmpI = dyn_cast<ICmpInst>(Cond))
158 Flavor = matchDecomposedSelectPattern(CmpI, A, B, A, B).Flavor;
159 else
160 Flavor = SPF_UNKNOWN;
161
162 return true;
Sanjay Patele08783e2019-04-16 20:41:20 +0000163}
164
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000165static unsigned getHashValueImpl(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000166 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +0000167 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000168 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000169 Value *LHS = BinOp->getOperand(0);
170 Value *RHS = BinOp->getOperand(1);
171 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
172 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000173
Michael Ilseman336cb792012-10-09 16:57:38 +0000174 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000175 }
176
Michael Ilseman336cb792012-10-09 16:57:38 +0000177 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
Joseph Tremouletdaa1ae62019-06-17 19:11:28 +0000178 // Compares can be commuted by swapping the comparands and
179 // updating the predicate. Choose the form that has the
180 // comparands in sorted order, or in the case of a tie, the
181 // one with the lower predicate.
Michael Ilseman336cb792012-10-09 16:57:38 +0000182 Value *LHS = CI->getOperand(0);
183 Value *RHS = CI->getOperand(1);
184 CmpInst::Predicate Pred = CI->getPredicate();
Joseph Tremouletdaa1ae62019-06-17 19:11:28 +0000185 CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
186 if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000187 std::swap(LHS, RHS);
Joseph Tremouletdaa1ae62019-06-17 19:11:28 +0000188 Pred = SwappedPred;
Michael Ilseman336cb792012-10-09 16:57:38 +0000189 }
190 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
191 }
192
Sanjay Patele08783e2019-04-16 20:41:20 +0000193 // Hash general selects to allow matching commuted true/false operands.
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000194 SelectPatternFlavor SPF;
195 Value *Cond, *A, *B;
196 if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
197 // Hash min/max/abs (cmp + select) to allow for commuted operands.
198 // Min/max may also have non-canonical compare predicate (eg, the compare for
199 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
200 // compare.
201 // TODO: We should also detect FP min/max.
202 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
203 SPF == SPF_UMIN || SPF == SPF_UMAX) {
204 if (A > B)
205 std::swap(A, B);
206 return hash_combine(Inst->getOpcode(), SPF, A, B);
207 }
208 if (SPF == SPF_ABS || SPF == SPF_NABS) {
209 // ABS/NABS always puts the input in A and its negation in B.
210 return hash_combine(Inst->getOpcode(), SPF, A, B);
211 }
212
213 // Hash general selects to allow matching commuted true/false operands.
214
Sanjay Patele08783e2019-04-16 20:41:20 +0000215 // If we do not have a compare as the condition, just hash in the condition.
216 CmpInst::Predicate Pred;
217 Value *X, *Y;
218 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000219 return hash_combine(Inst->getOpcode(), Cond, A, B);
Sanjay Patele08783e2019-04-16 20:41:20 +0000220
221 // Similar to cmp normalization (above) - canonicalize the predicate value:
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000222 // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
Sanjay Patele08783e2019-04-16 20:41:20 +0000223 if (CmpInst::getInversePredicate(Pred) < Pred) {
224 Pred = CmpInst::getInversePredicate(Pred);
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000225 std::swap(A, B);
Sanjay Patele08783e2019-04-16 20:41:20 +0000226 }
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000227 return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
Sanjay Patele08783e2019-04-16 20:41:20 +0000228 }
229
Michael Ilseman336cb792012-10-09 16:57:38 +0000230 if (CastInst *CI = dyn_cast<CastInst>(Inst))
231 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
232
233 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
234 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
235 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
236
237 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
238 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
239 IVI->getOperand(1),
240 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
241
Sanjay Patele08783e2019-04-16 20:41:20 +0000242 assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
Michael Ilseman336cb792012-10-09 16:57:38 +0000243 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Cameron McInally303b6db2019-08-07 14:34:41 +0000244 isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst)) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000245 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000246
Chris Lattner02a97762011-01-03 01:10:08 +0000247 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000248 return hash_combine(
249 Inst->getOpcode(),
250 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000251}
252
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000253unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
254#ifndef NDEBUG
255 // If -earlycse-debug-hash was specified, return a constant -- this
256 // will force all hashing to collide, so we'll exhaustively search
257 // the table for a match, and the assertion in isEqual will fire if
258 // there's a bug causing equal keys to hash differently.
259 if (EarlyCSEDebugHash)
260 return 0;
261#endif
262 return getHashValueImpl(Val);
263}
264
265static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000266 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
267
268 if (LHS.isSentinel() || RHS.isSentinel())
269 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Chandler Carruth7253bba2015-01-24 11:33:55 +0000271 if (LHSI->getOpcode() != RHSI->getOpcode())
272 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000273 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000274 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000275
276 // If we're not strictly identical, we still might be a commutable instruction
277 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
278 if (!LHSBinOp->isCommutative())
279 return false;
280
Chandler Carruth7253bba2015-01-24 11:33:55 +0000281 assert(isa<BinaryOperator>(RHSI) &&
282 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000283 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
284
Michael Ilseman336cb792012-10-09 16:57:38 +0000285 // Commuted equality
286 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000287 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000288 }
289 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000290 assert(isa<CmpInst>(RHSI) &&
291 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000292 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
293 // Commuted equality
294 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000295 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
296 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000297 }
298
Sanjay Patel558a4652017-12-13 22:57:35 +0000299 // Min/max/abs can occur with commuted operands, non-canonical predicates,
300 // and/or non-canonical operands.
Sanjay Patele08783e2019-04-16 20:41:20 +0000301 // Selects can be non-trivially equivalent via inverted conditions and swaps.
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000302 SelectPatternFlavor LSPF, RSPF;
303 Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
304 if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
305 matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
306 if (LSPF == RSPF) {
307 // TODO: We should also detect FP min/max.
308 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
309 LSPF == SPF_UMIN || LSPF == SPF_UMAX)
310 return ((LHSA == RHSA && LHSB == RHSB) ||
311 (LHSA == RHSB && LHSB == RHSA));
312
313 if (LSPF == SPF_ABS || LSPF == SPF_NABS) {
314 // Abs results are placed in a defined order by matchSelectPattern.
315 return LHSA == RHSA && LHSB == RHSB;
316 }
317
318 // select Cond, A, B <--> select not(Cond), B, A
319 if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
320 return true;
321 }
Sanjay Patele08783e2019-04-16 20:41:20 +0000322
323 // If the true/false operands are swapped and the conditions are compares
324 // with inverted predicates, the selects are equal:
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000325 // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
Sanjay Patele08783e2019-04-16 20:41:20 +0000326 //
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000327 // This also handles patterns with a double-negation in the sense of not +
328 // inverse, because we looked through a 'not' in the matching function and
329 // swapped A/B:
330 // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
331 //
332 // This intentionally does NOT handle patterns with a double-negation in
333 // the sense of not + not, because doing so could result in values
334 // comparing
335 // as equal that hash differently in the min/max/abs cases like:
336 // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
337 // ^ hashes as min ^ would not hash as min
338 // In the context of the EarlyCSE pass, however, such cases never reach
339 // this code, as we simplify the double-negation before hashing the second
340 // select (and so still succeed at CSEing them).
341 if (LHSA == RHSB && LHSB == RHSA) {
Sanjay Patele08783e2019-04-16 20:41:20 +0000342 CmpInst::Predicate PredL, PredR;
343 Value *X, *Y;
344 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
345 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
346 CmpInst::getInversePredicate(PredL) == PredR)
347 return true;
348 }
349 }
350
Michael Ilseman336cb792012-10-09 16:57:38 +0000351 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000352}
353
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +0000354bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
355 // These comparisons are nontrivial, so assert that equality implies
356 // hash equality (DenseMap demands this as an invariant).
357 bool Result = isEqualImpl(LHS, RHS);
358 assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
359 getHashValueImpl(LHS) == getHashValueImpl(RHS));
360 return Result;
361}
362
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000363//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000364// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000365//===----------------------------------------------------------------------===//
366
367namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000369/// Struct representing the available call values in the scoped hash
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000370/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000371struct CallValue {
372 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000373
Chandler Carruth7253bba2015-01-24 11:33:55 +0000374 CallValue(Instruction *I) : Inst(I) {
375 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
376 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000377
Chandler Carruth7253bba2015-01-24 11:33:55 +0000378 bool isSentinel() const {
379 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
380 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
381 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000382
Chandler Carruth7253bba2015-01-24 11:33:55 +0000383 static bool canHandle(Instruction *Inst) {
384 // Don't value number anything that returns void.
385 if (Inst->getType()->isVoidTy())
386 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000387
Chandler Carruth7253bba2015-01-24 11:33:55 +0000388 CallInst *CI = dyn_cast<CallInst>(Inst);
389 if (!CI || !CI->onlyReadsMemory())
390 return false;
391 return true;
392 }
393};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000394
395} // end anonymous namespace
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000396
397namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000398
Chandler Carruth7253bba2015-01-24 11:33:55 +0000399template <> struct DenseMapInfo<CallValue> {
400 static inline CallValue getEmptyKey() {
401 return DenseMapInfo<Instruction *>::getEmptyKey();
402 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000403
Chandler Carruth7253bba2015-01-24 11:33:55 +0000404 static inline CallValue getTombstoneKey() {
405 return DenseMapInfo<Instruction *>::getTombstoneKey();
406 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000407
Chandler Carruth7253bba2015-01-24 11:33:55 +0000408 static unsigned getHashValue(CallValue Val);
409 static bool isEqual(CallValue LHS, CallValue RHS);
410};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000411
412} // end namespace llvm
Chandler Carruth7253bba2015-01-24 11:33:55 +0000413
Chris Lattner92bb0f92011-01-03 03:41:27 +0000414unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000415 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000416 // Hash all of the operands as pointers and mix in the opcode.
417 return hash_combine(
418 Inst->getOpcode(),
419 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000420}
421
Chris Lattner92bb0f92011-01-03 03:41:27 +0000422bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000423 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000424 if (LHS.isSentinel() || RHS.isSentinel())
425 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000426 return LHSI->isIdenticalTo(RHSI);
427}
428
Chris Lattner79d83062011-01-03 02:20:48 +0000429//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000430// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000431//===----------------------------------------------------------------------===//
432
Chris Lattner18ae5432011-01-02 23:04:14 +0000433namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000434
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000435/// A simple and fast domtree-based CSE pass.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000436///
437/// This pass does a simple depth-first walk over the dominator tree,
438/// eliminating trivially redundant instructions and using instsimplify to
439/// canonicalize things as it goes. It is intended to be fast and catch obvious
440/// cases so that instcombine and other passes are more effective. It is
441/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000442class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000443public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000444 const TargetLibraryInfo &TLI;
445 const TargetTransformInfo &TTI;
446 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000447 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000448 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000449 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000450 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000451
452 using AllocatorTy =
453 RecyclingAllocator<BumpPtrAllocator,
454 ScopedHashTableVal<SimpleValue, Value *>>;
455 using ScopedHTType =
456 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
457 AllocatorTy>;
Nadav Rotem465834c2012-07-24 10:51:42 +0000458
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000459 /// A scoped hash table of the current values of all of our simple
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000460 /// scalar expressions.
461 ///
462 /// As we walk down the domtree, we look to see if instructions are in this:
463 /// if so, we replace them with what we find, otherwise we insert them so
464 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000465 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000466
Hiroshi Inouef2096492018-06-14 05:41:49 +0000467 /// A scoped hash table of the current values of previously encountered
468 /// memory locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000469 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000470 /// This allows us to get efficient access to dominating loads or stores when
471 /// we have a fully redundant load. In addition to the most recent load, we
472 /// keep track of a generation count of the read, which is compared against
473 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000474 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000475 /// CSE loads with other loads that have no intervening store. Ordering
476 /// events (such as fences or atomic instructions) increment the generation
477 /// count as well; essentially, we model these as writes to all possible
478 /// locations. Note that atomic and/or volatile loads and stores can be
479 /// present the table; it is the responsibility of the consumer to inspect
480 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000481 struct LoadValue {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000482 Instruction *DefInst = nullptr;
483 unsigned Generation = 0;
484 int MatchingId = -1;
485 bool IsAtomic = false;
Philip Reames0adbb192018-03-14 21:35:06 +0000486
Eugene Zelenko3b879392017-10-13 21:17:07 +0000487 LoadValue() = default;
Geoff Berry5ae272c2016-04-28 15:22:37 +0000488 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reamesca587fe2018-03-15 17:29:32 +0000489 bool IsAtomic)
Sanjoy Das07c65212016-06-16 20:47:57 +0000490 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reamesca587fe2018-03-15 17:29:32 +0000491 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000492 };
Eugene Zelenko3b879392017-10-13 21:17:07 +0000493
494 using LoadMapAllocator =
495 RecyclingAllocator<BumpPtrAllocator,
496 ScopedHashTableVal<Value *, LoadValue>>;
497 using LoadHTType =
498 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
499 LoadMapAllocator>;
500
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000501 LoadHTType AvailableLoads;
Fangrui Songf78650a2018-07-30 19:41:25 +0000502
Philip Reames0adbb192018-03-14 21:35:06 +0000503 // A scoped hash table mapping memory locations (represented as typed
504 // addresses) to generation numbers at which that memory location became
505 // (henceforth indefinitely) invariant.
506 using InvariantMapAllocator =
507 RecyclingAllocator<BumpPtrAllocator,
508 ScopedHashTableVal<MemoryLocation, unsigned>>;
509 using InvariantHTType =
510 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
511 InvariantMapAllocator>;
512 InvariantHTType AvailableInvariants;
Nadav Rotem465834c2012-07-24 10:51:42 +0000513
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000514 /// A scoped hash table of the current values of read-only call
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000515 /// values.
516 ///
517 /// It uses the same generation count as loads.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000518 using CallHTType =
519 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000520 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000521
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000522 /// This is the current generation of the memory value.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000523 unsigned CurrentGeneration = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000524
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000525 /// Set up the EarlyCSE runner for a particular function.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000526 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
527 const TargetTransformInfo &TTI, DominatorTree &DT,
528 AssumptionCache &AC, MemorySSA *MSSA)
529 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000530 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000531
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000532 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000533
534private:
Alina Sbirlea383ccfb2019-02-15 22:47:54 +0000535 unsigned ClobberCounter = 0;
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000536 // Almost a POD, but needs to call the constructors for the scoped hash
537 // tables so that a new scope gets pushed on. These are RAII so that the
538 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000539 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000540 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000541 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000542 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
543 : Scope(AvailableValues), LoadScope(AvailableLoads),
544 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
Eugene Zelenko3b879392017-10-13 21:17:07 +0000545 NodeScope(const NodeScope &) = delete;
546 NodeScope &operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000547
Chandler Carruth7253bba2015-01-24 11:33:55 +0000548 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000549 ScopedHTType::ScopeTy Scope;
550 LoadHTType::ScopeTy LoadScope;
Philip Reames0adbb192018-03-14 21:35:06 +0000551 InvariantHTType::ScopeTy InvariantScope;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000552 CallHTType::ScopeTy CallScope;
553 };
554
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000555 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000556 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000557 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000558 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000559 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000560 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000561 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000562 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
563 unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
564 DomTreeNode::iterator end)
Chandler Carruth7253bba2015-01-24 11:33:55 +0000565 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Philip Reames0adbb192018-03-14 21:35:06 +0000566 EndIter(end),
567 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
568 AvailableCalls)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000569 {}
570 StackNode(const StackNode &) = delete;
571 StackNode &operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000572
573 // Accessors.
574 unsigned currentGeneration() { return CurrentGeneration; }
575 unsigned childGeneration() { return ChildGeneration; }
576 void childGeneration(unsigned generation) { ChildGeneration = generation; }
577 DomTreeNode *node() { return Node; }
578 DomTreeNode::iterator childIter() { return ChildIter; }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000579
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000580 DomTreeNode *nextChild() {
581 DomTreeNode *child = *ChildIter;
582 ++ChildIter;
583 return child;
584 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000585
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000586 DomTreeNode::iterator end() { return EndIter; }
587 bool isProcessed() { return Processed; }
588 void process() { Processed = true; }
589
Chandler Carruth7253bba2015-01-24 11:33:55 +0000590 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000591 unsigned CurrentGeneration;
592 unsigned ChildGeneration;
593 DomTreeNode *Node;
594 DomTreeNode::iterator ChildIter;
595 DomTreeNode::iterator EndIter;
596 NodeScope Scopes;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000597 bool Processed = false;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000598 };
599
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000600 /// Wrapper class to handle memory instructions, including loads,
Chad Rosierf9327d62015-01-26 22:51:15 +0000601 /// stores and intrinsic loads and stores defined by the target.
602 class ParseMemoryInst {
603 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000604 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000605 : Inst(Inst) {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000606 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000607 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000608 IsTargetMemInst = true;
609 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000610
Philip Reames9e5e2d62015-12-07 22:41:23 +0000611 bool isLoad() const {
612 if (IsTargetMemInst) return Info.ReadMem;
613 return isa<LoadInst>(Inst);
614 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000615
Philip Reames9e5e2d62015-12-07 22:41:23 +0000616 bool isStore() const {
617 if (IsTargetMemInst) return Info.WriteMem;
618 return isa<StoreInst>(Inst);
619 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000620
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000621 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000622 if (IsTargetMemInst)
623 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000624 return Inst->isAtomic();
625 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000626
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000627 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000628 if (IsTargetMemInst)
629 return Info.isUnordered();
630
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000631 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
632 return LI->isUnordered();
633 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
634 return SI->isUnordered();
635 }
636 // Conservative answer
637 return !Inst->isAtomic();
638 }
639
640 bool isVolatile() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000641 if (IsTargetMemInst)
642 return Info.IsVolatile;
643
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000644 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
645 return LI->isVolatile();
646 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
647 return SI->isVolatile();
648 }
649 // Conservative answer
650 return true;
651 }
652
Sanjoy Das07c65212016-06-16 20:47:57 +0000653 bool isInvariantLoad() const {
654 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000655 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000656 return false;
657 }
Junmo Park80440eb2016-02-18 10:09:20 +0000658
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000659 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000660 return (getPointerOperand() == Inst.getPointerOperand() &&
661 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000662 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000663
Philip Reames9e5e2d62015-12-07 22:41:23 +0000664 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000665
Chad Rosierf9327d62015-01-26 22:51:15 +0000666 // For regular (non-intrinsic) loads/stores, this is set to -1. For
667 // intrinsic loads/stores, the id is retrieved from the corresponding
668 // field in the MemIntrinsicInfo structure. That field contains
669 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000670 int getMatchingId() const {
671 if (IsTargetMemInst) return Info.MatchingId;
672 return -1;
673 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000674
Philip Reames9e5e2d62015-12-07 22:41:23 +0000675 Value *getPointerOperand() const {
676 if (IsTargetMemInst) return Info.PtrVal;
Renato Golin038ede22018-03-09 21:05:58 +0000677 return getLoadStorePointerOperand(Inst);
Philip Reames9e5e2d62015-12-07 22:41:23 +0000678 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000679
Philip Reames9e5e2d62015-12-07 22:41:23 +0000680 bool mayReadFromMemory() const {
681 if (IsTargetMemInst) return Info.ReadMem;
682 return Inst->mayReadFromMemory();
683 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000684
Philip Reames9e5e2d62015-12-07 22:41:23 +0000685 bool mayWriteToMemory() const {
686 if (IsTargetMemInst) return Info.WriteMem;
687 return Inst->mayWriteToMemory();
688 }
689
690 private:
Eugene Zelenko3b879392017-10-13 21:17:07 +0000691 bool IsTargetMemInst = false;
Philip Reames9e5e2d62015-12-07 22:41:23 +0000692 MemIntrinsicInfo Info;
693 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000694 };
695
Chris Lattner18ae5432011-01-02 23:04:14 +0000696 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000697
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000698 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
699 const BasicBlock *BB, const BasicBlock *Pred);
700
Chad Rosierf9327d62015-01-26 22:51:15 +0000701 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000702 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000703 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000704 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000705 return SI->getValueOperand();
706 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000707 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
708 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000709 }
Geoff Berry8d846052016-08-31 19:24:10 +0000710
Philip Reames0adbb192018-03-14 21:35:06 +0000711 /// Return true if the instruction is known to only operate on memory
712 /// provably invariant in the given "generation".
713 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
714
Geoff Berry8d846052016-08-31 19:24:10 +0000715 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
716 Instruction *EarlierInst, Instruction *LaterInst);
717
718 void removeMSSA(Instruction *Inst) {
719 if (!MSSA)
720 return;
Alina Sbirleaa782a702018-09-17 22:35:21 +0000721 if (VerifyMemorySSA)
722 MSSA->verifyMemorySSA();
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000723 // Removing a store here can leave MemorySSA in an unoptimized state by
724 // creating MemoryPhis that have identical arguments and by creating
Alina Sbirleae2718892019-01-31 21:12:41 +0000725 // MemoryUses whose defining access is not an actual clobber. The phi case
726 // is handled by MemorySSA when passing OptimizePhis = true to
727 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
728 // by MemorySSA's getClobberingMemoryAccess.
729 MSSAUpdater->removeMemoryAccess(Inst, true);
Geoff Berry8d846052016-08-31 19:24:10 +0000730 }
Chris Lattner704541b2011-01-02 21:47:05 +0000731};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000732
733} // end anonymous namespace
Chris Lattner704541b2011-01-02 21:47:05 +0000734
Geoff Berry68154682016-10-24 15:54:00 +0000735/// Determine if the memory referenced by LaterInst is from the same heap
736/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000737/// This is currently called in two scenarios:
738///
739/// load p
740/// ...
741/// load p
742///
743/// and
744///
745/// x = load p
746/// ...
747/// store x, p
748///
749/// in both cases we want to verify that there are no possible writes to the
750/// memory referenced by p between the earlier and later instruction.
751bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
752 unsigned LaterGeneration,
753 Instruction *EarlierInst,
754 Instruction *LaterInst) {
755 // Check the simple memory generation tracking first.
756 if (EarlierGeneration == LaterGeneration)
757 return true;
758
759 if (!MSSA)
760 return false;
761
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000762 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
763 // read/write memory, then we can safely return true here.
764 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
765 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
766 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
767 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
768 // with the default optimization pipeline.
769 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
770 if (!EarlierMA)
771 return true;
772 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
773 if (!LaterMA)
774 return true;
775
Geoff Berry8d846052016-08-31 19:24:10 +0000776 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
777 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
778 // EarlierInst and LaterInst and neither can any other write that potentially
779 // clobbers LaterInst.
Alina Sbirlea383ccfb2019-02-15 22:47:54 +0000780 MemoryAccess *LaterDef;
781 if (ClobberCounter < EarlyCSEMssaOptCap) {
782 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
783 ClobberCounter++;
784 } else
785 LaterDef = LaterMA->getDefiningAccess();
786
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000787 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000788}
789
Philip Reames0adbb192018-03-14 21:35:06 +0000790bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
791 // A location loaded from with an invariant_load is assumed to *never* change
792 // within the visible scope of the compilation.
793 if (auto *LI = dyn_cast<LoadInst>(I))
794 if (LI->getMetadata(LLVMContext::MD_invariant_load))
795 return true;
796
797 auto MemLocOpt = MemoryLocation::getOrNone(I);
798 if (!MemLocOpt)
799 // "target" intrinsic forms of loads aren't currently known to
800 // MemoryLocation::get. TODO
801 return false;
802 MemoryLocation MemLoc = *MemLocOpt;
803 if (!AvailableInvariants.count(MemLoc))
804 return false;
805
806 // Is the generation at which this became invariant older than the
807 // current one?
808 return AvailableInvariants.lookup(MemLoc) <= GenAt;
809}
810
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000811bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
812 const BranchInst *BI, const BasicBlock *BB,
813 const BasicBlock *Pred) {
814 assert(BI->isConditional() && "Should be a conditional branch!");
815 assert(BI->getCondition() == CondInst && "Wrong condition?");
816 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
817 auto *TorF = (BI->getSuccessor(0) == BB)
818 ? ConstantInt::getTrue(BB->getContext())
819 : ConstantInt::getFalse(BB->getContext());
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000820 auto MatchBinOp = [](Instruction *I, unsigned Opcode) {
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000821 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I))
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000822 return BOp->getOpcode() == Opcode;
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000823 return false;
824 };
825 // If the condition is AND operation, we can propagate its operands into the
826 // true branch. If it is OR operation, we can propagate them into the false
827 // branch.
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000828 unsigned PropagateOpcode =
829 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000830
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000831 bool MadeChanges = false;
832 SmallVector<Instruction *, 4> WorkList;
833 SmallPtrSet<Instruction *, 4> Visited;
834 WorkList.push_back(CondInst);
835 while (!WorkList.empty()) {
836 Instruction *Curr = WorkList.pop_back_val();
837
838 AvailableValues.insert(Curr, TorF);
839 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
840 << Curr->getName() << "' as " << *TorF << " in "
841 << BB->getName() << "\n");
842 if (!DebugCounter::shouldExecute(CSECounter)) {
843 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
844 } else {
845 // Replace all dominated uses with the known value.
846 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
847 BasicBlockEdge(Pred, BB))) {
848 NumCSECVP += Count;
849 MadeChanges = true;
850 }
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000851 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000852
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000853 if (MatchBinOp(Curr, PropagateOpcode))
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000854 for (auto &Op : cast<BinaryOperator>(Curr)->operands())
855 if (Instruction *OPI = dyn_cast<Instruction>(Op))
856 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
857 WorkList.push_back(OPI);
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000858 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000859
860 return MadeChanges;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000861}
862
Chris Lattner18ae5432011-01-02 23:04:14 +0000863bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000864 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000865 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000866
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000867 // If this block has a single predecessor, then the predecessor is the parent
868 // of the domtree node and all of the live out memory values are still current
869 // in this block. If this block has multiple predecessors, then they could
870 // have invalidated the live-out memory values of our parent value. For now,
871 // just be conservative and invalidate memory if this block has multiple
872 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000873 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000874 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000875
Philip Reames7c78ef72015-05-22 23:53:24 +0000876 // If this node has a single predecessor which ends in a conditional branch,
877 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000878 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000879 // which reaches this block where the condition might hold a different
880 // value. Since we're adding this to the scoped hash table (like any other
881 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000882 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
883 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
884 if (BI && BI->isConditional()) {
885 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000886 if (CondInst && SimpleValue::canHandle(CondInst))
887 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000888 }
889 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000890
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000891 /// LastStore - Keep track of the last non-volatile store that we saw... for
892 /// as long as there in no instruction that reads memory. If we see a store
893 /// to the same location, we delete the dead store. This zaps trivial dead
894 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000895 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000896
Chris Lattner18ae5432011-01-02 23:04:14 +0000897 // See if any instructions in the block can be eliminated. If so, do it. If
898 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000899 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000900 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000901
Chris Lattner18ae5432011-01-02 23:04:14 +0000902 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000903 if (isInstructionTriviallyDead(Inst, &TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000904 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000905 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000906 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000907 continue;
908 }
Davide Italianoe41e1d02018-12-17 01:42:39 +0000909 if (!salvageDebugInfo(*Inst))
910 replaceDbgUsesWithUndef(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000911 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000912 Inst->eraseFromParent();
913 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000914 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000915 continue;
916 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000917
Hal Finkel1e16fa32014-11-03 20:21:32 +0000918 // Skip assume intrinsics, they don't really have side effects (although
919 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000920 // and this pass will not bother with its removal. However, we should mark
921 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000922 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000923 auto *CondI =
924 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
925 if (CondI && SimpleValue::canHandle(CondI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000926 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst
927 << '\n');
Max Kazantsev531db9a2017-04-28 06:25:39 +0000928 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
929 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000930 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000931 continue;
932 }
933
Dan Gohman2c74fe92017-11-08 21:59:51 +0000934 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
935 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000936 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n');
Dan Gohman2c74fe92017-11-08 21:59:51 +0000937 continue;
938 }
939
Philip Reames0adbb192018-03-14 21:35:06 +0000940 // We can skip all invariant.start intrinsics since they only read memory,
941 // and we can forward values across it. For invariant starts without
942 // invariant ends, we can use the fact that the invariantness never ends to
943 // start a scope in the current generaton which is true for all future
944 // generations. Also, we dont need to consume the last store since the
945 // semantics of invariant.start allow us to perform DSE of the last
Fangrui Songf78650a2018-07-30 19:41:25 +0000946 // store, if there was a store following invariant.start. Consider:
Anna Thomasb2d12b82016-08-09 20:00:47 +0000947 //
948 // store 30, i8* p
949 // invariant.start(p)
950 // store 40, i8* p
951 // We can DSE the store to 30, since the store 40 to invariant location p
952 // causes undefined behaviour.
Philip Reames0adbb192018-03-14 21:35:06 +0000953 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000954 // If there are any uses, the scope might end.
Philip Reames0adbb192018-03-14 21:35:06 +0000955 if (!Inst->use_empty())
956 continue;
957 auto *CI = cast<CallInst>(Inst);
958 MemoryLocation MemLoc = MemoryLocation::getForArgument(CI, 1, TLI);
Philip Reames422024a2018-03-15 18:12:27 +0000959 // Don't start a scope if we already have a better one pushed
960 if (!AvailableInvariants.count(MemLoc))
961 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Anna Thomasb2d12b82016-08-09 20:00:47 +0000962 continue;
Philip Reames0adbb192018-03-14 21:35:06 +0000963 }
Anna Thomasb2d12b82016-08-09 20:00:47 +0000964
Max Kazantsev3c284bd2018-08-30 03:39:16 +0000965 if (isGuard(Inst)) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000966 if (auto *CondI =
967 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000968 if (SimpleValue::canHandle(CondI)) {
969 // Do we already know the actual value of this condition?
970 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
971 // Is the condition known to be true?
972 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000973 cast<ConstantInt>(KnownCond)->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000974 LLVM_DEBUG(dbgs()
975 << "EarlyCSE removing guard: " << *Inst << '\n');
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000976 removeMSSA(Inst);
977 Inst->eraseFromParent();
978 Changed = true;
979 continue;
980 } else
981 // Use the known value if it wasn't true.
982 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
983 }
984 // The condition we're on guarding here is true for all dominated
985 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000986 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000987 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000988 }
989
990 // Guard intrinsics read all memory, but don't write any memory.
991 // Accordingly, don't update the generation but consume the last store (to
992 // avoid an incorrect DSE).
993 LastStore = nullptr;
994 continue;
995 }
996
Chris Lattner18ae5432011-01-02 23:04:14 +0000997 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
998 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000999 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001000 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V
1001 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001002 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001003 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001004 } else {
1005 bool Killed = false;
1006 if (!Inst->use_empty()) {
1007 Inst->replaceAllUsesWith(V);
1008 Changed = true;
1009 }
1010 if (isInstructionTriviallyDead(Inst, &TLI)) {
1011 removeMSSA(Inst);
1012 Inst->eraseFromParent();
1013 Changed = true;
1014 Killed = true;
1015 }
1016 if (Changed)
1017 ++NumSimplify;
1018 if (Killed)
1019 continue;
David Majnemerb8da3a22016-06-25 00:04:10 +00001020 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001021 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001022
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001023 // If this is a simple instruction that we can value number, process it.
1024 if (SimpleValue::canHandle(Inst)) {
1025 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001026 if (Value *V = AvailableValues.lookup(Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001027 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V
1028 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001029 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001030 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001031 continue;
1032 }
David Majnemer9554c132016-04-22 06:37:45 +00001033 if (auto *I = dyn_cast<Instruction>(V))
1034 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001035 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +00001036 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001037 Inst->eraseFromParent();
1038 Changed = true;
1039 ++NumCSE;
1040 continue;
1041 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001042
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001043 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001044 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +00001045 continue;
1046 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001047
Chad Rosierf9327d62015-01-26 22:51:15 +00001048 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +00001049 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +00001050 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001051 // (conservatively) we can't peak past the ordering implied by this
1052 // operation, but we can add this load to our set of available values
1053 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001054 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001055 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001056 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001057
Philip Reamesca587fe2018-03-15 17:29:32 +00001058 if (MemInst.isInvariantLoad()) {
1059 // If we pass an invariant load, we know that memory location is
1060 // indefinitely constant from the moment of first dereferenceability.
Philip Reames422024a2018-03-15 18:12:27 +00001061 // We conservatively treat the invariant_load as that moment. If we
1062 // pass a invariant load after already establishing a scope, don't
1063 // restart it since we want to preserve the earliest point seen.
Philip Reamesca587fe2018-03-15 17:29:32 +00001064 auto MemLoc = MemoryLocation::get(Inst);
Philip Reames422024a2018-03-15 18:12:27 +00001065 if (!AvailableInvariants.count(MemLoc))
1066 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Philip Reamesca587fe2018-03-15 17:29:32 +00001067 }
1068
Chris Lattner92bb0f92011-01-03 03:41:27 +00001069 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +00001070 // generation or the load is known to be from an invariant location,
1071 // replace this instruction.
1072 //
Geoff Berry64f5ed12016-08-31 17:45:31 +00001073 // If either the dominating load or the current load are invariant, then
1074 // we can assume the current load loads the same value as the dominating
1075 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +00001076 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +00001077 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001078 InVal.MatchingId == MemInst.getMatchingId() &&
1079 // We don't yet handle removing loads with ordering of any kind.
1080 !MemInst.isVolatile() && MemInst.isUnordered() &&
1081 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +00001082 InVal.IsAtomic >= MemInst.isAtomic() &&
Philip Reamesca587fe2018-03-15 17:29:32 +00001083 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
Geoff Berry8d846052016-08-31 19:24:10 +00001084 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1085 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +00001086 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +00001087 if (Op != nullptr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001088 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
1089 << " to: " << *InVal.DefInst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001090 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001091 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001092 continue;
1093 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001094 if (!Inst->use_empty())
1095 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +00001096 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +00001097 Inst->eraseFromParent();
1098 Changed = true;
1099 ++NumCSELoad;
1100 continue;
1101 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001102 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001103
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001104 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001105 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001106 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001107 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001108 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +00001109 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +00001110 continue;
1111 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001112
Sanjoy Das6de072a2017-01-17 20:15:47 +00001113 // If this instruction may read from memory or throw (and potentially read
1114 // from memory in the exception handler), forget LastStore. Load/store
1115 // intrinsics will indicate both a read and a write to memory. The target
1116 // may override this (e.g. so that a store intrinsic does not read from
1117 // memory, and thus will be treated the same as a regular store for
1118 // commoning purposes).
1119 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +00001120 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +00001121 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001122
Chris Lattner92bb0f92011-01-03 03:41:27 +00001123 // If this is a read-only call, process it.
1124 if (CallValue::canHandle(Inst)) {
1125 // If we have an available version of this call, and if it is the right
1126 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +00001127 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +00001128 if (InVal.first != nullptr &&
1129 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1130 Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001131 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
1132 << " to: " << *InVal.first << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001133 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001134 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001135 continue;
1136 }
Chandler Carruth7253bba2015-01-24 11:33:55 +00001137 if (!Inst->use_empty())
1138 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +00001139 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +00001140 Inst->eraseFromParent();
1141 Changed = true;
1142 ++NumCSECall;
1143 continue;
1144 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001145
Chris Lattner92bb0f92011-01-03 03:41:27 +00001146 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001147 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +00001148 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001149 continue;
1150 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001151
Philip Reamesdfd890d2015-08-27 01:32:33 +00001152 // A release fence requires that all stores complete before it, but does
1153 // not prevent the reordering of following loads 'before' the fence. As a
1154 // result, we don't need to consider it as writing to memory and don't need
1155 // to advance the generation. We do need to prevent DSE across the fence,
1156 // but that's handled above.
1157 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +00001158 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +00001159 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
1160 continue;
1161 }
1162
Philip Reamesae1f265b2015-12-16 01:01:30 +00001163 // write back DSE - If we write back the same value we just loaded from
1164 // the same location and haven't passed any intervening writes or ordering
1165 // operations, we can remove the write. The primary benefit is in allowing
1166 // the available load table to remain valid and value forward past where
1167 // the store originally was.
1168 if (MemInst.isValid() && MemInst.isStore()) {
1169 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +00001170 if (InVal.DefInst &&
1171 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +00001172 InVal.MatchingId == MemInst.getMatchingId() &&
1173 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +00001174 !MemInst.isVolatile() && MemInst.isUnordered() &&
Philip Reames0adbb192018-03-14 21:35:06 +00001175 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
1176 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1177 InVal.DefInst, Inst))) {
Geoff Berry8d846052016-08-31 19:24:10 +00001178 // It is okay to have a LastStore to a different pointer here if MemorySSA
1179 // tells us that the load and store are from the same memory generation.
1180 // In that case, LastStore should keep its present value since we're
1181 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +00001182 assert((!LastStore ||
1183 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +00001184 MemInst.getPointerOperand() ||
1185 MSSA) &&
1186 "can't have an intervening store if not using MemorySSA!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001187 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001188 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001189 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001190 continue;
1191 }
Geoff Berry8d846052016-08-31 19:24:10 +00001192 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +00001193 Inst->eraseFromParent();
1194 Changed = true;
1195 ++NumDSE;
1196 // We can avoid incrementing the generation count since we were able
1197 // to eliminate this store.
1198 continue;
1199 }
1200 }
1201
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001202 // Okay, this isn't something we can CSE at all. Check to see if it is
1203 // something that could modify memory. If so, our available memory values
1204 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +00001205 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001206 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +00001207
Chad Rosierf9327d62015-01-26 22:51:15 +00001208 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001209 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +00001210 // location with no intervening loads. Delete the earlier store.
1211 // At the moment, we don't remove ordered stores, but do remove
1212 // unordered atomic stores. There's no special requirement (for
1213 // unordered atomics) about removing atomic stores only in favor of
Kristina Brooks5b1e1c02019-03-12 07:08:19 +00001214 // other atomic stores since we were going to execute the non-atomic
Philip Reames15145fb2015-12-17 18:50:50 +00001215 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +00001216 if (LastStore) {
1217 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +00001218 assert(LastStoreMemInst.isUnordered() &&
1219 !LastStoreMemInst.isVolatile() &&
1220 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +00001221 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001222 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1223 << " due to: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001224 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001225 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001226 } else {
1227 removeMSSA(LastStore);
1228 LastStore->eraseFromParent();
1229 Changed = true;
1230 ++NumDSE;
1231 LastStore = nullptr;
1232 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001233 }
Philip Reames018dbf12014-11-18 17:46:32 +00001234 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001235 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001236
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001237 // Okay, we just invalidated anything we knew about loaded values. Try
1238 // to salvage *something* by remembering that the stored value is a live
1239 // version of the pointer. It is safe to forward from volatile stores
1240 // to non-volatile loads, so we don't have to check for volatility of
1241 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001242 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001243 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001244 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001245 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001246
Philip Reames15145fb2015-12-17 18:50:50 +00001247 // Remember that this was the last unordered store we saw for DSE. We
1248 // don't yet handle DSE on ordered or volatile stores since we don't
1249 // have a good way to model the ordering requirement for following
1250 // passes once the store is removed. We could insert a fence, but
1251 // since fences are slightly stronger than stores in their ordering,
1252 // it's not clear this is a profitable transform. Another option would
1253 // be to merge the ordering with that of the post dominating store.
1254 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +00001255 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001256 else
1257 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +00001258 }
1259 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001260 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001261
Chris Lattner18ae5432011-01-02 23:04:14 +00001262 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +00001263}
Chris Lattner18ae5432011-01-02 23:04:14 +00001264
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001265bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +00001266 // Note, deque is being used here because there is significant performance
1267 // gains over vector when the container becomes very large due to the
1268 // specific access patterns. For more information see the mailing list
1269 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +00001270 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +00001271 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001272
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001273 bool Changed = false;
1274
1275 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +00001276 nodesToProcess.push_back(new StackNode(
Philip Reames0adbb192018-03-14 21:35:06 +00001277 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1278 CurrentGeneration, DT.getRootNode(),
1279 DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001280
Alina Sbirlea73446cd2019-02-21 19:49:57 +00001281 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001282
1283 // Process the stack.
1284 while (!nodesToProcess.empty()) {
1285 // Grab the first item off the stack. Set the current generation, remove
1286 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +00001287 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001288
1289 // Initialize class members.
1290 CurrentGeneration = NodeToProcess->currentGeneration();
1291
1292 // Check if the node needs to be processed.
1293 if (!NodeToProcess->isProcessed()) {
1294 // Process the node.
1295 Changed |= processNode(NodeToProcess->node());
1296 NodeToProcess->childGeneration(CurrentGeneration);
1297 NodeToProcess->process();
1298 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1299 // Push the next child onto the stack.
1300 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +00001301 nodesToProcess.push_back(
Philip Reames0adbb192018-03-14 21:35:06 +00001302 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1303 AvailableCalls, NodeToProcess->childGeneration(),
1304 child, child->begin(), child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001305 } else {
1306 // It has been processed, and there are no more children to process,
1307 // so delete it and pop it off the stack.
1308 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +00001309 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001310 }
1311 } // while (!nodes...)
1312
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001313 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +00001314}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001315
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001316PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00001317 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00001318 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1319 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1320 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001321 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001322 auto *MSSA =
1323 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001324
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001325 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001326
1327 if (!CSE.run())
1328 return PreservedAnalyses::all();
1329
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001330 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001331 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001332 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001333 if (UseMemorySSA)
1334 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001335 return PA;
1336}
1337
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001338namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001339
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001340/// A simple and fast domtree-based CSE pass.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001341///
1342/// This pass does a simple depth-first walk over the dominator tree,
1343/// eliminating trivially redundant instructions and using instsimplify to
1344/// canonicalize things as it goes. It is intended to be fast and catch obvious
1345/// cases so that instcombine and other passes are more effective. It is
1346/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001347template<bool UseMemorySSA>
1348class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001349public:
1350 static char ID;
1351
Geoff Berry8d846052016-08-31 19:24:10 +00001352 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1353 if (UseMemorySSA)
1354 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1355 else
1356 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001357 }
1358
1359 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001360 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001361 return false;
1362
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001363 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001364 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001365 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001366 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001367 auto *MSSA =
1368 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001369
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001370 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001371
1372 return CSE.run();
1373 }
1374
1375 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001376 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001377 AU.addRequired<DominatorTreeWrapperPass>();
1378 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001379 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001380 if (UseMemorySSA) {
1381 AU.addRequired<MemorySSAWrapperPass>();
1382 AU.addPreserved<MemorySSAWrapperPass>();
1383 }
James Molloyefbba722015-09-10 10:22:12 +00001384 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001385 AU.setPreservesCFG();
1386 }
1387};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001388
1389} // end anonymous namespace
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001390
Geoff Berry8d846052016-08-31 19:24:10 +00001391using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001392
Geoff Berry8d846052016-08-31 19:24:10 +00001393template<>
1394char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001395
1396INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1397 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001398INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001399INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001400INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1401INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1402INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001403
1404using EarlyCSEMemSSALegacyPass =
1405 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1406
1407template<>
1408char EarlyCSEMemSSALegacyPass::ID = 0;
1409
1410FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1411 if (UseMemorySSA)
1412 return new EarlyCSEMemSSALegacyPass();
1413 else
1414 return new EarlyCSELegacyPass();
1415}
1416
1417INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1418 "Early CSE w/ MemorySSA", false, false)
1419INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001420INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001421INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1422INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1423INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1424INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1425 "Early CSE w/ MemorySSA", false, false)