blob: 565745d12e99e0bf38176accd401a82a87bd7f66 [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"
Eugene Zelenko3b879392017-10-13 21:17:07 +000016#include "llvm/ADT/DenseMapInfo.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000017#include "llvm/ADT/Hashing.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000019#include "llvm/ADT/ScopedHashTable.h"
Davide Italiano0dc47782017-06-14 19:29:53 +000020#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000021#include "llvm/ADT/SmallVector.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000022#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000023#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000024#include "llvm/Analysis/GlobalsModRef.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"
Eugene Zelenko3b879392017-10-13 21:17:07 +000057#include <cassert>
Lenny Maiorani9eefc812014-09-20 13:29:20 +000058#include <deque>
Eugene Zelenko3b879392017-10-13 21:17:07 +000059#include <memory>
60#include <utility>
61
Chris Lattner704541b2011-01-02 21:47:05 +000062using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000063using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000064
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "early-cse"
66
Chris Lattner4cb36542011-01-03 03:28:23 +000067STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
68STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000069STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000070STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
71STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000072STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000073
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000074DEBUG_COUNTER(CSECounter, "early-cse",
75 "Controls which instructions are removed");
76
Chris Lattner79d83062011-01-03 02:20:48 +000077//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000078// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000079//===----------------------------------------------------------------------===//
80
Chris Lattner704541b2011-01-02 21:47:05 +000081namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +000082
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000083/// Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000084struct SimpleValue {
85 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000086
Chandler Carruth7253bba2015-01-24 11:33:55 +000087 SimpleValue(Instruction *I) : Inst(I) {
88 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
89 }
Nadav Rotem465834c2012-07-24 10:51:42 +000090
Chandler Carruth7253bba2015-01-24 11:33:55 +000091 bool isSentinel() const {
92 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
93 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
94 }
Nadav Rotem465834c2012-07-24 10:51:42 +000095
Chandler Carruth7253bba2015-01-24 11:33:55 +000096 static bool canHandle(Instruction *Inst) {
97 // This can only handle non-void readnone functions.
98 if (CallInst *CI = dyn_cast<CallInst>(Inst))
99 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
100 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
101 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
102 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
103 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
104 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
105 }
106};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000107
108} // end anonymous namespace
Chris Lattner18ae5432011-01-02 23:04:14 +0000109
110namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000111
Chandler Carruth7253bba2015-01-24 11:33:55 +0000112template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +0000113 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000114 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000115 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000116
Chris Lattner79d83062011-01-03 02:20:48 +0000117 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000118 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000119 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000120
Chris Lattner79d83062011-01-03 02:20:48 +0000121 static unsigned getHashValue(SimpleValue Val);
122 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +0000123};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000124
125} // end namespace llvm
Chris Lattner18ae5432011-01-02 23:04:14 +0000126
Chris Lattner79d83062011-01-03 02:20:48 +0000127unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000128 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +0000129 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000130 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000131 Value *LHS = BinOp->getOperand(0);
132 Value *RHS = BinOp->getOperand(1);
133 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
134 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000135
Michael Ilseman336cb792012-10-09 16:57:38 +0000136 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000137 }
138
Michael Ilseman336cb792012-10-09 16:57:38 +0000139 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
140 Value *LHS = CI->getOperand(0);
141 Value *RHS = CI->getOperand(1);
142 CmpInst::Predicate Pred = CI->getPredicate();
143 if (Inst->getOperand(0) > Inst->getOperand(1)) {
144 std::swap(LHS, RHS);
145 Pred = CI->getSwappedPredicate();
146 }
147 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
148 }
149
Sanjay Patel558a4652017-12-13 22:57:35 +0000150 // Hash min/max/abs (cmp + select) to allow for commuted operands.
151 // Min/max may also have non-canonical compare predicate (eg, the compare for
152 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
153 // compare.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000154 Value *A, *B;
155 SelectPatternFlavor SPF = matchSelectPattern(Inst, A, B).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000156 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000157 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
Craig Topperf14e62c2018-05-21 18:42:42 +0000158 SPF == SPF_UMIN || SPF == SPF_UMAX) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000159 if (A > B)
160 std::swap(A, B);
161 return hash_combine(Inst->getOpcode(), SPF, A, B);
162 }
Craig Topperf14e62c2018-05-21 18:42:42 +0000163 if (SPF == SPF_ABS || SPF == SPF_NABS) {
164 // ABS/NABS always puts the input in A and its negation in B.
165 return hash_combine(Inst->getOpcode(), SPF, A, B);
166 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000167
Michael Ilseman336cb792012-10-09 16:57:38 +0000168 if (CastInst *CI = dyn_cast<CastInst>(Inst))
169 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
170
171 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
172 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
173 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
174
175 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
176 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
177 IVI->getOperand(1),
178 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
179
180 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
181 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
182 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000183 isa<ShuffleVectorInst>(Inst)) &&
184 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000185
Chris Lattner02a97762011-01-03 01:10:08 +0000186 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000187 return hash_combine(
188 Inst->getOpcode(),
189 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000190}
191
Chris Lattner79d83062011-01-03 02:20:48 +0000192bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000193 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
194
195 if (LHS.isSentinel() || RHS.isSentinel())
196 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000197
Chandler Carruth7253bba2015-01-24 11:33:55 +0000198 if (LHSI->getOpcode() != RHSI->getOpcode())
199 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000200 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000201 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000202
203 // If we're not strictly identical, we still might be a commutable instruction
204 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
205 if (!LHSBinOp->isCommutative())
206 return false;
207
Chandler Carruth7253bba2015-01-24 11:33:55 +0000208 assert(isa<BinaryOperator>(RHSI) &&
209 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000210 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
211
Michael Ilseman336cb792012-10-09 16:57:38 +0000212 // Commuted equality
213 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000214 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000215 }
216 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000217 assert(isa<CmpInst>(RHSI) &&
218 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000219 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
220 // Commuted equality
221 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000222 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
223 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000224 }
225
Sanjay Patel558a4652017-12-13 22:57:35 +0000226 // Min/max/abs can occur with commuted operands, non-canonical predicates,
227 // and/or non-canonical operands.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000228 Value *LHSA, *LHSB;
229 SelectPatternFlavor LSPF = matchSelectPattern(LHSI, LHSA, LHSB).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000230 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000231 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
Sanjay Patel558a4652017-12-13 22:57:35 +0000232 LSPF == SPF_UMIN || LSPF == SPF_UMAX ||
233 LSPF == SPF_ABS || LSPF == SPF_NABS) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000234 Value *RHSA, *RHSB;
235 SelectPatternFlavor RSPF = matchSelectPattern(RHSI, RHSA, RHSB).Flavor;
Craig Topperf14e62c2018-05-21 18:42:42 +0000236 if (LSPF == RSPF) {
237 // Abs results are placed in a defined order by matchSelectPattern.
238 if (LSPF == SPF_ABS || LSPF == SPF_NABS)
239 return LHSA == RHSA && LHSB == RHSB;
240 return ((LHSA == RHSA && LHSB == RHSB) ||
241 (LHSA == RHSB && LHSB == RHSA));
242 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000243 }
244
Michael Ilseman336cb792012-10-09 16:57:38 +0000245 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000246}
247
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000248//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000249// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000250//===----------------------------------------------------------------------===//
251
252namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254/// Struct representing the available call values in the scoped hash
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000255/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000256struct CallValue {
257 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000258
Chandler Carruth7253bba2015-01-24 11:33:55 +0000259 CallValue(Instruction *I) : Inst(I) {
260 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
261 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000262
Chandler Carruth7253bba2015-01-24 11:33:55 +0000263 bool isSentinel() const {
264 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
265 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
266 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000267
Chandler Carruth7253bba2015-01-24 11:33:55 +0000268 static bool canHandle(Instruction *Inst) {
269 // Don't value number anything that returns void.
270 if (Inst->getType()->isVoidTy())
271 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000272
Chandler Carruth7253bba2015-01-24 11:33:55 +0000273 CallInst *CI = dyn_cast<CallInst>(Inst);
274 if (!CI || !CI->onlyReadsMemory())
275 return false;
276 return true;
277 }
278};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000279
280} // end anonymous namespace
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000281
282namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000283
Chandler Carruth7253bba2015-01-24 11:33:55 +0000284template <> struct DenseMapInfo<CallValue> {
285 static inline CallValue getEmptyKey() {
286 return DenseMapInfo<Instruction *>::getEmptyKey();
287 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000288
Chandler Carruth7253bba2015-01-24 11:33:55 +0000289 static inline CallValue getTombstoneKey() {
290 return DenseMapInfo<Instruction *>::getTombstoneKey();
291 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000292
Chandler Carruth7253bba2015-01-24 11:33:55 +0000293 static unsigned getHashValue(CallValue Val);
294 static bool isEqual(CallValue LHS, CallValue RHS);
295};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000296
297} // end namespace llvm
Chandler Carruth7253bba2015-01-24 11:33:55 +0000298
Chris Lattner92bb0f92011-01-03 03:41:27 +0000299unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000300 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000301 // Hash all of the operands as pointers and mix in the opcode.
302 return hash_combine(
303 Inst->getOpcode(),
304 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000305}
306
Chris Lattner92bb0f92011-01-03 03:41:27 +0000307bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000308 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000309 if (LHS.isSentinel() || RHS.isSentinel())
310 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000311 return LHSI->isIdenticalTo(RHSI);
312}
313
Chris Lattner79d83062011-01-03 02:20:48 +0000314//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000315// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000316//===----------------------------------------------------------------------===//
317
Chris Lattner18ae5432011-01-02 23:04:14 +0000318namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320/// A simple and fast domtree-based CSE pass.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000321///
322/// This pass does a simple depth-first walk over the dominator tree,
323/// eliminating trivially redundant instructions and using instsimplify to
324/// canonicalize things as it goes. It is intended to be fast and catch obvious
325/// cases so that instcombine and other passes are more effective. It is
326/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000327class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000328public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000329 const TargetLibraryInfo &TLI;
330 const TargetTransformInfo &TTI;
331 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000332 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000333 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000334 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000335 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000336
337 using AllocatorTy =
338 RecyclingAllocator<BumpPtrAllocator,
339 ScopedHashTableVal<SimpleValue, Value *>>;
340 using ScopedHTType =
341 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
342 AllocatorTy>;
Nadav Rotem465834c2012-07-24 10:51:42 +0000343
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000344 /// A scoped hash table of the current values of all of our simple
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000345 /// scalar expressions.
346 ///
347 /// As we walk down the domtree, we look to see if instructions are in this:
348 /// if so, we replace them with what we find, otherwise we insert them so
349 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000350 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000351
Hiroshi Inouef2096492018-06-14 05:41:49 +0000352 /// A scoped hash table of the current values of previously encountered
353 /// memory locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000354 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000355 /// This allows us to get efficient access to dominating loads or stores when
356 /// we have a fully redundant load. In addition to the most recent load, we
357 /// keep track of a generation count of the read, which is compared against
358 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000359 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000360 /// CSE loads with other loads that have no intervening store. Ordering
361 /// events (such as fences or atomic instructions) increment the generation
362 /// count as well; essentially, we model these as writes to all possible
363 /// locations. Note that atomic and/or volatile loads and stores can be
364 /// present the table; it is the responsibility of the consumer to inspect
365 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000366 struct LoadValue {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000367 Instruction *DefInst = nullptr;
368 unsigned Generation = 0;
369 int MatchingId = -1;
370 bool IsAtomic = false;
Philip Reames0adbb192018-03-14 21:35:06 +0000371
Eugene Zelenko3b879392017-10-13 21:17:07 +0000372 LoadValue() = default;
Geoff Berry5ae272c2016-04-28 15:22:37 +0000373 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reamesca587fe2018-03-15 17:29:32 +0000374 bool IsAtomic)
Sanjoy Das07c65212016-06-16 20:47:57 +0000375 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reamesca587fe2018-03-15 17:29:32 +0000376 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000377 };
Eugene Zelenko3b879392017-10-13 21:17:07 +0000378
379 using LoadMapAllocator =
380 RecyclingAllocator<BumpPtrAllocator,
381 ScopedHashTableVal<Value *, LoadValue>>;
382 using LoadHTType =
383 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
384 LoadMapAllocator>;
385
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000386 LoadHTType AvailableLoads;
Philip Reames0adbb192018-03-14 21:35:06 +0000387
388 // A scoped hash table mapping memory locations (represented as typed
389 // addresses) to generation numbers at which that memory location became
390 // (henceforth indefinitely) invariant.
391 using InvariantMapAllocator =
392 RecyclingAllocator<BumpPtrAllocator,
393 ScopedHashTableVal<MemoryLocation, unsigned>>;
394 using InvariantHTType =
395 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
396 InvariantMapAllocator>;
397 InvariantHTType AvailableInvariants;
Nadav Rotem465834c2012-07-24 10:51:42 +0000398
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000399 /// A scoped hash table of the current values of read-only call
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000400 /// values.
401 ///
402 /// It uses the same generation count as loads.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000403 using CallHTType =
404 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000405 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000406
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000407 /// This is the current generation of the memory value.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000408 unsigned CurrentGeneration = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000409
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000410 /// Set up the EarlyCSE runner for a particular function.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000411 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
412 const TargetTransformInfo &TTI, DominatorTree &DT,
413 AssumptionCache &AC, MemorySSA *MSSA)
414 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Eugene Zelenko3b879392017-10-13 21:17:07 +0000415 MSSAUpdater(llvm::make_unique<MemorySSAUpdater>(MSSA)) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000416
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000417 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000418
419private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000420 // Almost a POD, but needs to call the constructors for the scoped hash
421 // tables so that a new scope gets pushed on. These are RAII so that the
422 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000423 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000424 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000425 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000426 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
427 : Scope(AvailableValues), LoadScope(AvailableLoads),
428 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
Eugene Zelenko3b879392017-10-13 21:17:07 +0000429 NodeScope(const NodeScope &) = delete;
430 NodeScope &operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000431
Chandler Carruth7253bba2015-01-24 11:33:55 +0000432 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000433 ScopedHTType::ScopeTy Scope;
434 LoadHTType::ScopeTy LoadScope;
Philip Reames0adbb192018-03-14 21:35:06 +0000435 InvariantHTType::ScopeTy InvariantScope;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000436 CallHTType::ScopeTy CallScope;
437 };
438
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000439 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000440 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000441 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000442 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000443 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000444 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000445 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000446 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
447 unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
448 DomTreeNode::iterator end)
Chandler Carruth7253bba2015-01-24 11:33:55 +0000449 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Philip Reames0adbb192018-03-14 21:35:06 +0000450 EndIter(end),
451 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
452 AvailableCalls)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000453 {}
454 StackNode(const StackNode &) = delete;
455 StackNode &operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000456
457 // Accessors.
458 unsigned currentGeneration() { return CurrentGeneration; }
459 unsigned childGeneration() { return ChildGeneration; }
460 void childGeneration(unsigned generation) { ChildGeneration = generation; }
461 DomTreeNode *node() { return Node; }
462 DomTreeNode::iterator childIter() { return ChildIter; }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000463
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000464 DomTreeNode *nextChild() {
465 DomTreeNode *child = *ChildIter;
466 ++ChildIter;
467 return child;
468 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000469
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000470 DomTreeNode::iterator end() { return EndIter; }
471 bool isProcessed() { return Processed; }
472 void process() { Processed = true; }
473
Chandler Carruth7253bba2015-01-24 11:33:55 +0000474 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000475 unsigned CurrentGeneration;
476 unsigned ChildGeneration;
477 DomTreeNode *Node;
478 DomTreeNode::iterator ChildIter;
479 DomTreeNode::iterator EndIter;
480 NodeScope Scopes;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000481 bool Processed = false;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000482 };
483
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000484 /// Wrapper class to handle memory instructions, including loads,
Chad Rosierf9327d62015-01-26 22:51:15 +0000485 /// stores and intrinsic loads and stores defined by the target.
486 class ParseMemoryInst {
487 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000488 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000489 : Inst(Inst) {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000490 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000491 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000492 IsTargetMemInst = true;
493 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000494
Philip Reames9e5e2d62015-12-07 22:41:23 +0000495 bool isLoad() const {
496 if (IsTargetMemInst) return Info.ReadMem;
497 return isa<LoadInst>(Inst);
498 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000499
Philip Reames9e5e2d62015-12-07 22:41:23 +0000500 bool isStore() const {
501 if (IsTargetMemInst) return Info.WriteMem;
502 return isa<StoreInst>(Inst);
503 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000504
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000505 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000506 if (IsTargetMemInst)
507 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000508 return Inst->isAtomic();
509 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000510
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000511 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000512 if (IsTargetMemInst)
513 return Info.isUnordered();
514
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000515 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
516 return LI->isUnordered();
517 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
518 return SI->isUnordered();
519 }
520 // Conservative answer
521 return !Inst->isAtomic();
522 }
523
524 bool isVolatile() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000525 if (IsTargetMemInst)
526 return Info.IsVolatile;
527
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000528 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
529 return LI->isVolatile();
530 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
531 return SI->isVolatile();
532 }
533 // Conservative answer
534 return true;
535 }
536
Sanjoy Das07c65212016-06-16 20:47:57 +0000537 bool isInvariantLoad() const {
538 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000539 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000540 return false;
541 }
Junmo Park80440eb2016-02-18 10:09:20 +0000542
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000543 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000544 return (getPointerOperand() == Inst.getPointerOperand() &&
545 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000546 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000547
Philip Reames9e5e2d62015-12-07 22:41:23 +0000548 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000549
Chad Rosierf9327d62015-01-26 22:51:15 +0000550 // For regular (non-intrinsic) loads/stores, this is set to -1. For
551 // intrinsic loads/stores, the id is retrieved from the corresponding
552 // field in the MemIntrinsicInfo structure. That field contains
553 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000554 int getMatchingId() const {
555 if (IsTargetMemInst) return Info.MatchingId;
556 return -1;
557 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000558
Philip Reames9e5e2d62015-12-07 22:41:23 +0000559 Value *getPointerOperand() const {
560 if (IsTargetMemInst) return Info.PtrVal;
Renato Golin038ede22018-03-09 21:05:58 +0000561 return getLoadStorePointerOperand(Inst);
Philip Reames9e5e2d62015-12-07 22:41:23 +0000562 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000563
Philip Reames9e5e2d62015-12-07 22:41:23 +0000564 bool mayReadFromMemory() const {
565 if (IsTargetMemInst) return Info.ReadMem;
566 return Inst->mayReadFromMemory();
567 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000568
Philip Reames9e5e2d62015-12-07 22:41:23 +0000569 bool mayWriteToMemory() const {
570 if (IsTargetMemInst) return Info.WriteMem;
571 return Inst->mayWriteToMemory();
572 }
573
574 private:
Eugene Zelenko3b879392017-10-13 21:17:07 +0000575 bool IsTargetMemInst = false;
Philip Reames9e5e2d62015-12-07 22:41:23 +0000576 MemIntrinsicInfo Info;
577 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000578 };
579
Chris Lattner18ae5432011-01-02 23:04:14 +0000580 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000581
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000582 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
583 const BasicBlock *BB, const BasicBlock *Pred);
584
Chad Rosierf9327d62015-01-26 22:51:15 +0000585 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000586 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000587 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000588 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000589 return SI->getValueOperand();
590 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000591 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
592 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000593 }
Geoff Berry8d846052016-08-31 19:24:10 +0000594
Philip Reames0adbb192018-03-14 21:35:06 +0000595 /// Return true if the instruction is known to only operate on memory
596 /// provably invariant in the given "generation".
597 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
598
Geoff Berry8d846052016-08-31 19:24:10 +0000599 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
600 Instruction *EarlierInst, Instruction *LaterInst);
601
602 void removeMSSA(Instruction *Inst) {
603 if (!MSSA)
604 return;
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000605 // Removing a store here can leave MemorySSA in an unoptimized state by
606 // creating MemoryPhis that have identical arguments and by creating
Geoff Berry68154682016-10-24 15:54:00 +0000607 // MemoryUses whose defining access is not an actual clobber. We handle the
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000608 // phi case eagerly here. The non-optimized MemoryUse case is lazily
609 // updated by MemorySSA getClobberingMemoryAccess.
Geoff Berry68154682016-10-24 15:54:00 +0000610 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst)) {
611 // Optimize MemoryPhi nodes that may become redundant by having all the
612 // same input values once MA is removed.
Davide Italiano0dc47782017-06-14 19:29:53 +0000613 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
Geoff Berry68154682016-10-24 15:54:00 +0000614 SmallVector<MemoryAccess *, 8> WorkQueue;
615 WorkQueue.push_back(MA);
616 // Process MemoryPhi nodes in FIFO order using a ever-growing vector since
617 // we shouldn't be processing that many phis and this will avoid an
618 // allocation in almost all cases.
619 for (unsigned I = 0; I < WorkQueue.size(); ++I) {
620 MemoryAccess *WI = WorkQueue[I];
621
622 for (auto *U : WI->users())
623 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U))
Davide Italiano0dc47782017-06-14 19:29:53 +0000624 PhisToCheck.insert(MP);
Geoff Berry68154682016-10-24 15:54:00 +0000625
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000626 MSSAUpdater->removeMemoryAccess(WI);
Geoff Berry68154682016-10-24 15:54:00 +0000627
628 for (MemoryPhi *MP : PhisToCheck) {
629 MemoryAccess *FirstIn = MP->getIncomingValue(0);
Eugene Zelenko3b879392017-10-13 21:17:07 +0000630 if (llvm::all_of(MP->incoming_values(),
631 [=](Use &In) { return In == FirstIn; }))
Geoff Berry68154682016-10-24 15:54:00 +0000632 WorkQueue.push_back(MP);
633 }
634 PhisToCheck.clear();
635 }
636 }
Geoff Berry8d846052016-08-31 19:24:10 +0000637 }
Chris Lattner704541b2011-01-02 21:47:05 +0000638};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000639
640} // end anonymous namespace
Chris Lattner704541b2011-01-02 21:47:05 +0000641
Geoff Berry68154682016-10-24 15:54:00 +0000642/// Determine if the memory referenced by LaterInst is from the same heap
643/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000644/// This is currently called in two scenarios:
645///
646/// load p
647/// ...
648/// load p
649///
650/// and
651///
652/// x = load p
653/// ...
654/// store x, p
655///
656/// in both cases we want to verify that there are no possible writes to the
657/// memory referenced by p between the earlier and later instruction.
658bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
659 unsigned LaterGeneration,
660 Instruction *EarlierInst,
661 Instruction *LaterInst) {
662 // Check the simple memory generation tracking first.
663 if (EarlierGeneration == LaterGeneration)
664 return true;
665
666 if (!MSSA)
667 return false;
668
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000669 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
670 // read/write memory, then we can safely return true here.
671 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
672 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
673 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
674 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
675 // with the default optimization pipeline.
676 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
677 if (!EarlierMA)
678 return true;
679 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
680 if (!LaterMA)
681 return true;
682
Geoff Berry8d846052016-08-31 19:24:10 +0000683 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
684 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
685 // EarlierInst and LaterInst and neither can any other write that potentially
686 // clobbers LaterInst.
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000687 MemoryAccess *LaterDef =
688 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000689 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000690}
691
Philip Reames0adbb192018-03-14 21:35:06 +0000692bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
693 // A location loaded from with an invariant_load is assumed to *never* change
694 // within the visible scope of the compilation.
695 if (auto *LI = dyn_cast<LoadInst>(I))
696 if (LI->getMetadata(LLVMContext::MD_invariant_load))
697 return true;
698
699 auto MemLocOpt = MemoryLocation::getOrNone(I);
700 if (!MemLocOpt)
701 // "target" intrinsic forms of loads aren't currently known to
702 // MemoryLocation::get. TODO
703 return false;
704 MemoryLocation MemLoc = *MemLocOpt;
705 if (!AvailableInvariants.count(MemLoc))
706 return false;
707
708 // Is the generation at which this became invariant older than the
709 // current one?
710 return AvailableInvariants.lookup(MemLoc) <= GenAt;
711}
712
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000713bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
714 const BranchInst *BI, const BasicBlock *BB,
715 const BasicBlock *Pred) {
716 assert(BI->isConditional() && "Should be a conditional branch!");
717 assert(BI->getCondition() == CondInst && "Wrong condition?");
718 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
719 auto *TorF = (BI->getSuccessor(0) == BB)
720 ? ConstantInt::getTrue(BB->getContext())
721 : ConstantInt::getFalse(BB->getContext());
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000722 auto MatchBinOp = [](Instruction *I, unsigned Opcode) {
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000723 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I))
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000724 return BOp->getOpcode() == Opcode;
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000725 return false;
726 };
727 // If the condition is AND operation, we can propagate its operands into the
728 // true branch. If it is OR operation, we can propagate them into the false
729 // branch.
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000730 unsigned PropagateOpcode =
731 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000732
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000733 bool MadeChanges = false;
734 SmallVector<Instruction *, 4> WorkList;
735 SmallPtrSet<Instruction *, 4> Visited;
736 WorkList.push_back(CondInst);
737 while (!WorkList.empty()) {
738 Instruction *Curr = WorkList.pop_back_val();
739
740 AvailableValues.insert(Curr, TorF);
741 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
742 << Curr->getName() << "' as " << *TorF << " in "
743 << BB->getName() << "\n");
744 if (!DebugCounter::shouldExecute(CSECounter)) {
745 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
746 } else {
747 // Replace all dominated uses with the known value.
748 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
749 BasicBlockEdge(Pred, BB))) {
750 NumCSECVP += Count;
751 MadeChanges = true;
752 }
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000753 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000754
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000755 if (MatchBinOp(Curr, PropagateOpcode))
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000756 for (auto &Op : cast<BinaryOperator>(Curr)->operands())
757 if (Instruction *OPI = dyn_cast<Instruction>(Op))
758 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
759 WorkList.push_back(OPI);
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000760 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000761
762 return MadeChanges;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000763}
764
Chris Lattner18ae5432011-01-02 23:04:14 +0000765bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000766 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000767 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000768
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000769 // If this block has a single predecessor, then the predecessor is the parent
770 // of the domtree node and all of the live out memory values are still current
771 // in this block. If this block has multiple predecessors, then they could
772 // have invalidated the live-out memory values of our parent value. For now,
773 // just be conservative and invalidate memory if this block has multiple
774 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000775 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000776 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000777
Philip Reames7c78ef72015-05-22 23:53:24 +0000778 // If this node has a single predecessor which ends in a conditional branch,
779 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000780 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000781 // which reaches this block where the condition might hold a different
782 // value. Since we're adding this to the scoped hash table (like any other
783 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000784 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
785 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
786 if (BI && BI->isConditional()) {
787 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000788 if (CondInst && SimpleValue::canHandle(CondInst))
789 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000790 }
791 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000792
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000793 /// LastStore - Keep track of the last non-volatile store that we saw... for
794 /// as long as there in no instruction that reads memory. If we see a store
795 /// to the same location, we delete the dead store. This zaps trivial dead
796 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000797 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000798
Chris Lattner18ae5432011-01-02 23:04:14 +0000799 // See if any instructions in the block can be eliminated. If so, do it. If
800 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000801 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000802 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000803
Chris Lattner18ae5432011-01-02 23:04:14 +0000804 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000805 if (isInstructionTriviallyDead(Inst, &TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000806 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000807 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000808 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000809 continue;
810 }
Petar Jovanovic1d26c7e2018-01-09 15:08:37 +0000811 salvageDebugInfo(*Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000812 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000813 Inst->eraseFromParent();
814 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000815 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000816 continue;
817 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000818
Hal Finkel1e16fa32014-11-03 20:21:32 +0000819 // Skip assume intrinsics, they don't really have side effects (although
820 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000821 // and this pass will not bother with its removal. However, we should mark
822 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000823 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000824 auto *CondI =
825 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
826 if (CondI && SimpleValue::canHandle(CondI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000827 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst
828 << '\n');
Max Kazantsev531db9a2017-04-28 06:25:39 +0000829 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
830 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000831 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000832 continue;
833 }
834
Dan Gohman2c74fe92017-11-08 21:59:51 +0000835 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
836 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000837 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n');
Dan Gohman2c74fe92017-11-08 21:59:51 +0000838 continue;
839 }
840
Philip Reames0adbb192018-03-14 21:35:06 +0000841 // We can skip all invariant.start intrinsics since they only read memory,
842 // and we can forward values across it. For invariant starts without
843 // invariant ends, we can use the fact that the invariantness never ends to
844 // start a scope in the current generaton which is true for all future
845 // generations. Also, we dont need to consume the last store since the
846 // semantics of invariant.start allow us to perform DSE of the last
847 // store, if there was a store following invariant.start. Consider:
Anna Thomasb2d12b82016-08-09 20:00:47 +0000848 //
849 // store 30, i8* p
850 // invariant.start(p)
851 // store 40, i8* p
852 // We can DSE the store to 30, since the store 40 to invariant location p
853 // causes undefined behaviour.
Philip Reames0adbb192018-03-14 21:35:06 +0000854 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
855 // If there are any uses, the scope might end.
856 if (!Inst->use_empty())
857 continue;
858 auto *CI = cast<CallInst>(Inst);
859 MemoryLocation MemLoc = MemoryLocation::getForArgument(CI, 1, TLI);
Philip Reames422024a2018-03-15 18:12:27 +0000860 // Don't start a scope if we already have a better one pushed
861 if (!AvailableInvariants.count(MemLoc))
862 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Anna Thomasb2d12b82016-08-09 20:00:47 +0000863 continue;
Philip Reames0adbb192018-03-14 21:35:06 +0000864 }
Anna Thomasb2d12b82016-08-09 20:00:47 +0000865
Sanjoy Dasee81b232016-04-29 21:52:58 +0000866 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000867 if (auto *CondI =
868 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000869 if (SimpleValue::canHandle(CondI)) {
870 // Do we already know the actual value of this condition?
871 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
872 // Is the condition known to be true?
873 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000874 cast<ConstantInt>(KnownCond)->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000875 LLVM_DEBUG(dbgs()
876 << "EarlyCSE removing guard: " << *Inst << '\n');
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000877 removeMSSA(Inst);
878 Inst->eraseFromParent();
879 Changed = true;
880 continue;
881 } else
882 // Use the known value if it wasn't true.
883 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
884 }
885 // The condition we're on guarding here is true for all dominated
886 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000887 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000888 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000889 }
890
891 // Guard intrinsics read all memory, but don't write any memory.
892 // Accordingly, don't update the generation but consume the last store (to
893 // avoid an incorrect DSE).
894 LastStore = nullptr;
895 continue;
896 }
897
Chris Lattner18ae5432011-01-02 23:04:14 +0000898 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
899 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000900 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000901 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V
902 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000903 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000904 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000905 } else {
906 bool Killed = false;
907 if (!Inst->use_empty()) {
908 Inst->replaceAllUsesWith(V);
909 Changed = true;
910 }
911 if (isInstructionTriviallyDead(Inst, &TLI)) {
912 removeMSSA(Inst);
913 Inst->eraseFromParent();
914 Changed = true;
915 Killed = true;
916 }
917 if (Changed)
918 ++NumSimplify;
919 if (Killed)
920 continue;
David Majnemerb8da3a22016-06-25 00:04:10 +0000921 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000922 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000923
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000924 // If this is a simple instruction that we can value number, process it.
925 if (SimpleValue::canHandle(Inst)) {
926 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000927 if (Value *V = AvailableValues.lookup(Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000928 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V
929 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000930 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000931 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000932 continue;
933 }
David Majnemer9554c132016-04-22 06:37:45 +0000934 if (auto *I = dyn_cast<Instruction>(V))
935 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000936 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000937 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000938 Inst->eraseFromParent();
939 Changed = true;
940 ++NumCSE;
941 continue;
942 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000943
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000944 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000945 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000946 continue;
947 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000948
Chad Rosierf9327d62015-01-26 22:51:15 +0000949 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000950 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000951 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000952 // (conservatively) we can't peak past the ordering implied by this
953 // operation, but we can add this load to our set of available values
954 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000955 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000956 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000957 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000958
Philip Reamesca587fe2018-03-15 17:29:32 +0000959 if (MemInst.isInvariantLoad()) {
960 // If we pass an invariant load, we know that memory location is
961 // indefinitely constant from the moment of first dereferenceability.
Philip Reames422024a2018-03-15 18:12:27 +0000962 // We conservatively treat the invariant_load as that moment. If we
963 // pass a invariant load after already establishing a scope, don't
964 // restart it since we want to preserve the earliest point seen.
Philip Reamesca587fe2018-03-15 17:29:32 +0000965 auto MemLoc = MemoryLocation::get(Inst);
Philip Reames422024a2018-03-15 18:12:27 +0000966 if (!AvailableInvariants.count(MemLoc))
967 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Philip Reamesca587fe2018-03-15 17:29:32 +0000968 }
969
Chris Lattner92bb0f92011-01-03 03:41:27 +0000970 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000971 // generation or the load is known to be from an invariant location,
972 // replace this instruction.
973 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000974 // If either the dominating load or the current load are invariant, then
975 // we can assume the current load loads the same value as the dominating
976 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000977 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000978 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000979 InVal.MatchingId == MemInst.getMatchingId() &&
980 // We don't yet handle removing loads with ordering of any kind.
981 !MemInst.isVolatile() && MemInst.isUnordered() &&
982 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000983 InVal.IsAtomic >= MemInst.isAtomic() &&
Philip Reamesca587fe2018-03-15 17:29:32 +0000984 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
Geoff Berry8d846052016-08-31 19:24:10 +0000985 isSameMemGeneration(InVal.Generation, CurrentGeneration,
986 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000987 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000988 if (Op != nullptr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000989 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
990 << " to: " << *InVal.DefInst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000991 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000992 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000993 continue;
994 }
Chad Rosierf9327d62015-01-26 22:51:15 +0000995 if (!Inst->use_empty())
996 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +0000997 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +0000998 Inst->eraseFromParent();
999 Changed = true;
1000 ++NumCSELoad;
1001 continue;
1002 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001003 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001004
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001005 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001006 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001007 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001008 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001009 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +00001010 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +00001011 continue;
1012 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001013
Sanjoy Das6de072a2017-01-17 20:15:47 +00001014 // If this instruction may read from memory or throw (and potentially read
1015 // from memory in the exception handler), forget LastStore. Load/store
1016 // intrinsics will indicate both a read and a write to memory. The target
1017 // may override this (e.g. so that a store intrinsic does not read from
1018 // memory, and thus will be treated the same as a regular store for
1019 // commoning purposes).
1020 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +00001021 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +00001022 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001023
Chris Lattner92bb0f92011-01-03 03:41:27 +00001024 // If this is a read-only call, process it.
1025 if (CallValue::canHandle(Inst)) {
1026 // If we have an available version of this call, and if it is the right
1027 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +00001028 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +00001029 if (InVal.first != nullptr &&
1030 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1031 Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001032 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
1033 << " to: " << *InVal.first << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001034 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001035 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001036 continue;
1037 }
Chandler Carruth7253bba2015-01-24 11:33:55 +00001038 if (!Inst->use_empty())
1039 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +00001040 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +00001041 Inst->eraseFromParent();
1042 Changed = true;
1043 ++NumCSECall;
1044 continue;
1045 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001046
Chris Lattner92bb0f92011-01-03 03:41:27 +00001047 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001048 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +00001049 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001050 continue;
1051 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001052
Philip Reamesdfd890d2015-08-27 01:32:33 +00001053 // A release fence requires that all stores complete before it, but does
1054 // not prevent the reordering of following loads 'before' the fence. As a
1055 // result, we don't need to consider it as writing to memory and don't need
1056 // to advance the generation. We do need to prevent DSE across the fence,
1057 // but that's handled above.
1058 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +00001059 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +00001060 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
1061 continue;
1062 }
1063
Philip Reamesae1f265b2015-12-16 01:01:30 +00001064 // write back DSE - If we write back the same value we just loaded from
1065 // the same location and haven't passed any intervening writes or ordering
1066 // operations, we can remove the write. The primary benefit is in allowing
1067 // the available load table to remain valid and value forward past where
1068 // the store originally was.
1069 if (MemInst.isValid() && MemInst.isStore()) {
1070 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +00001071 if (InVal.DefInst &&
1072 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +00001073 InVal.MatchingId == MemInst.getMatchingId() &&
1074 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +00001075 !MemInst.isVolatile() && MemInst.isUnordered() &&
Philip Reames0adbb192018-03-14 21:35:06 +00001076 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
1077 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1078 InVal.DefInst, Inst))) {
Geoff Berry8d846052016-08-31 19:24:10 +00001079 // It is okay to have a LastStore to a different pointer here if MemorySSA
1080 // tells us that the load and store are from the same memory generation.
1081 // In that case, LastStore should keep its present value since we're
1082 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +00001083 assert((!LastStore ||
1084 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +00001085 MemInst.getPointerOperand() ||
1086 MSSA) &&
1087 "can't have an intervening store if not using MemorySSA!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001088 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001089 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001090 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001091 continue;
1092 }
Geoff Berry8d846052016-08-31 19:24:10 +00001093 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +00001094 Inst->eraseFromParent();
1095 Changed = true;
1096 ++NumDSE;
1097 // We can avoid incrementing the generation count since we were able
1098 // to eliminate this store.
1099 continue;
1100 }
1101 }
1102
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001103 // Okay, this isn't something we can CSE at all. Check to see if it is
1104 // something that could modify memory. If so, our available memory values
1105 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +00001106 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001107 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +00001108
Chad Rosierf9327d62015-01-26 22:51:15 +00001109 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001110 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +00001111 // location with no intervening loads. Delete the earlier store.
1112 // At the moment, we don't remove ordered stores, but do remove
1113 // unordered atomic stores. There's no special requirement (for
1114 // unordered atomics) about removing atomic stores only in favor of
1115 // other atomic stores since we we're going to execute the non-atomic
1116 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +00001117 if (LastStore) {
1118 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +00001119 assert(LastStoreMemInst.isUnordered() &&
1120 !LastStoreMemInst.isVolatile() &&
1121 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +00001122 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001123 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1124 << " due to: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001125 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001126 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001127 } else {
1128 removeMSSA(LastStore);
1129 LastStore->eraseFromParent();
1130 Changed = true;
1131 ++NumDSE;
1132 LastStore = nullptr;
1133 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001134 }
Philip Reames018dbf12014-11-18 17:46:32 +00001135 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001136 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001137
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001138 // Okay, we just invalidated anything we knew about loaded values. Try
1139 // to salvage *something* by remembering that the stored value is a live
1140 // version of the pointer. It is safe to forward from volatile stores
1141 // to non-volatile loads, so we don't have to check for volatility of
1142 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001143 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001144 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001145 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001146 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001147
Philip Reames15145fb2015-12-17 18:50:50 +00001148 // Remember that this was the last unordered store we saw for DSE. We
1149 // don't yet handle DSE on ordered or volatile stores since we don't
1150 // have a good way to model the ordering requirement for following
1151 // passes once the store is removed. We could insert a fence, but
1152 // since fences are slightly stronger than stores in their ordering,
1153 // it's not clear this is a profitable transform. Another option would
1154 // be to merge the ordering with that of the post dominating store.
1155 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +00001156 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001157 else
1158 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +00001159 }
1160 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001161 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001162
Chris Lattner18ae5432011-01-02 23:04:14 +00001163 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +00001164}
Chris Lattner18ae5432011-01-02 23:04:14 +00001165
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001166bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +00001167 // Note, deque is being used here because there is significant performance
1168 // gains over vector when the container becomes very large due to the
1169 // specific access patterns. For more information see the mailing list
1170 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +00001171 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +00001172 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001173
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001174 bool Changed = false;
1175
1176 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +00001177 nodesToProcess.push_back(new StackNode(
Philip Reames0adbb192018-03-14 21:35:06 +00001178 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1179 CurrentGeneration, DT.getRootNode(),
1180 DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001181
1182 // Save the current generation.
1183 unsigned LiveOutGeneration = CurrentGeneration;
1184
1185 // Process the stack.
1186 while (!nodesToProcess.empty()) {
1187 // Grab the first item off the stack. Set the current generation, remove
1188 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +00001189 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001190
1191 // Initialize class members.
1192 CurrentGeneration = NodeToProcess->currentGeneration();
1193
1194 // Check if the node needs to be processed.
1195 if (!NodeToProcess->isProcessed()) {
1196 // Process the node.
1197 Changed |= processNode(NodeToProcess->node());
1198 NodeToProcess->childGeneration(CurrentGeneration);
1199 NodeToProcess->process();
1200 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1201 // Push the next child onto the stack.
1202 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +00001203 nodesToProcess.push_back(
Philip Reames0adbb192018-03-14 21:35:06 +00001204 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1205 AvailableCalls, NodeToProcess->childGeneration(),
1206 child, child->begin(), child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001207 } else {
1208 // It has been processed, and there are no more children to process,
1209 // so delete it and pop it off the stack.
1210 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +00001211 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001212 }
1213 } // while (!nodes...)
1214
1215 // Reset the current generation.
1216 CurrentGeneration = LiveOutGeneration;
1217
1218 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +00001219}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001220
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001221PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00001222 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00001223 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1224 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1225 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001226 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001227 auto *MSSA =
1228 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001229
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001230 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001231
1232 if (!CSE.run())
1233 return PreservedAnalyses::all();
1234
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001235 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001236 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001237 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001238 if (UseMemorySSA)
1239 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001240 return PA;
1241}
1242
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001243namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001245/// A simple and fast domtree-based CSE pass.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001246///
1247/// This pass does a simple depth-first walk over the dominator tree,
1248/// eliminating trivially redundant instructions and using instsimplify to
1249/// canonicalize things as it goes. It is intended to be fast and catch obvious
1250/// cases so that instcombine and other passes are more effective. It is
1251/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001252template<bool UseMemorySSA>
1253class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001254public:
1255 static char ID;
1256
Geoff Berry8d846052016-08-31 19:24:10 +00001257 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1258 if (UseMemorySSA)
1259 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1260 else
1261 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001262 }
1263
1264 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001265 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001266 return false;
1267
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001268 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001269 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001270 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001271 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001272 auto *MSSA =
1273 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001274
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001275 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001276
1277 return CSE.run();
1278 }
1279
1280 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001281 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001282 AU.addRequired<DominatorTreeWrapperPass>();
1283 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001284 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001285 if (UseMemorySSA) {
1286 AU.addRequired<MemorySSAWrapperPass>();
1287 AU.addPreserved<MemorySSAWrapperPass>();
1288 }
James Molloyefbba722015-09-10 10:22:12 +00001289 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001290 AU.setPreservesCFG();
1291 }
1292};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001293
1294} // end anonymous namespace
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001295
Geoff Berry8d846052016-08-31 19:24:10 +00001296using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001297
Geoff Berry8d846052016-08-31 19:24:10 +00001298template<>
1299char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001300
1301INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1302 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001303INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001304INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001305INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1306INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1307INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001308
1309using EarlyCSEMemSSALegacyPass =
1310 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1311
1312template<>
1313char EarlyCSEMemSSALegacyPass::ID = 0;
1314
1315FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1316 if (UseMemorySSA)
1317 return new EarlyCSEMemSSALegacyPass();
1318 else
1319 return new EarlyCSELegacyPass();
1320}
1321
1322INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1323 "Early CSE w/ MemorySSA", false, false)
1324INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001325INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001326INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1327INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1328INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1329INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1330 "Early CSE w/ MemorySSA", false, false)