LLVM 24.0.0git
EarlyCSE.cpp
Go to the documentation of this file.
1//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs a simple dominator tree walk that eliminates trivially
10// redundant instructions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "ScalarOptions.h"
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/PassManager.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
45#include "llvm/Pass.h"
49#include "llvm/Support/Debug.h"
56#include <cassert>
57#include <deque>
58#include <memory>
59#include <utility>
60
61using namespace llvm;
62using namespace llvm::PatternMatch;
63
64#define DEBUG_TYPE "early-cse"
65
66STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
67STATISTIC(NumCSE, "Number of instructions CSE'd");
68STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
69STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
70STATISTIC(NumCSECall, "Number of call instructions CSE'd");
71STATISTIC(NumCSEGEP, "Number of GEP instructions CSE'd");
72STATISTIC(NumDSE, "Number of trivial dead stores removed");
73
74DEBUG_COUNTER(CSECounter, "early-cse",
75 "Controls which instructions are removed");
76
77//===----------------------------------------------------------------------===//
78// SimpleValue
79//===----------------------------------------------------------------------===//
80
81namespace {
82
83/// Struct representing the available values in the scoped hash table.
84struct SimpleValue {
85 Instruction *Inst;
86
87 SimpleValue(Instruction *I) : Inst(I) {
88 assert(canHandle(I) && "Inst can't be handled!");
89 }
90
91 static bool canHandle(Instruction *Inst) {
92 // This can only handle non-void readnone functions.
93 // Also handled are constrained intrinsic that look like the types
94 // of instruction handled below (UnaryOperator, etc.).
95 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
96 if (Function *F = CI->getCalledFunction()) {
97 switch (F->getIntrinsicID()) {
98 case Intrinsic::experimental_constrained_fadd:
99 case Intrinsic::experimental_constrained_fsub:
100 case Intrinsic::experimental_constrained_fmul:
101 case Intrinsic::experimental_constrained_fdiv:
102 case Intrinsic::experimental_constrained_frem:
103 case Intrinsic::experimental_constrained_fptosi:
104 case Intrinsic::experimental_constrained_sitofp:
105 case Intrinsic::experimental_constrained_fptoui:
106 case Intrinsic::experimental_constrained_uitofp:
107 case Intrinsic::experimental_constrained_fcmp:
108 case Intrinsic::experimental_constrained_fcmps: {
109 auto *CFP = cast<ConstrainedFPIntrinsic>(CI);
110 if (CFP->getExceptionBehavior() &&
111 CFP->getExceptionBehavior() == fp::ebStrict)
112 return false;
113 // Since we CSE across function calls we must not allow
114 // the rounding mode to change.
115 if (CFP->getRoundingMode() &&
116 CFP->getRoundingMode() == RoundingMode::Dynamic)
117 return false;
118 return true;
119 }
120 }
121 }
122 return CI->doesNotAccessMemory() &&
123 // FIXME: Currently the calls which may access the thread id may
124 // be considered as not accessing the memory. But this is
125 // problematic for coroutines, since coroutines may resume in a
126 // different thread. So we disable the optimization here for the
127 // correctness. However, it may block many other correct
128 // optimizations. Revert this one when we detect the memory
129 // accessing kind more precisely.
130 !CI->getFunction()->isPresplitCoroutine();
131 }
132 return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
133 isa<BinaryOperator>(Inst) || isa<CmpInst>(Inst) ||
137 isa<FreezeInst>(Inst);
138 }
139};
140
141} // end anonymous namespace
142
143template <> struct llvm::DenseMapInfo<SimpleValue> {
144 static unsigned getHashValue(SimpleValue Val);
145 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
146};
147
148/// Match a 'select' including an optional 'not's of the condition.
150 Value *&B) {
151 // Return false if V is not even a select.
152 if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
153 return false;
154
155 // Look through a 'not' of the condition operand by swapping A/B.
156 Value *CondNot;
157 if (match(Cond, m_Not(m_Value(CondNot)))) {
158 Cond = CondNot;
159 std::swap(A, B);
160 }
161
162 return true;
163}
164
165static unsigned hashCallInst(CallInst *CI) {
166 // Don't CSE convergent calls in different basic blocks, because they
167 // implicitly depend on the set of threads that is currently executing.
168 if (CI->isConvergent()) {
169 return hash_combine(CI->getOpcode(), CI->getParent(),
171 }
172 return hash_combine(CI->getOpcode(),
174}
175
176static unsigned getHashValueImpl(SimpleValue Val) {
177 Instruction *Inst = Val.Inst;
178 // Hash in all of the operands as pointers.
179 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
180 Value *LHS = BinOp->getOperand(0);
181 Value *RHS = BinOp->getOperand(1);
182 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
183 std::swap(LHS, RHS);
184
185 return hash_combine(BinOp->getOpcode(), LHS, RHS);
186 }
187
188 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
189 // Compares can be commuted by swapping the comparands and
190 // updating the predicate. Choose the form that has the
191 // comparands in sorted order, or in the case of a tie, the
192 // one with the lower predicate.
193 Value *LHS = CI->getOperand(0);
194 Value *RHS = CI->getOperand(1);
195 CmpInst::Predicate Pred = CI->getPredicate();
196 CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
197 if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
198 std::swap(LHS, RHS);
199 Pred = SwappedPred;
200 }
201 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
202 }
203
204 // Hash general selects to allow matching commuted true/false operands.
205 Value *Cond, *A, *B;
206 if (matchSelectWithOptionalNotCond(Inst, Cond, A, B)) {
207 // Hash general selects to allow matching commuted true/false operands.
208
209 // If we do not have a compare as the condition, just hash in the condition.
210 CmpPredicate Pred;
211 Value *X, *Y;
212 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
213 return hash_combine(Inst->getOpcode(), Cond, A, B);
214
215 // Similar to cmp normalization (above) - canonicalize the predicate value:
216 // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
217 if (CmpInst::getInversePredicate(Pred) < Pred) {
218 Pred = CmpInst::getInversePredicate(Pred);
219 std::swap(A, B);
220 }
221 return hash_combine(Inst->getOpcode(),
222 static_cast<CmpInst::Predicate>(Pred), X, Y, A, B);
223 }
224
225 if (CastInst *CI = dyn_cast<CastInst>(Inst))
226 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
227
228 if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
229 return hash_combine(FI->getOpcode(), FI->getOperand(0));
230
231 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
232 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
233 hash_combine_range(EVI->indices()));
234
235 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
236 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
237 IVI->getOperand(1), hash_combine_range(IVI->indices()));
238
241 isa<UnaryOperator>(Inst) || isa<FreezeInst>(Inst)) &&
242 "Invalid/unknown instruction");
243
244 // Handle intrinsics with commutative operands.
245 auto *II = dyn_cast<IntrinsicInst>(Inst);
246 if (II && II->isCommutative() && II->arg_size() >= 2) {
247 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
248 if (LHS > RHS)
249 std::swap(LHS, RHS);
250 return hash_combine(
251 II->getOpcode(), LHS, RHS,
252 hash_combine_range(drop_begin(II->operand_values(), 2)));
253 }
254
255 // gc.relocate is 'special' call: its second and third operands are
256 // not real values, but indices into statepoint's argument list.
257 // Get values they point to.
258 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
259 return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
260 GCR->getBasePtr(), GCR->getDerivedPtr());
261
262 // Don't CSE convergent calls in different basic blocks, because they
263 // implicitly depend on the set of threads that is currently executing.
264 if (CallInst *CI = dyn_cast<CallInst>(Inst))
265 return hashCallInst(CI);
266
267 // Mix in the opcode.
268 return hash_combine(Inst->getOpcode(),
270}
271
272unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
273#ifndef NDEBUG
274 // If -earlycse-debug-hash was specified, return a constant -- this
275 // will force all hashing to collide, so we'll exhaustively search
276 // the table for a match, and the assertion in isEqual will fire if
277 // there's a bug causing equal keys to hash differently.
278 if (getScalarOptions(*Val.Inst->getFunction()).earlycse_debug_hash)
279 return 0;
280#endif
281 return getHashValueImpl(Val);
282}
283
284static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
285 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
286
287 if (LHSI->getOpcode() != RHSI->getOpcode())
288 return false;
289 if (LHSI->isIdenticalToWhenDefined(RHSI, /*IntersectAttrs=*/true)) {
290 // Convergent calls implicitly depend on the set of threads that is
291 // currently executing, so conservatively return false if they are in
292 // different basic blocks.
293 if (CallInst *CI = dyn_cast<CallInst>(LHSI);
294 CI && CI->isConvergent() && LHSI->getParent() != RHSI->getParent())
295 return false;
296
297 return true;
298 }
299
300 // If we're not strictly identical, we still might be a commutable instruction
301 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
302 if (!LHSBinOp->isCommutative())
303 return false;
304
306 "same opcode, but different instruction type?");
307 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
308
309 // Commuted equality
310 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
311 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
312 }
313 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
314 assert(isa<CmpInst>(RHSI) &&
315 "same opcode, but different instruction type?");
316 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
317 // Commuted equality
318 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
319 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
320 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
321 }
322
323 auto *LII = dyn_cast<IntrinsicInst>(LHSI);
324 auto *RII = dyn_cast<IntrinsicInst>(RHSI);
325 if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
326 LII->isCommutative() && LII->arg_size() >= 2) {
327 return LII->getArgOperand(0) == RII->getArgOperand(1) &&
328 LII->getArgOperand(1) == RII->getArgOperand(0) &&
329 std::equal(LII->arg_begin() + 2, LII->arg_end(),
330 RII->arg_begin() + 2, RII->arg_end()) &&
331 LII->hasSameSpecialState(RII, /*IgnoreAlignment=*/false,
332 /*IntersectAttrs=*/true);
333 }
334
335 // See comment above in `getHashValue()`.
336 if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
337 if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
338 return GCR1->getOperand(0) == GCR2->getOperand(0) &&
339 GCR1->getBasePtr() == GCR2->getBasePtr() &&
340 GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
341
342 // Selects can be non-trivially equivalent via inverted conditions and swaps.
343 Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
344 if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB) &&
345 matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB)) {
346 // select Cond, A, B <--> select not(Cond), B, A
347 if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
348 return true;
349
350 // If the true/false operands are swapped and the conditions are compares
351 // with inverted predicates, the selects are equal:
352 // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
353 //
354 // This also handles patterns with a double-negation in the sense of not +
355 // inverse, because we looked through a 'not' in the matching function and
356 // swapped A/B:
357 // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
358 if (LHSA == RHSB && LHSB == RHSA) {
359 CmpPredicate PredL, PredR;
360 Value *X, *Y;
361 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
362 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
363 CmpInst::getInversePredicate(PredL) == PredR)
364 return true;
365 }
366 }
367
368 return false;
369}
370
371bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
372 // These comparisons are nontrivial, so assert that equality implies
373 // hash equality (DenseMap demands this as an invariant).
374 bool Result = isEqualImpl(LHS, RHS);
376 return Result;
377}
378
379//===----------------------------------------------------------------------===//
380// CallValue
381//===----------------------------------------------------------------------===//
382
383namespace {
384
385/// Struct representing the available call values in the scoped hash
386/// table.
387struct CallValue {
388 Instruction *Inst;
389
390 CallValue(Instruction *I) : Inst(I) {
391 assert(canHandle(I) && "Inst can't be handled!");
392 }
393
394 static bool canHandle(Instruction *Inst) {
395 CallInst *CI = dyn_cast<CallInst>(Inst);
396 if (!CI || (!CI->onlyReadsMemory() && !CI->onlyWritesMemory()) ||
397 // FIXME: Currently the calls which may access the thread id may
398 // be considered as not accessing the memory. But this is
399 // problematic for coroutines, since coroutines may resume in a
400 // different thread. So we disable the optimization here for the
401 // correctness. However, it may block many other correct
402 // optimizations. Revert this one when we detect the memory
403 // accessing kind more precisely.
405 return false;
406 return true;
407 }
408};
409
410} // end anonymous namespace
411
412template <> struct llvm::DenseMapInfo<CallValue> {
413 static unsigned getHashValue(CallValue Val);
414 static bool isEqual(CallValue LHS, CallValue RHS);
415};
416
417unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
418 Instruction *Inst = Val.Inst;
419
420 // Hash all of the operands as pointers and mix in the opcode.
421 return hashCallInst(cast<CallInst>(Inst));
422}
423
424bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
425 CallInst *LHSI = cast<CallInst>(LHS.Inst);
426 CallInst *RHSI = cast<CallInst>(RHS.Inst);
427
428 // Convergent calls implicitly depend on the set of threads that is
429 // currently executing, so conservatively return false if they are in
430 // different basic blocks.
431 if (LHSI->isConvergent() && LHSI->getParent() != RHSI->getParent())
432 return false;
433
434 return LHSI->isIdenticalToWhenDefined(RHSI, /*IntersectAttrs=*/true);
435}
436
437//===----------------------------------------------------------------------===//
438// GEPValue
439//===----------------------------------------------------------------------===//
440
441namespace {
442
443struct GEPValue {
444 Instruction *Inst;
445 std::optional<int64_t> ConstantOffset;
446
447 GEPValue(Instruction *I) : Inst(I) {
448 assert(canHandle(I) && "Inst can't be handled!");
449 }
450
451 GEPValue(Instruction *I, std::optional<int64_t> ConstantOffset)
452 : Inst(I), ConstantOffset(ConstantOffset) {
453 assert(canHandle(I) && "Inst can't be handled!");
454 }
455
456 static bool canHandle(Instruction *Inst) {
457 return isa<GetElementPtrInst>(Inst);
458 }
459};
460
461} // namespace
462
463template <> struct llvm::DenseMapInfo<GEPValue> {
464 static unsigned getHashValue(const GEPValue &Val);
465 static bool isEqual(const GEPValue &LHS, const GEPValue &RHS);
466};
467
468unsigned DenseMapInfo<GEPValue>::getHashValue(const GEPValue &Val) {
469 auto *GEP = cast<GetElementPtrInst>(Val.Inst);
470 if (Val.ConstantOffset.has_value())
471 return hash_combine(GEP->getOpcode(), GEP->getPointerOperand(),
472 Val.ConstantOffset.value());
473 return hash_combine(GEP->getOpcode(),
474 hash_combine_range(GEP->operand_values()));
475}
476
477bool DenseMapInfo<GEPValue>::isEqual(const GEPValue &LHS, const GEPValue &RHS) {
478 auto *LGEP = cast<GetElementPtrInst>(LHS.Inst);
479 auto *RGEP = cast<GetElementPtrInst>(RHS.Inst);
480 if (LGEP->getPointerOperand() != RGEP->getPointerOperand())
481 return false;
482 if (LHS.ConstantOffset.has_value() && RHS.ConstantOffset.has_value())
483 return LHS.ConstantOffset.value() == RHS.ConstantOffset.value();
484 return LGEP->isIdenticalToWhenDefined(RGEP);
485}
486
487//===----------------------------------------------------------------------===//
488// EarlyCSE implementation
489//===----------------------------------------------------------------------===//
490
491namespace {
492
493/// A simple and fast domtree-based CSE pass.
494///
495/// This pass does a simple depth-first walk over the dominator tree,
496/// eliminating trivially redundant instructions and using instsimplify to
497/// canonicalize things as it goes. It is intended to be fast and catch obvious
498/// cases so that instcombine and other passes are more effective. It is
499/// expected that a later pass of GVN will catch the interesting/hard cases.
500class EarlyCSE {
501public:
502 const ScalarOptions &Opts;
503 const TargetLibraryInfo &TLI;
504 const TargetTransformInfo &TTI;
505 DominatorTree &DT;
506 AssumptionCache &AC;
507 const SimplifyQuery SQ;
508 MemorySSA *MSSA;
509 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
510
511 using AllocatorTy =
512 RecyclingAllocator<BumpPtrAllocator,
513 ScopedHashTableVal<SimpleValue, Value *>>;
514 using ScopedHTType =
515 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
516 AllocatorTy>;
517
518 /// A scoped hash table of the current values of all of our simple
519 /// scalar expressions.
520 ///
521 /// As we walk down the domtree, we look to see if instructions are in this:
522 /// if so, we replace them with what we find, otherwise we insert them so
523 /// that dominated values can succeed in their lookup.
524 ScopedHTType AvailableValues;
525
526 /// A scoped hash table of the current values of previously encountered
527 /// memory locations.
528 ///
529 /// This allows us to get efficient access to dominating loads or stores when
530 /// we have a fully redundant load. In addition to the most recent load, we
531 /// keep track of a generation count of the read, which is compared against
532 /// the current generation count. The current generation count is incremented
533 /// after every possibly writing memory operation, which ensures that we only
534 /// CSE loads with other loads that have no intervening store. Ordering
535 /// events (such as fences or atomic instructions) increment the generation
536 /// count as well; essentially, we model these as writes to all possible
537 /// locations. Note that atomic and/or volatile loads and stores can be
538 /// present the table; it is the responsibility of the consumer to inspect
539 /// the atomicity/volatility if needed.
540 struct LoadValue {
541 Instruction *DefInst = nullptr;
542 unsigned Generation = 0;
543 int MatchingId = -1;
544 bool IsAtomic = false;
545 bool IsLoad = false;
546
547 LoadValue() = default;
548 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
549 bool IsAtomic, bool IsLoad)
550 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
551 IsAtomic(IsAtomic), IsLoad(IsLoad) {}
552 };
553
554 using LoadMapAllocator =
555 RecyclingAllocator<BumpPtrAllocator,
556 ScopedHashTableVal<Value *, LoadValue>>;
557 using LoadHTType =
558 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
559 LoadMapAllocator>;
560
561 LoadHTType AvailableLoads;
562
563 // A scoped hash table mapping memory locations (represented as typed
564 // addresses) to generation numbers at which that memory location became
565 // (henceforth indefinitely) invariant.
566 using InvariantMapAllocator =
567 RecyclingAllocator<BumpPtrAllocator,
568 ScopedHashTableVal<MemoryLocation, unsigned>>;
569 using InvariantHTType =
570 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
571 InvariantMapAllocator>;
572 InvariantHTType AvailableInvariants;
573
574 /// A scoped hash table of the current values of read-only call
575 /// values.
576 ///
577 /// It uses the same generation count as loads.
578 using CallHTType =
579 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
580 CallHTType AvailableCalls;
581
582 using GEPMapAllocatorTy =
583 RecyclingAllocator<BumpPtrAllocator,
584 ScopedHashTableVal<GEPValue, Value *>>;
585 using GEPHTType = ScopedHashTable<GEPValue, Value *, DenseMapInfo<GEPValue>,
586 GEPMapAllocatorTy>;
587 GEPHTType AvailableGEPs;
588
589 /// This is the current generation of the memory value.
590 unsigned CurrentGeneration = 0;
591
592 /// Set up the EarlyCSE runner for a particular function.
593 EarlyCSE(const ScalarOptions &Opts, const DataLayout &DL,
594 const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
595 DominatorTree &DT, AssumptionCache &AC, MemorySSA *MSSA)
596 : Opts(Opts), TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC),
597 MSSA(MSSA), MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
598
599 bool run();
600
601private:
602 unsigned ClobberCounter = 0;
603 // Almost a POD, but needs to call the constructors for the scoped hash
604 // tables so that a new scope gets pushed on. These are RAII so that the
605 // scope gets popped when the NodeScope is destroyed.
606 class NodeScope {
607 public:
608 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
609 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
610 GEPHTType &AvailableGEPs)
611 : Scope(AvailableValues), LoadScope(AvailableLoads),
612 InvariantScope(AvailableInvariants), CallScope(AvailableCalls),
613 GEPScope(AvailableGEPs) {}
614 NodeScope(const NodeScope &) = delete;
615 NodeScope &operator=(const NodeScope &) = delete;
616
617 private:
619 LoadHTType::ScopeTy LoadScope;
620 InvariantHTType::ScopeTy InvariantScope;
621 CallHTType::ScopeTy CallScope;
622 GEPHTType::ScopeTy GEPScope;
623 };
624
625 // Contains all the needed information to create a stack for doing a depth
626 // first traversal of the tree. This includes scopes for values, loads, and
627 // calls as well as the generation. There is a child iterator so that the
628 // children do not need to be store separately.
629 class StackNode {
630 public:
631 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
632 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
633 GEPHTType &AvailableGEPs, unsigned cg, DomTreeNode *n,
634 DomTreeNode::const_iterator child,
635 DomTreeNode::const_iterator end)
636 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
637 EndIter(end),
638 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
639 AvailableCalls, AvailableGEPs) {}
640 StackNode(const StackNode &) = delete;
641 StackNode &operator=(const StackNode &) = delete;
642
643 // Accessors.
644 unsigned currentGeneration() const { return CurrentGeneration; }
645 unsigned childGeneration() const { return ChildGeneration; }
646 void childGeneration(unsigned generation) { ChildGeneration = generation; }
647 DomTreeNode *node() { return Node; }
648 DomTreeNode::const_iterator childIter() const { return ChildIter; }
649
650 DomTreeNode *nextChild() {
651 DomTreeNode *child = *ChildIter;
652 ++ChildIter;
653 return child;
654 }
655
656 DomTreeNode::const_iterator end() const { return EndIter; }
657 bool isProcessed() const { return Processed; }
658 void process() { Processed = true; }
659
660 private:
661 unsigned CurrentGeneration;
662 unsigned ChildGeneration;
663 DomTreeNode *Node;
664 DomTreeNode::const_iterator ChildIter;
665 DomTreeNode::const_iterator EndIter;
666 NodeScope Scopes;
667 bool Processed = false;
668 };
669
670 /// Wrapper class to handle memory instructions, including loads,
671 /// stores and intrinsic loads and stores defined by the target.
672 class ParseMemoryInst {
673 public:
674 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
675 : Inst(Inst) {
676 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
677 IntrID = II->getIntrinsicID();
678 if (TTI.getTgtMemIntrinsic(II, Info))
679 return;
680 if (isHandledNonTargetIntrinsic(IntrID)) {
681 switch (IntrID) {
682 case Intrinsic::masked_load:
683 Info.PtrVal = Inst->getOperand(0);
684 Info.MatchingId = Intrinsic::masked_load;
685 Info.ReadMem = true;
686 Info.WriteMem = false;
687 Info.IsVolatile = false;
688 break;
689 case Intrinsic::masked_store:
690 Info.PtrVal = Inst->getOperand(1);
691 // Use the ID of masked load as the "matching id". This will
692 // prevent matching non-masked loads/stores with masked ones
693 // (which could be done), but at the moment, the code here
694 // does not support matching intrinsics with non-intrinsics,
695 // so keep the MatchingIds specific to masked instructions
696 // for now (TODO).
697 Info.MatchingId = Intrinsic::masked_load;
698 Info.ReadMem = false;
699 Info.WriteMem = true;
700 Info.IsVolatile = false;
701 break;
702 }
703 } else if (auto *MI = dyn_cast<MemSetInst>(Inst)) {
704 Info.PtrVal = MI->getDest();
705 Info.MatchingId = 0;
706 Info.ReadMem = false;
707 Info.WriteMem = true;
708 Info.IsVolatile = MI->isVolatile();
709 }
710 }
711 }
712
713 Instruction *get() { return Inst; }
714 const Instruction *get() const { return Inst; }
715
716 bool isLoad() const {
717 if (IntrID != 0)
718 return Info.ReadMem;
719 return isa<LoadInst>(Inst);
720 }
721
722 bool isStore() const {
723 if (IntrID != 0)
724 return Info.WriteMem;
725 return isa<StoreInst>(Inst);
726 }
727
728 bool isAtomic() const {
729 if (IntrID != 0)
730 return Info.Ordering != AtomicOrdering::NotAtomic;
731 return Inst->isAtomic();
732 }
733
734 bool isUnordered() const {
735 if (IntrID != 0)
736 return Info.isUnordered();
737
738 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
739 return LI->isUnordered();
740 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
741 return SI->isUnordered();
742 }
743 // Conservative answer
744 return !Inst->isAtomic();
745 }
746
747 bool isVolatile() const {
748 if (IntrID != 0)
749 return Info.IsVolatile;
750
751 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
752 return LI->isVolatile();
753 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
754 return SI->isVolatile();
755 }
756 // Conservative answer
757 return true;
758 }
759
760 bool isInvariantLoad() const {
761 if (auto *LI = dyn_cast<LoadInst>(Inst))
762 return LI->hasMetadata(LLVMContext::MD_invariant_load);
763 return false;
764 }
765
766 bool isValid() const { return getPointerOperand() != nullptr; }
767
768 // For regular (non-intrinsic) loads/stores, this is set to -1. For
769 // intrinsic loads/stores, the id is retrieved from the corresponding
770 // field in the MemIntrinsicInfo structure. That field contains
771 // non-negative values only.
772 int getMatchingId() const {
773 if (IntrID != 0)
774 return Info.MatchingId;
775 return -1;
776 }
777
778 Value *getPointerOperand() const {
779 if (IntrID != 0)
780 return Info.PtrVal;
781 return getLoadStorePointerOperand(Inst);
782 }
783
784 Type *getValueType() const {
785 // TODO: handle target-specific intrinsics.
786 return Inst->getAccessType();
787 }
788
789 bool mayReadFromMemory() const {
790 if (IntrID != 0)
791 return Info.ReadMem;
792 return Inst->mayReadFromMemory();
793 }
794
795 bool mayWriteToMemory() const {
796 if (IntrID != 0)
797 return Info.WriteMem;
798 return Inst->mayWriteToMemory();
799 }
800
801 private:
802 Intrinsic::ID IntrID = 0;
803 MemIntrinsicInfo Info;
804 Instruction *Inst;
805 };
806
807 // This function is to prevent accidentally passing a non-target
808 // intrinsic ID to TargetTransformInfo.
809 static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
810 switch (ID) {
811 case Intrinsic::masked_load:
812 case Intrinsic::masked_store:
813 return true;
814 }
815 return false;
816 }
817 static bool isHandledNonTargetIntrinsic(const Value *V) {
818 if (auto *II = dyn_cast<IntrinsicInst>(V))
819 return isHandledNonTargetIntrinsic(II->getIntrinsicID());
820 return false;
821 }
822
823 bool processNode(DomTreeNode *Node);
824
825 bool handleBranchCondition(Instruction *CondInst, const CondBrInst *BI,
826 const BasicBlock *BB, const BasicBlock *Pred);
827
828 Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
829 unsigned CurrentGeneration);
830
831 bool overridingStores(const ParseMemoryInst &Earlier,
832 const ParseMemoryInst &Later);
833
834 Value *getOrCreateResult(Instruction *Inst, Type *ExpectedType,
835 bool CanCreate) const {
836 // TODO: We could insert relevant casts on type mismatch.
837 // The load or the store's first operand.
838 Value *V;
839 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
840 switch (II->getIntrinsicID()) {
841 case Intrinsic::masked_load:
842 V = II;
843 break;
844 case Intrinsic::masked_store:
845 V = II->getOperand(0);
846 break;
847 default:
848 return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType,
849 CanCreate);
850 }
851 } else {
852 V = isa<LoadInst>(Inst) ? Inst : cast<StoreInst>(Inst)->getValueOperand();
853 }
854
855 return V->getType() == ExpectedType ? V : nullptr;
856 }
857
858 /// Return true if the instruction is known to only operate on memory
859 /// provably invariant in the given "generation".
860 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
861
862 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
863 Instruction *EarlierInst, Instruction *LaterInst);
864
865 bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
866 const IntrinsicInst *Later) {
867 auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
868 // Is Mask0 a submask of Mask1?
869 if (Mask0 == Mask1)
870 return true;
871 if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
872 return false;
873 auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
874 auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
875 if (!Vec0 || !Vec1)
876 return false;
877 if (Vec0->getType() != Vec1->getType())
878 return false;
879 for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
880 Constant *Elem0 = Vec0->getOperand(i);
881 Constant *Elem1 = Vec1->getOperand(i);
882 auto *Int0 = dyn_cast<ConstantInt>(Elem0);
883 if (Int0 && Int0->isZero())
884 continue;
885 auto *Int1 = dyn_cast<ConstantInt>(Elem1);
886 if (Int1 && !Int1->isZero())
887 continue;
888 if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
889 return false;
890 if (Elem0 == Elem1)
891 continue;
892 return false;
893 }
894 return true;
895 };
896 auto PtrOp = [](const IntrinsicInst *II) {
897 if (II->getIntrinsicID() == Intrinsic::masked_load)
898 return II->getOperand(0);
899 if (II->getIntrinsicID() == Intrinsic::masked_store)
900 return II->getOperand(1);
901 llvm_unreachable("Unexpected IntrinsicInst");
902 };
903 auto MaskOp = [](const IntrinsicInst *II) {
904 if (II->getIntrinsicID() == Intrinsic::masked_load)
905 return II->getOperand(1);
906 if (II->getIntrinsicID() == Intrinsic::masked_store)
907 return II->getOperand(2);
908 llvm_unreachable("Unexpected IntrinsicInst");
909 };
910 auto ThruOp = [](const IntrinsicInst *II) {
911 if (II->getIntrinsicID() == Intrinsic::masked_load)
912 return II->getOperand(2);
913 llvm_unreachable("Unexpected IntrinsicInst");
914 };
915
916 if (PtrOp(Earlier) != PtrOp(Later))
917 return false;
918
919 Intrinsic::ID IDE = Earlier->getIntrinsicID();
920 Intrinsic::ID IDL = Later->getIntrinsicID();
921 // We could really use specific intrinsic classes for masked loads
922 // and stores in IntrinsicInst.h.
923 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
924 // Trying to replace later masked load with the earlier one.
925 // Check that the pointers are the same, and
926 // - masks and pass-throughs are the same, or
927 // - replacee's pass-through is "undef" and replacer's mask is a
928 // super-set of the replacee's mask.
929 if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
930 return true;
931 if (!isa<UndefValue>(ThruOp(Later)))
932 return false;
933 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
934 }
935 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
936 // Trying to replace a load of a stored value with the store's value.
937 // Check that the pointers are the same, and
938 // - load's mask is a subset of store's mask, and
939 // - load's pass-through is "undef".
940 if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
941 return false;
942 return isa<UndefValue>(ThruOp(Later));
943 }
944 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
945 // Trying to remove a store of the loaded value.
946 // Check that the pointers are the same, and
947 // - store's mask is a subset of the load's mask.
948 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
949 }
950 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
951 // Trying to remove a dead store (earlier).
952 // Check that the pointers are the same,
953 // - the to-be-removed store's mask is a subset of the other store's
954 // mask.
955 return IsSubmask(MaskOp(Earlier), MaskOp(Later));
956 }
957 return false;
958 }
959
960 void removeMSSA(Instruction &Inst) {
961 if (!MSSA)
962 return;
963 if (VerifyMemorySSA)
964 MSSA->verifyMemorySSA();
965 // Removing a store here can leave MemorySSA in an unoptimized state by
966 // creating MemoryPhis that have identical arguments and by creating
967 // MemoryUses whose defining access is not an actual clobber. The phi case
968 // is handled by MemorySSA when passing OptimizePhis = true to
969 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
970 // by MemorySSA's getClobberingMemoryAccess.
971 MSSAUpdater->removeMemoryAccess(&Inst, true);
972 }
973};
974
975} // end anonymous namespace
976
977/// Determine if the memory referenced by LaterInst is from the same heap
978/// version as EarlierInst.
979/// This is currently called in two scenarios:
980///
981/// load p
982/// ...
983/// load p
984///
985/// and
986///
987/// x = load p
988/// ...
989/// store x, p
990///
991/// in both cases we want to verify that there are no possible writes to the
992/// memory referenced by p between the earlier and later instruction.
993bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
994 unsigned LaterGeneration,
995 Instruction *EarlierInst,
996 Instruction *LaterInst) {
997 // Check the simple memory generation tracking first.
998 if (EarlierGeneration == LaterGeneration)
999 return true;
1000
1001 if (!MSSA)
1002 return false;
1003
1004 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
1005 // read/write memory, then we can safely return true here.
1006 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
1007 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
1008 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
1009 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
1010 // with the default optimization pipeline.
1011 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
1012 if (!EarlierMA)
1013 return true;
1014 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
1015 if (!LaterMA)
1016 return true;
1017
1018 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
1019 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
1020 // EarlierInst and LaterInst and neither can any other write that potentially
1021 // clobbers LaterInst.
1022 MemoryAccess *LaterDef;
1023 if (ClobberCounter < Opts.earlycse_mssa_optimization_cap) {
1024 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
1025 ClobberCounter++;
1026 } else
1027 LaterDef = LaterMA->getDefiningAccess();
1028
1029 return MSSA->dominates(LaterDef, EarlierMA);
1030}
1031
1032bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
1033 // A location loaded from with an invariant_load is assumed to *never* change
1034 // within the visible scope of the compilation.
1035 if (auto *LI = dyn_cast<LoadInst>(I))
1036 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1037 return true;
1038
1039 auto MemLocOpt = MemoryLocation::getOrNone(I);
1040 if (!MemLocOpt)
1041 // "target" intrinsic forms of loads aren't currently known to
1042 // MemoryLocation::get. TODO
1043 return false;
1044 MemoryLocation MemLoc = *MemLocOpt;
1045 if (!AvailableInvariants.count(MemLoc))
1046 return false;
1047
1048 // Is the generation at which this became invariant older than the
1049 // current one?
1050 return AvailableInvariants.lookup(MemLoc) <= GenAt;
1051}
1052
1053bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
1054 const CondBrInst *BI, const BasicBlock *BB,
1055 const BasicBlock *Pred) {
1056 assert(BI->getCondition() == CondInst && "Wrong condition?");
1057 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
1058 auto *TorF = (BI->getSuccessor(0) == BB)
1060 : ConstantInt::getFalse(BB->getContext());
1061 auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
1062 Value *&RHS) {
1063 if (Opcode == Instruction::And &&
1065 return true;
1066 else if (Opcode == Instruction::Or &&
1068 return true;
1069 return false;
1070 };
1071 // If the condition is AND operation, we can propagate its operands into the
1072 // true branch. If it is OR operation, we can propagate them into the false
1073 // branch.
1074 unsigned PropagateOpcode =
1075 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
1076
1077 bool MadeChanges = false;
1078 SmallVector<Instruction *, 4> WorkList;
1079 SmallPtrSet<Instruction *, 4> Visited;
1080 WorkList.push_back(CondInst);
1081 while (!WorkList.empty()) {
1082 Instruction *Curr = WorkList.pop_back_val();
1083
1084 AvailableValues.insert(Curr, TorF);
1085 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
1086 << Curr->getName() << "' as " << *TorF << " in "
1087 << BB->getName() << "\n");
1088 if (!DebugCounter::shouldExecute(CSECounter)) {
1089 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1090 } else {
1091 // Replace all dominated uses with the known value.
1092 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
1093 BasicBlockEdge(Pred, BB))) {
1094 NumCSECVP += Count;
1095 MadeChanges = true;
1096 }
1097 }
1098
1099 Value *LHS, *RHS;
1100 if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
1101 for (auto *Op : { LHS, RHS })
1102 if (Instruction *OPI = dyn_cast<Instruction>(Op))
1103 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
1104 WorkList.push_back(OPI);
1105 }
1106
1107 return MadeChanges;
1108}
1109
1110Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
1111 unsigned CurrentGeneration) {
1112 if (InVal.DefInst == nullptr)
1113 return nullptr;
1114 if (auto *MSI = dyn_cast<MemSetInst>(InVal.DefInst)) {
1115 if (!MemInst.isLoad() || MemInst.isVolatile() || !MemInst.isUnordered() ||
1116 MemInst.getMatchingId() != -1)
1117 return nullptr;
1118 if (MSI->isVolatile())
1119 return nullptr;
1120 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
1121 if (!Val || !Val->isZero())
1122 return nullptr;
1123 auto Len = MSI->getLengthInBytes();
1124 if (!Len)
1125 return nullptr;
1126 Type *InstType = MemInst.getValueType();
1127 if (!InstType)
1128 return nullptr;
1129 TypeSize LoadSize = SQ.DL.getTypeStoreSize(InstType);
1130 if (LoadSize.isScalable() || Len->ult(LoadSize.getFixedValue()))
1131 return nullptr;
1132 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1133 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1134 MemInst.get()))
1135 return nullptr;
1136 return Constant::getNullValue(MemInst.getValueType());
1137 }
1138 if (InVal.MatchingId != MemInst.getMatchingId())
1139 return nullptr;
1140 // We don't yet handle removing loads with ordering of any kind.
1141 if (MemInst.isVolatile() || !MemInst.isUnordered())
1142 return nullptr;
1143 // We can't replace an atomic load with one which isn't also atomic.
1144 if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
1145 return nullptr;
1146 // The value V returned from this function is used differently depending
1147 // on whether MemInst is a load or a store. If it's a load, we will replace
1148 // MemInst with V, if it's a store, we will check if V is the same as the
1149 // available value.
1150 bool MemInstMatching = !MemInst.isLoad();
1151 Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
1152 Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
1153
1154 // For stores check the result values before checking memory generation
1155 // (otherwise isSameMemGeneration may crash).
1156 Value *Result =
1157 MemInst.isStore()
1158 ? getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/false)
1159 : nullptr;
1160 if (MemInst.isStore() && InVal.DefInst != Result)
1161 return nullptr;
1162
1163 // Deal with non-target memory intrinsics.
1164 bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
1165 bool OtherNTI = isHandledNonTargetIntrinsic(Other);
1166 if (OtherNTI != MatchingNTI)
1167 return nullptr;
1168 if (OtherNTI && MatchingNTI) {
1169 if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
1170 cast<IntrinsicInst>(MemInst.get())))
1171 return nullptr;
1172 }
1173
1174 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1175 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1176 MemInst.get()))
1177 return nullptr;
1178
1179 if (!Result)
1180 Result = getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/true);
1181 return Result;
1182}
1183
1184static void combineIRFlags(Instruction &From, Value *To) {
1185 if (auto *I = dyn_cast<Instruction>(To)) {
1186 // If I being poison triggers UB, there is no need to drop those
1187 // flags. Otherwise, only retain flags present on both I and Inst.
1188 // TODO: Currently some fast-math flags are not treated as
1189 // poison-generating even though they should. Until this is fixed,
1190 // always retain flags present on both I and Inst for floating point
1191 // instructions.
1192 if (isa<FPMathOperator>(I) ||
1193 (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
1194 I->andIRFlags(&From);
1195 }
1196 if (isa<CallBase>(&From) && isa<CallBase>(To)) {
1197 // NB: Intersection of attrs between InVal.first and Inst is overly
1198 // conservative. Since we only CSE readonly functions that have the same
1199 // memory state, we can preserve (or possibly in some cases combine)
1200 // more attributes. Likewise this implies when checking equality of
1201 // callsite for CSEing, we can probably ignore more attributes.
1202 // Generally poison generating attributes need to be handled with more
1203 // care as they can create *new* UB if preserved/combined and violated.
1204 // Attributes that imply immediate UB on the other hand would have been
1205 // violated either way.
1206 bool Success =
1207 cast<CallBase>(To)->tryIntersectAttributes(cast<CallBase>(&From));
1208 assert(Success && "Failed to intersect attributes in callsites that "
1209 "passed identical check");
1210 // For NDEBUG Compile.
1211 (void)Success;
1212 }
1213}
1214
1215bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
1216 const ParseMemoryInst &Later) {
1217 // Can we remove Earlier store because of Later store?
1218
1219 assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
1220 "Violated invariant");
1221 if (Earlier.getPointerOperand() != Later.getPointerOperand())
1222 return false;
1223 if (!Earlier.getValueType() || !Later.getValueType() ||
1224 Earlier.getValueType() != Later.getValueType())
1225 return false;
1226 if (Earlier.getMatchingId() != Later.getMatchingId())
1227 return false;
1228 // At the moment, we don't remove ordered stores, but do remove
1229 // unordered atomic stores. There's no special requirement (for
1230 // unordered atomics) about removing atomic stores only in favor of
1231 // other atomic stores since we were going to execute the non-atomic
1232 // one anyway and the atomic one might never have become visible.
1233 if (!Earlier.isUnordered() || !Later.isUnordered())
1234 return false;
1235
1236 // Deal with non-target memory intrinsics.
1237 bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
1238 bool LNTI = isHandledNonTargetIntrinsic(Later.get());
1239 if (ENTI && LNTI)
1240 return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
1241 cast<IntrinsicInst>(Later.get()));
1242
1243 // Because of the check above, at least one of them is false.
1244 // For now disallow matching intrinsics with non-intrinsics,
1245 // so assume that the stores match if neither is an intrinsic.
1246 return ENTI == LNTI;
1247}
1248
1249bool EarlyCSE::processNode(DomTreeNode *Node) {
1250 bool Changed = false;
1251 BasicBlock *BB = Node->getBlock();
1252
1253 // If this block has a single predecessor, then the predecessor is the parent
1254 // of the domtree node and all of the live out memory values are still current
1255 // in this block. If this block has multiple predecessors, then they could
1256 // have invalidated the live-out memory values of our parent value. For now,
1257 // just be conservative and invalidate memory if this block has multiple
1258 // predecessors.
1259 if (!BB->getSinglePredecessor())
1260 ++CurrentGeneration;
1261
1262 // If this node has a single predecessor which ends in a conditional branch,
1263 // we can infer the value of the branch condition given that we took this
1264 // path. We need the single predecessor to ensure there's not another path
1265 // which reaches this block where the condition might hold a different
1266 // value. Since we're adding this to the scoped hash table (like any other
1267 // def), it will have been popped if we encounter a future merge block.
1268 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1269 if (auto *BI = dyn_cast<CondBrInst>(Pred->getTerminator())) {
1270 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
1271 if (CondInst && SimpleValue::canHandle(CondInst))
1272 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
1273 }
1274 }
1275
1276 /// LastStore - Keep track of the last non-volatile store that we saw... for
1277 /// as long as there in no instruction that reads memory. If we see a store
1278 /// to the same location, we delete the dead store. This zaps trivial dead
1279 /// stores which can occur in bitfield code among other things.
1280 Instruction *LastStore = nullptr;
1281
1282 // See if any instructions in the block can be eliminated. If so, do it. If
1283 // not, add them to AvailableValues.
1284 for (Instruction &Inst : make_early_inc_range(*BB)) {
1285 // Dead instructions should just be removed.
1286 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1287 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
1288 if (!DebugCounter::shouldExecute(CSECounter)) {
1289 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1290 continue;
1291 }
1292
1293 salvageKnowledge(&Inst, &AC);
1294 salvageDebugInfo(Inst);
1295 removeMSSA(Inst);
1296 Inst.eraseFromParent();
1297 Changed = true;
1298 ++NumSimplify;
1299 continue;
1300 }
1301
1302 // Skip assume intrinsics, they don't really have side effects (although
1303 // they're marked as such to ensure preservation of control dependencies),
1304 // and this pass will not bother with its removal. However, we should mark
1305 // its condition as true for all dominated blocks.
1306 if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
1307 auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
1308 if (CondI && SimpleValue::canHandle(CondI)) {
1309 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
1310 << '\n');
1311 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1312 } else
1313 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
1314 continue;
1315 }
1316
1317 // Likewise, noalias intrinsics don't actually write.
1318 if (match(&Inst,
1320 LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
1321 << '\n');
1322 continue;
1323 }
1324
1325 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
1327 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
1328 continue;
1329 }
1330
1331 // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
1333 LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
1334 continue;
1335 }
1336
1337 // We can skip all invariant.start intrinsics since they only read memory,
1338 // and we can forward values across it. For invariant starts without
1339 // invariant ends, we can use the fact that the invariantness never ends to
1340 // start a scope in the current generaton which is true for all future
1341 // generations. Also, we dont need to consume the last store since the
1342 // semantics of invariant.start allow us to perform DSE of the last
1343 // store, if there was a store following invariant.start. Consider:
1344 //
1345 // store 30, i8* p
1346 // invariant.start(p)
1347 // store 40, i8* p
1348 // We can DSE the store to 30, since the store 40 to invariant location p
1349 // causes undefined behaviour.
1351 // If there are any uses, the scope might end.
1352 if (!Inst.use_empty())
1353 continue;
1354 MemoryLocation MemLoc =
1356 // Don't start a scope if we already have a better one pushed
1357 if (!AvailableInvariants.count(MemLoc))
1358 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1359 continue;
1360 }
1361
1362 if (isGuard(&Inst)) {
1363 if (auto *CondI =
1364 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1365 if (SimpleValue::canHandle(CondI)) {
1366 // Do we already know the actual value of this condition?
1367 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1368 // Is the condition known to be true?
1369 if (isa<ConstantInt>(KnownCond) &&
1370 cast<ConstantInt>(KnownCond)->isOne()) {
1372 << "EarlyCSE removing guard: " << Inst << '\n');
1373 salvageKnowledge(&Inst, &AC);
1374 removeMSSA(Inst);
1375 Inst.eraseFromParent();
1376 Changed = true;
1377 continue;
1378 } else
1379 // Use the known value if it wasn't true.
1380 cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1381 }
1382 // The condition we're on guarding here is true for all dominated
1383 // locations.
1384 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1385 }
1386 }
1387
1388 // Guard intrinsics read all memory, but don't write any memory.
1389 // Accordingly, don't update the generation but consume the last store (to
1390 // avoid an incorrect DSE).
1391 LastStore = nullptr;
1392 continue;
1393 }
1394
1395 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1396 // its simpler value.
1397 if (Value *V = simplifyInstruction(&Inst, SQ)) {
1398 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V
1399 << '\n');
1400 if (!DebugCounter::shouldExecute(CSECounter)) {
1401 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1402 } else {
1403 bool Killed = false;
1404 if (!Inst.use_empty()) {
1405 Inst.replaceAllUsesWith(V);
1406 Changed = true;
1407 }
1408 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1409 salvageKnowledge(&Inst, &AC);
1410 removeMSSA(Inst);
1411 Inst.eraseFromParent();
1412 Changed = true;
1413 Killed = true;
1414 }
1415 if (Changed)
1416 ++NumSimplify;
1417 if (Killed)
1418 continue;
1419 }
1420 }
1421
1422 // Make sure stores prior to a potential unwind are not removed, as the
1423 // caller may read the memory.
1424 if (Inst.mayThrow())
1425 LastStore = nullptr;
1426
1427 // If this is a simple instruction that we can value number, process it.
1428 if (SimpleValue::canHandle(&Inst)) {
1429 if ([[maybe_unused]] auto *CI = dyn_cast<ConstrainedFPIntrinsic>(&Inst)) {
1430 assert(CI->getExceptionBehavior() != fp::ebStrict &&
1431 "Unexpected ebStrict from SimpleValue::canHandle()");
1432 assert((!CI->getRoundingMode() ||
1433 CI->getRoundingMode() != RoundingMode::Dynamic) &&
1434 "Unexpected dynamic rounding from SimpleValue::canHandle()");
1435 }
1436 // See if the instruction has an available value. If so, use it.
1437 if (Value *V = AvailableValues.lookup(&Inst)) {
1438 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V
1439 << '\n');
1440 if (!DebugCounter::shouldExecute(CSECounter)) {
1441 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1442 continue;
1443 }
1444 combineIRFlags(Inst, V);
1445 Inst.replaceAllUsesWith(V);
1446 salvageKnowledge(&Inst, &AC);
1447 removeMSSA(Inst);
1448 Inst.eraseFromParent();
1449 Changed = true;
1450 ++NumCSE;
1451 continue;
1452 }
1453
1454 // Otherwise, just remember that this value is available.
1455 AvailableValues.insert(&Inst, &Inst);
1456 continue;
1457 }
1458
1459 ParseMemoryInst MemInst(&Inst, TTI);
1460 // If this is a non-volatile load, process it.
1461 if (MemInst.isValid() && MemInst.isLoad()) {
1462 // (conservatively) we can't peak past the ordering implied by this
1463 // operation, but we can add this load to our set of available values
1464 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1465 LastStore = nullptr;
1466 ++CurrentGeneration;
1467 }
1468
1469 if (MemInst.isInvariantLoad()) {
1470 // If we pass an invariant load, we know that memory location is
1471 // indefinitely constant from the moment of first dereferenceability.
1472 // We conservatively treat the invariant_load as that moment. If we
1473 // pass a invariant load after already establishing a scope, don't
1474 // restart it since we want to preserve the earliest point seen.
1475 auto MemLoc = MemoryLocation::get(&Inst);
1476 if (!AvailableInvariants.count(MemLoc))
1477 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1478 }
1479
1480 // If we have an available version of this load, and if it is the right
1481 // generation or the load is known to be from an invariant location,
1482 // replace this instruction.
1483 //
1484 // If either the dominating load or the current load are invariant, then
1485 // we can assume the current load loads the same value as the dominating
1486 // load.
1487 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1488 if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1489 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1490 << " to: " << *InVal.DefInst << '\n');
1491 if (!DebugCounter::shouldExecute(CSECounter)) {
1492 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1493 continue;
1494 }
1495 if (InVal.IsLoad)
1496 if (auto *I = dyn_cast<Instruction>(Op))
1497 combineMetadataForCSE(I, &Inst, false);
1498 if (!Inst.use_empty())
1499 Inst.replaceAllUsesWith(Op);
1500 salvageKnowledge(&Inst, &AC);
1501 removeMSSA(Inst);
1502 Inst.eraseFromParent();
1503 Changed = true;
1504 ++NumCSELoad;
1505 continue;
1506 }
1507
1508 // Otherwise, remember that we have this instruction.
1509 AvailableLoads.insert(MemInst.getPointerOperand(),
1510 LoadValue(&Inst, CurrentGeneration,
1511 MemInst.getMatchingId(),
1512 MemInst.isAtomic(),
1513 MemInst.isLoad()));
1514 LastStore = nullptr;
1515 continue;
1516 }
1517
1518 // If this instruction may read from memory, forget LastStore. Load/store
1519 // intrinsics will indicate both a read and a write to memory. The target
1520 // may override this (e.g. so that a store intrinsic does not read from
1521 // memory, and thus will be treated the same as a regular store for
1522 // commoning purposes).
1523 if (Inst.mayReadFromMemory() &&
1524 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1525 LastStore = nullptr;
1526
1527 // If this is a read-only or write-only call, process it. Skip store
1528 // MemInsts, as they will be more precisely handled later on. Also skip
1529 // memsets, as DSE may be able to optimize them better by removing the
1530 // earlier rather than later store.
1531 if (CallValue::canHandle(&Inst) &&
1532 (!MemInst.isValid() || !MemInst.isStore()) && !isa<MemSetInst>(&Inst)) {
1533 // If we have an available version of this call, and if it is the right
1534 // generation, replace this instruction.
1535 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1536 if (InVal.first != nullptr &&
1537 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1538 &Inst) &&
1539 InVal.first->mayReadFromMemory() == Inst.mayReadFromMemory()) {
1540 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1541 << " to: " << *InVal.first << '\n');
1542 if (!DebugCounter::shouldExecute(CSECounter)) {
1543 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1544 continue;
1545 }
1546 combineIRFlags(Inst, InVal.first);
1547 if (!Inst.use_empty())
1548 Inst.replaceAllUsesWith(InVal.first);
1549 salvageKnowledge(&Inst, &AC);
1550 removeMSSA(Inst);
1551 Inst.eraseFromParent();
1552 Changed = true;
1553 ++NumCSECall;
1554 continue;
1555 }
1556
1557 // Increase memory generation for writes. Do this before inserting
1558 // the call, so it has the generation after the write occurred.
1559 if (Inst.mayWriteToMemory())
1560 ++CurrentGeneration;
1561
1562 // Otherwise, remember that we have this instruction.
1563 AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1564 continue;
1565 }
1566
1567 // Compare GEP instructions based on offset.
1568 if (GEPValue::canHandle(&Inst)) {
1569 auto *GEP = cast<GetElementPtrInst>(&Inst);
1570 APInt Offset = APInt(SQ.DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1571 GEPValue GEPVal(GEP, GEP->accumulateConstantOffset(SQ.DL, Offset)
1572 ? Offset.trySExtValue()
1573 : std::nullopt);
1574 if (Value *V = AvailableGEPs.lookup(GEPVal)) {
1575 LLVM_DEBUG(dbgs() << "EarlyCSE CSE GEP: " << Inst << " to: " << *V
1576 << '\n');
1577 combineIRFlags(Inst, V);
1578 Inst.replaceAllUsesWith(V);
1579 salvageKnowledge(&Inst, &AC);
1580 removeMSSA(Inst);
1581 Inst.eraseFromParent();
1582 Changed = true;
1583 ++NumCSEGEP;
1584 continue;
1585 }
1586
1587 // Otherwise, just remember that we have this GEP.
1588 AvailableGEPs.insert(GEPVal, &Inst);
1589 continue;
1590 }
1591
1592 // A release fence requires that all stores complete before it, but does
1593 // not prevent the reordering of following loads 'before' the fence. As a
1594 // result, we don't need to consider it as writing to memory and don't need
1595 // to advance the generation. We do need to prevent DSE across the fence,
1596 // but that's handled above.
1597 if (auto *FI = dyn_cast<FenceInst>(&Inst))
1598 if (FI->getOrdering() == AtomicOrdering::Release) {
1599 assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1600 continue;
1601 }
1602
1603 // write back DSE - If we write back the same value we just loaded from
1604 // the same location and haven't passed any intervening writes or ordering
1605 // operations, we can remove the write. The primary benefit is in allowing
1606 // the available load table to remain valid and value forward past where
1607 // the store originally was.
1608 if (MemInst.isValid() && MemInst.isStore()) {
1609 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1610 if (InVal.DefInst &&
1611 InVal.DefInst ==
1612 getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1613 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1614 if (!DebugCounter::shouldExecute(CSECounter)) {
1615 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1616 continue;
1617 }
1618 salvageKnowledge(&Inst, &AC);
1619 removeMSSA(Inst);
1620 Inst.eraseFromParent();
1621 Changed = true;
1622 ++NumDSE;
1623 // We can avoid incrementing the generation count since we were able
1624 // to eliminate this store.
1625 continue;
1626 }
1627 }
1628
1629 // Okay, this isn't something we can CSE at all. Check to see if it is
1630 // something that could modify memory. If so, our available memory values
1631 // cannot be used so bump the generation count.
1632 if (Inst.mayWriteToMemory()) {
1633 ++CurrentGeneration;
1634
1635 if (MemInst.isValid() && MemInst.isStore()) {
1636 // We do a trivial form of DSE if there are two stores to the same
1637 // location with no intervening loads. Delete the earlier store.
1638 if (LastStore) {
1639 if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
1640 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1641 << " due to: " << Inst << '\n');
1642 if (!DebugCounter::shouldExecute(CSECounter)) {
1643 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1644 } else {
1645 salvageKnowledge(&Inst, &AC);
1646 removeMSSA(*LastStore);
1647 LastStore->eraseFromParent();
1648 Changed = true;
1649 ++NumDSE;
1650 LastStore = nullptr;
1651 }
1652 }
1653 // fallthrough - we can exploit information about this store
1654 }
1655
1656 // Okay, we just invalidated anything we knew about loaded values. Try
1657 // to salvage *something* by remembering that the stored value is a live
1658 // version of the pointer. It is safe to forward from volatile stores
1659 // to non-volatile loads, so we don't have to check for volatility of
1660 // the store.
1661 AvailableLoads.insert(MemInst.getPointerOperand(),
1662 LoadValue(&Inst, CurrentGeneration,
1663 MemInst.getMatchingId(),
1664 MemInst.isAtomic(),
1665 MemInst.isLoad()));
1666
1667 // Remember that this was the last unordered store we saw for DSE. We
1668 // don't yet handle DSE on ordered or volatile stores since we don't
1669 // have a good way to model the ordering requirement for following
1670 // passes once the store is removed. We could insert a fence, but
1671 // since fences are slightly stronger than stores in their ordering,
1672 // it's not clear this is a profitable transform. Another option would
1673 // be to merge the ordering with that of the post dominating store.
1674 if (MemInst.isUnordered() && !MemInst.isVolatile())
1675 LastStore = &Inst;
1676 else
1677 LastStore = nullptr;
1678 }
1679 }
1680 }
1681
1682 return Changed;
1683}
1684
1685bool EarlyCSE::run() {
1686 // Note, deque is being used here because there is significant performance
1687 // gains over vector when the container becomes very large due to the
1688 // specific access patterns. For more information see the mailing list
1689 // discussion on this:
1690 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1691 std::deque<StackNode *> nodesToProcess;
1692
1693 bool Changed = false;
1694
1695 // Process the root node.
1696 nodesToProcess.push_back(new StackNode(
1697 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1698 AvailableGEPs, CurrentGeneration, DT.getRootNode(),
1699 DT.getRootNode()->begin(), DT.getRootNode()->end()));
1700
1701 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1702
1703 // Process the stack.
1704 while (!nodesToProcess.empty()) {
1705 // Grab the first item off the stack. Set the current generation, remove
1706 // the node from the stack, and process it.
1707 StackNode *NodeToProcess = nodesToProcess.back();
1708
1709 // Initialize class members.
1710 CurrentGeneration = NodeToProcess->currentGeneration();
1711
1712 // Check if the node needs to be processed.
1713 if (!NodeToProcess->isProcessed()) {
1714 // Process the node.
1715 Changed |= processNode(NodeToProcess->node());
1716 NodeToProcess->childGeneration(CurrentGeneration);
1717 NodeToProcess->process();
1718 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1719 // Push the next child onto the stack.
1720 DomTreeNode *child = NodeToProcess->nextChild();
1721 nodesToProcess.push_back(new StackNode(
1722 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1723 AvailableGEPs, NodeToProcess->childGeneration(), child,
1724 child->begin(), child->end()));
1725 } else {
1726 // It has been processed, and there are no more children to process,
1727 // so delete it and pop it off the stack.
1728 delete NodeToProcess;
1729 nodesToProcess.pop_back();
1730 }
1731 } // while (!nodes...)
1732
1733 return Changed;
1734}
1735
1738 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1739 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1740 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1741 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1742 auto *MSSA =
1743 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1744
1745 EarlyCSE CSE(getScalarOptions(F), F.getDataLayout(), TLI, TTI, DT, AC, MSSA);
1746
1747 if (!CSE.run())
1748 return PreservedAnalyses::all();
1749
1752 if (UseMemorySSA)
1754 return PA;
1755}
1756
1758 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1759 static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
1760 OS, MapClassName2PassName);
1761 OS << '<';
1762 if (UseMemorySSA)
1763 OS << "memssa";
1764 OS << '>';
1765}
1766
1767namespace {
1768
1769/// A simple and fast domtree-based CSE pass.
1770///
1771/// This pass does a simple depth-first walk over the dominator tree,
1772/// eliminating trivially redundant instructions and using instsimplify to
1773/// canonicalize things as it goes. It is intended to be fast and catch obvious
1774/// cases so that instcombine and other passes are more effective. It is
1775/// expected that a later pass of GVN will catch the interesting/hard cases.
1776template<bool UseMemorySSA>
1777class EarlyCSELegacyCommonPass : public FunctionPass {
1778public:
1779 static char ID;
1780
1781 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1782 if (UseMemorySSA)
1784 else
1786 }
1787
1788 bool runOnFunction(Function &F) override {
1789 if (skipFunction(F))
1790 return false;
1791
1792 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1793 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1794 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1795 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1796 auto *MSSA =
1797 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1798
1799 EarlyCSE CSE(getScalarOptions(F), F.getDataLayout(), TLI, TTI, DT, AC,
1800 MSSA);
1801
1802 return CSE.run();
1803 }
1804
1805 void getAnalysisUsage(AnalysisUsage &AU) const override {
1806 AU.addRequired<AssumptionCacheTracker>();
1807 AU.addRequired<DominatorTreeWrapperPass>();
1808 AU.addRequired<TargetLibraryInfoWrapperPass>();
1809 AU.addRequired<TargetTransformInfoWrapperPass>();
1810 if (UseMemorySSA) {
1811 AU.addRequired<AAResultsWrapperPass>();
1812 AU.addRequired<MemorySSAWrapperPass>();
1813 AU.addPreserved<MemorySSAWrapperPass>();
1814 }
1815 AU.addPreserved<GlobalsAAWrapperPass>();
1816 AU.addPreserved<AAResultsWrapperPass>();
1817 AU.setPreservesCFG();
1818 }
1819};
1820
1821} // end anonymous namespace
1822
1823using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1824
1825template<>
1826char EarlyCSELegacyPass::ID = 0;
1827
1828INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1829 false)
1834INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1835
1836using EarlyCSEMemSSALegacyPass =
1837 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1838
1839template<>
1840char EarlyCSEMemSSALegacyPass::ID = 0;
1841
1843 if (UseMemorySSA)
1844 return new EarlyCSEMemSSALegacyPass();
1845 else
1846 return new EarlyCSELegacyPass();
1847}
1848
1849INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1850 "Early CSE w/ MemorySSA", false, false)
1857INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1858 "Early CSE w/ MemorySSA", false, false)
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isLoad(int Opcode)
static bool isStore(int Opcode)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
Atomic ordering constants.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Optimize for code generation
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines DenseMapInfo traits for DenseMap.
static void combineIRFlags(Instruction &From, Value *To)
EarlyCSELegacyCommonPass< false > EarlyCSELegacyPass
static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A, Value *&B)
Match a 'select' including an optional 'not's of the condition.
Definition EarlyCSE.cpp:149
early cse Early CSE w MemorySSA
static unsigned getHashValueImpl(SimpleValue Val)
Definition EarlyCSE.cpp:176
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
Definition EarlyCSE.cpp:284
static unsigned hashCallInst(CallInst *CI)
Definition EarlyCSE.cpp:165
This file provides the interface for a simple, fast CSE pass.
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
static bool isInvariantLoad(const Instruction *I, const Value *Ptr, const bool IsKernelFn)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineOperand, 4 > Cond
const RISCVInstrInfo * RII
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
separate const offset from Split GEPs to a variadic base and a constant offset for better CSE
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
bool isProcessed() const
unsigned currentGeneration() const
unsigned childGeneration() const
DomTreeNode::const_iterator end() const
void process()
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
DomTreeNode * node()
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
bool onlyWritesMemory(unsigned OpNo) const
bool onlyReadsMemory(unsigned OpNo) const
bool isConvergent() const
Determine if the invoke is convergent.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
static bool shouldExecute(CounterInfo &Counter)
iterator begin() const
iterator end() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
This instruction extracts a struct member or array element value from an aggregate value.
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isPresplitCoroutine() const
Determine if the function is presplit coroutine.
Definition Function.h:522
Represents calls to the gc.relocate intrinsic.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:917
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1030
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:970
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:714
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
ScopedHashTableScope< SimpleValue, Value *, DenseMapInfo< SimpleValue >, AllocatorTy > ScopeTy
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Wrapper pass for TargetTransformInfo.
LLVM_ABI bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const
Value * getOperand(unsigned i) const
Definition User.h:207
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
bool use_empty() const
Definition Value.h:348
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
auto m_Cmp()
Matches any compare instruction and ignore it.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:390
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
Type * getValueType(Value *V, bool ReVec, bool LookThroughCmp)
Returns the "element type" of the given value/instruction V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1678
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
const ScalarOptions & getScalarOptions(const LLVMContext &C)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void initializeEarlyCSEMemSSALegacyPassPass(PassRegistry &)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3126
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
LLVM_ABI void initializeEarlyCSELegacyPassPass(PassRegistry &)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
unsigned Generation
static unsigned getHashValue(CallValue Val)
static bool isEqual(CallValue LHS, CallValue RHS)
static bool isEqual(const GEPValue &LHS, const GEPValue &RHS)
static unsigned getHashValue(const GEPValue &Val)
static unsigned getHashValue(SimpleValue Val)
static bool isEqual(SimpleValue LHS, SimpleValue RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
const DataLayout & DL