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 (ScalarOptions::Global.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 TargetLibraryInfo &TLI;
503 const TargetTransformInfo &TTI;
504 DominatorTree &DT;
505 AssumptionCache &AC;
506 const SimplifyQuery SQ;
507 MemorySSA *MSSA;
508 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
509
510 using AllocatorTy =
511 RecyclingAllocator<BumpPtrAllocator,
512 ScopedHashTableVal<SimpleValue, Value *>>;
513 using ScopedHTType =
514 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
515 AllocatorTy>;
516
517 /// A scoped hash table of the current values of all of our simple
518 /// scalar expressions.
519 ///
520 /// As we walk down the domtree, we look to see if instructions are in this:
521 /// if so, we replace them with what we find, otherwise we insert them so
522 /// that dominated values can succeed in their lookup.
523 ScopedHTType AvailableValues;
524
525 /// A scoped hash table of the current values of previously encountered
526 /// memory locations.
527 ///
528 /// This allows us to get efficient access to dominating loads or stores when
529 /// we have a fully redundant load. In addition to the most recent load, we
530 /// keep track of a generation count of the read, which is compared against
531 /// the current generation count. The current generation count is incremented
532 /// after every possibly writing memory operation, which ensures that we only
533 /// CSE loads with other loads that have no intervening store. Ordering
534 /// events (such as fences or atomic instructions) increment the generation
535 /// count as well; essentially, we model these as writes to all possible
536 /// locations. Note that atomic and/or volatile loads and stores can be
537 /// present the table; it is the responsibility of the consumer to inspect
538 /// the atomicity/volatility if needed.
539 struct LoadValue {
540 Instruction *DefInst = nullptr;
541 unsigned Generation = 0;
542 int MatchingId = -1;
543 bool IsAtomic = false;
544 bool IsLoad = false;
545
546 LoadValue() = default;
547 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
548 bool IsAtomic, bool IsLoad)
549 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
550 IsAtomic(IsAtomic), IsLoad(IsLoad) {}
551 };
552
553 using LoadMapAllocator =
554 RecyclingAllocator<BumpPtrAllocator,
555 ScopedHashTableVal<Value *, LoadValue>>;
556 using LoadHTType =
557 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
558 LoadMapAllocator>;
559
560 LoadHTType AvailableLoads;
561
562 // A scoped hash table mapping memory locations (represented as typed
563 // addresses) to generation numbers at which that memory location became
564 // (henceforth indefinitely) invariant.
565 using InvariantMapAllocator =
566 RecyclingAllocator<BumpPtrAllocator,
567 ScopedHashTableVal<MemoryLocation, unsigned>>;
568 using InvariantHTType =
569 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
570 InvariantMapAllocator>;
571 InvariantHTType AvailableInvariants;
572
573 /// A scoped hash table of the current values of read-only call
574 /// values.
575 ///
576 /// It uses the same generation count as loads.
577 using CallHTType =
578 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
579 CallHTType AvailableCalls;
580
581 using GEPMapAllocatorTy =
582 RecyclingAllocator<BumpPtrAllocator,
583 ScopedHashTableVal<GEPValue, Value *>>;
584 using GEPHTType = ScopedHashTable<GEPValue, Value *, DenseMapInfo<GEPValue>,
585 GEPMapAllocatorTy>;
586 GEPHTType AvailableGEPs;
587
588 /// This is the current generation of the memory value.
589 unsigned CurrentGeneration = 0;
590
591 /// Set up the EarlyCSE runner for a particular function.
592 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
593 const TargetTransformInfo &TTI, DominatorTree &DT,
594 AssumptionCache &AC, MemorySSA *MSSA)
595 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
596 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
597
598 bool run();
599
600private:
601 unsigned ClobberCounter = 0;
602 // Almost a POD, but needs to call the constructors for the scoped hash
603 // tables so that a new scope gets pushed on. These are RAII so that the
604 // scope gets popped when the NodeScope is destroyed.
605 class NodeScope {
606 public:
607 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
608 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
609 GEPHTType &AvailableGEPs)
610 : Scope(AvailableValues), LoadScope(AvailableLoads),
611 InvariantScope(AvailableInvariants), CallScope(AvailableCalls),
612 GEPScope(AvailableGEPs) {}
613 NodeScope(const NodeScope &) = delete;
614 NodeScope &operator=(const NodeScope &) = delete;
615
616 private:
618 LoadHTType::ScopeTy LoadScope;
619 InvariantHTType::ScopeTy InvariantScope;
620 CallHTType::ScopeTy CallScope;
621 GEPHTType::ScopeTy GEPScope;
622 };
623
624 // Contains all the needed information to create a stack for doing a depth
625 // first traversal of the tree. This includes scopes for values, loads, and
626 // calls as well as the generation. There is a child iterator so that the
627 // children do not need to be store separately.
628 class StackNode {
629 public:
630 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
631 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
632 GEPHTType &AvailableGEPs, unsigned cg, DomTreeNode *n,
633 DomTreeNode::const_iterator child,
634 DomTreeNode::const_iterator end)
635 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
636 EndIter(end),
637 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
638 AvailableCalls, AvailableGEPs) {}
639 StackNode(const StackNode &) = delete;
640 StackNode &operator=(const StackNode &) = delete;
641
642 // Accessors.
643 unsigned currentGeneration() const { return CurrentGeneration; }
644 unsigned childGeneration() const { return ChildGeneration; }
645 void childGeneration(unsigned generation) { ChildGeneration = generation; }
646 DomTreeNode *node() { return Node; }
647 DomTreeNode::const_iterator childIter() const { return ChildIter; }
648
649 DomTreeNode *nextChild() {
650 DomTreeNode *child = *ChildIter;
651 ++ChildIter;
652 return child;
653 }
654
655 DomTreeNode::const_iterator end() const { return EndIter; }
656 bool isProcessed() const { return Processed; }
657 void process() { Processed = true; }
658
659 private:
660 unsigned CurrentGeneration;
661 unsigned ChildGeneration;
662 DomTreeNode *Node;
663 DomTreeNode::const_iterator ChildIter;
664 DomTreeNode::const_iterator EndIter;
665 NodeScope Scopes;
666 bool Processed = false;
667 };
668
669 /// Wrapper class to handle memory instructions, including loads,
670 /// stores and intrinsic loads and stores defined by the target.
671 class ParseMemoryInst {
672 public:
673 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
674 : Inst(Inst) {
675 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
676 IntrID = II->getIntrinsicID();
677 if (TTI.getTgtMemIntrinsic(II, Info))
678 return;
679 if (isHandledNonTargetIntrinsic(IntrID)) {
680 switch (IntrID) {
681 case Intrinsic::masked_load:
682 Info.PtrVal = Inst->getOperand(0);
683 Info.MatchingId = Intrinsic::masked_load;
684 Info.ReadMem = true;
685 Info.WriteMem = false;
686 Info.IsVolatile = false;
687 break;
688 case Intrinsic::masked_store:
689 Info.PtrVal = Inst->getOperand(1);
690 // Use the ID of masked load as the "matching id". This will
691 // prevent matching non-masked loads/stores with masked ones
692 // (which could be done), but at the moment, the code here
693 // does not support matching intrinsics with non-intrinsics,
694 // so keep the MatchingIds specific to masked instructions
695 // for now (TODO).
696 Info.MatchingId = Intrinsic::masked_load;
697 Info.ReadMem = false;
698 Info.WriteMem = true;
699 Info.IsVolatile = false;
700 break;
701 }
702 } else if (auto *MI = dyn_cast<MemSetInst>(Inst)) {
703 Info.PtrVal = MI->getDest();
704 Info.MatchingId = 0;
705 Info.ReadMem = false;
706 Info.WriteMem = true;
707 Info.IsVolatile = MI->isVolatile();
708 }
709 }
710 }
711
712 Instruction *get() { return Inst; }
713 const Instruction *get() const { return Inst; }
714
715 bool isLoad() const {
716 if (IntrID != 0)
717 return Info.ReadMem;
718 return isa<LoadInst>(Inst);
719 }
720
721 bool isStore() const {
722 if (IntrID != 0)
723 return Info.WriteMem;
724 return isa<StoreInst>(Inst);
725 }
726
727 bool isAtomic() const {
728 if (IntrID != 0)
729 return Info.Ordering != AtomicOrdering::NotAtomic;
730 return Inst->isAtomic();
731 }
732
733 bool isUnordered() const {
734 if (IntrID != 0)
735 return Info.isUnordered();
736
737 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
738 return LI->isUnordered();
739 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
740 return SI->isUnordered();
741 }
742 // Conservative answer
743 return !Inst->isAtomic();
744 }
745
746 bool isVolatile() const {
747 if (IntrID != 0)
748 return Info.IsVolatile;
749
750 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
751 return LI->isVolatile();
752 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
753 return SI->isVolatile();
754 }
755 // Conservative answer
756 return true;
757 }
758
759 bool isInvariantLoad() const {
760 if (auto *LI = dyn_cast<LoadInst>(Inst))
761 return LI->hasMetadata(LLVMContext::MD_invariant_load);
762 return false;
763 }
764
765 bool isValid() const { return getPointerOperand() != nullptr; }
766
767 // For regular (non-intrinsic) loads/stores, this is set to -1. For
768 // intrinsic loads/stores, the id is retrieved from the corresponding
769 // field in the MemIntrinsicInfo structure. That field contains
770 // non-negative values only.
771 int getMatchingId() const {
772 if (IntrID != 0)
773 return Info.MatchingId;
774 return -1;
775 }
776
777 Value *getPointerOperand() const {
778 if (IntrID != 0)
779 return Info.PtrVal;
780 return getLoadStorePointerOperand(Inst);
781 }
782
783 Type *getValueType() const {
784 // TODO: handle target-specific intrinsics.
785 return Inst->getAccessType();
786 }
787
788 bool mayReadFromMemory() const {
789 if (IntrID != 0)
790 return Info.ReadMem;
791 return Inst->mayReadFromMemory();
792 }
793
794 bool mayWriteToMemory() const {
795 if (IntrID != 0)
796 return Info.WriteMem;
797 return Inst->mayWriteToMemory();
798 }
799
800 private:
801 Intrinsic::ID IntrID = 0;
802 MemIntrinsicInfo Info;
803 Instruction *Inst;
804 };
805
806 // This function is to prevent accidentally passing a non-target
807 // intrinsic ID to TargetTransformInfo.
808 static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
809 switch (ID) {
810 case Intrinsic::masked_load:
811 case Intrinsic::masked_store:
812 return true;
813 }
814 return false;
815 }
816 static bool isHandledNonTargetIntrinsic(const Value *V) {
817 if (auto *II = dyn_cast<IntrinsicInst>(V))
818 return isHandledNonTargetIntrinsic(II->getIntrinsicID());
819 return false;
820 }
821
822 bool processNode(DomTreeNode *Node);
823
824 bool handleBranchCondition(Instruction *CondInst, const CondBrInst *BI,
825 const BasicBlock *BB, const BasicBlock *Pred);
826
827 Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
828 unsigned CurrentGeneration);
829
830 bool overridingStores(const ParseMemoryInst &Earlier,
831 const ParseMemoryInst &Later);
832
833 Value *getOrCreateResult(Instruction *Inst, Type *ExpectedType,
834 bool CanCreate) const {
835 // TODO: We could insert relevant casts on type mismatch.
836 // The load or the store's first operand.
837 Value *V;
838 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
839 switch (II->getIntrinsicID()) {
840 case Intrinsic::masked_load:
841 V = II;
842 break;
843 case Intrinsic::masked_store:
844 V = II->getOperand(0);
845 break;
846 default:
847 return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType,
848 CanCreate);
849 }
850 } else {
851 V = isa<LoadInst>(Inst) ? Inst : cast<StoreInst>(Inst)->getValueOperand();
852 }
853
854 return V->getType() == ExpectedType ? V : nullptr;
855 }
856
857 /// Return true if the instruction is known to only operate on memory
858 /// provably invariant in the given "generation".
859 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
860
861 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
862 Instruction *EarlierInst, Instruction *LaterInst);
863
864 bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
865 const IntrinsicInst *Later) {
866 auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
867 // Is Mask0 a submask of Mask1?
868 if (Mask0 == Mask1)
869 return true;
870 if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
871 return false;
872 auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
873 auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
874 if (!Vec0 || !Vec1)
875 return false;
876 if (Vec0->getType() != Vec1->getType())
877 return false;
878 for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
879 Constant *Elem0 = Vec0->getOperand(i);
880 Constant *Elem1 = Vec1->getOperand(i);
881 auto *Int0 = dyn_cast<ConstantInt>(Elem0);
882 if (Int0 && Int0->isZero())
883 continue;
884 auto *Int1 = dyn_cast<ConstantInt>(Elem1);
885 if (Int1 && !Int1->isZero())
886 continue;
887 if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
888 return false;
889 if (Elem0 == Elem1)
890 continue;
891 return false;
892 }
893 return true;
894 };
895 auto PtrOp = [](const IntrinsicInst *II) {
896 if (II->getIntrinsicID() == Intrinsic::masked_load)
897 return II->getOperand(0);
898 if (II->getIntrinsicID() == Intrinsic::masked_store)
899 return II->getOperand(1);
900 llvm_unreachable("Unexpected IntrinsicInst");
901 };
902 auto MaskOp = [](const IntrinsicInst *II) {
903 if (II->getIntrinsicID() == Intrinsic::masked_load)
904 return II->getOperand(1);
905 if (II->getIntrinsicID() == Intrinsic::masked_store)
906 return II->getOperand(2);
907 llvm_unreachable("Unexpected IntrinsicInst");
908 };
909 auto ThruOp = [](const IntrinsicInst *II) {
910 if (II->getIntrinsicID() == Intrinsic::masked_load)
911 return II->getOperand(2);
912 llvm_unreachable("Unexpected IntrinsicInst");
913 };
914
915 if (PtrOp(Earlier) != PtrOp(Later))
916 return false;
917
918 Intrinsic::ID IDE = Earlier->getIntrinsicID();
919 Intrinsic::ID IDL = Later->getIntrinsicID();
920 // We could really use specific intrinsic classes for masked loads
921 // and stores in IntrinsicInst.h.
922 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
923 // Trying to replace later masked load with the earlier one.
924 // Check that the pointers are the same, and
925 // - masks and pass-throughs are the same, or
926 // - replacee's pass-through is "undef" and replacer's mask is a
927 // super-set of the replacee's mask.
928 if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
929 return true;
930 if (!isa<UndefValue>(ThruOp(Later)))
931 return false;
932 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
933 }
934 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
935 // Trying to replace a load of a stored value with the store's value.
936 // Check that the pointers are the same, and
937 // - load's mask is a subset of store's mask, and
938 // - load's pass-through is "undef".
939 if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
940 return false;
941 return isa<UndefValue>(ThruOp(Later));
942 }
943 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
944 // Trying to remove a store of the loaded value.
945 // Check that the pointers are the same, and
946 // - store's mask is a subset of the load's mask.
947 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
948 }
949 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
950 // Trying to remove a dead store (earlier).
951 // Check that the pointers are the same,
952 // - the to-be-removed store's mask is a subset of the other store's
953 // mask.
954 return IsSubmask(MaskOp(Earlier), MaskOp(Later));
955 }
956 return false;
957 }
958
959 void removeMSSA(Instruction &Inst) {
960 if (!MSSA)
961 return;
962 if (VerifyMemorySSA)
963 MSSA->verifyMemorySSA();
964 // Removing a store here can leave MemorySSA in an unoptimized state by
965 // creating MemoryPhis that have identical arguments and by creating
966 // MemoryUses whose defining access is not an actual clobber. The phi case
967 // is handled by MemorySSA when passing OptimizePhis = true to
968 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
969 // by MemorySSA's getClobberingMemoryAccess.
970 MSSAUpdater->removeMemoryAccess(&Inst, true);
971 }
972};
973
974} // end anonymous namespace
975
976/// Determine if the memory referenced by LaterInst is from the same heap
977/// version as EarlierInst.
978/// This is currently called in two scenarios:
979///
980/// load p
981/// ...
982/// load p
983///
984/// and
985///
986/// x = load p
987/// ...
988/// store x, p
989///
990/// in both cases we want to verify that there are no possible writes to the
991/// memory referenced by p between the earlier and later instruction.
992bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
993 unsigned LaterGeneration,
994 Instruction *EarlierInst,
995 Instruction *LaterInst) {
996 // Check the simple memory generation tracking first.
997 if (EarlierGeneration == LaterGeneration)
998 return true;
999
1000 if (!MSSA)
1001 return false;
1002
1003 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
1004 // read/write memory, then we can safely return true here.
1005 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
1006 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
1007 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
1008 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
1009 // with the default optimization pipeline.
1010 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
1011 if (!EarlierMA)
1012 return true;
1013 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
1014 if (!LaterMA)
1015 return true;
1016
1017 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
1018 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
1019 // EarlierInst and LaterInst and neither can any other write that potentially
1020 // clobbers LaterInst.
1021 MemoryAccess *LaterDef;
1022 if (ClobberCounter < ScalarOptions::Global.earlycse_mssa_optimization_cap) {
1023 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
1024 ClobberCounter++;
1025 } else
1026 LaterDef = LaterMA->getDefiningAccess();
1027
1028 return MSSA->dominates(LaterDef, EarlierMA);
1029}
1030
1031bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
1032 // A location loaded from with an invariant_load is assumed to *never* change
1033 // within the visible scope of the compilation.
1034 if (auto *LI = dyn_cast<LoadInst>(I))
1035 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1036 return true;
1037
1038 auto MemLocOpt = MemoryLocation::getOrNone(I);
1039 if (!MemLocOpt)
1040 // "target" intrinsic forms of loads aren't currently known to
1041 // MemoryLocation::get. TODO
1042 return false;
1043 MemoryLocation MemLoc = *MemLocOpt;
1044 if (!AvailableInvariants.count(MemLoc))
1045 return false;
1046
1047 // Is the generation at which this became invariant older than the
1048 // current one?
1049 return AvailableInvariants.lookup(MemLoc) <= GenAt;
1050}
1051
1052bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
1053 const CondBrInst *BI, const BasicBlock *BB,
1054 const BasicBlock *Pred) {
1055 assert(BI->getCondition() == CondInst && "Wrong condition?");
1056 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
1057 auto *TorF = (BI->getSuccessor(0) == BB)
1059 : ConstantInt::getFalse(BB->getContext());
1060 auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
1061 Value *&RHS) {
1062 if (Opcode == Instruction::And &&
1064 return true;
1065 else if (Opcode == Instruction::Or &&
1067 return true;
1068 return false;
1069 };
1070 // If the condition is AND operation, we can propagate its operands into the
1071 // true branch. If it is OR operation, we can propagate them into the false
1072 // branch.
1073 unsigned PropagateOpcode =
1074 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
1075
1076 bool MadeChanges = false;
1077 SmallVector<Instruction *, 4> WorkList;
1078 SmallPtrSet<Instruction *, 4> Visited;
1079 WorkList.push_back(CondInst);
1080 while (!WorkList.empty()) {
1081 Instruction *Curr = WorkList.pop_back_val();
1082
1083 AvailableValues.insert(Curr, TorF);
1084 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
1085 << Curr->getName() << "' as " << *TorF << " in "
1086 << BB->getName() << "\n");
1087 if (!DebugCounter::shouldExecute(CSECounter)) {
1088 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1089 } else {
1090 // Replace all dominated uses with the known value.
1091 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
1092 BasicBlockEdge(Pred, BB))) {
1093 NumCSECVP += Count;
1094 MadeChanges = true;
1095 }
1096 }
1097
1098 Value *LHS, *RHS;
1099 if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
1100 for (auto *Op : { LHS, RHS })
1101 if (Instruction *OPI = dyn_cast<Instruction>(Op))
1102 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
1103 WorkList.push_back(OPI);
1104 }
1105
1106 return MadeChanges;
1107}
1108
1109Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
1110 unsigned CurrentGeneration) {
1111 if (InVal.DefInst == nullptr)
1112 return nullptr;
1113 if (auto *MSI = dyn_cast<MemSetInst>(InVal.DefInst)) {
1114 if (!MemInst.isLoad() || MemInst.isVolatile() || !MemInst.isUnordered() ||
1115 MemInst.getMatchingId() != -1)
1116 return nullptr;
1117 if (MSI->isVolatile())
1118 return nullptr;
1119 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
1120 if (!Val || !Val->isZero())
1121 return nullptr;
1122 auto Len = MSI->getLengthInBytes();
1123 if (!Len)
1124 return nullptr;
1125 Type *InstType = MemInst.getValueType();
1126 if (!InstType)
1127 return nullptr;
1128 TypeSize LoadSize = SQ.DL.getTypeStoreSize(InstType);
1129 if (LoadSize.isScalable() || Len->ult(LoadSize.getFixedValue()))
1130 return nullptr;
1131 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1132 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1133 MemInst.get()))
1134 return nullptr;
1135 return Constant::getNullValue(MemInst.getValueType());
1136 }
1137 if (InVal.MatchingId != MemInst.getMatchingId())
1138 return nullptr;
1139 // We don't yet handle removing loads with ordering of any kind.
1140 if (MemInst.isVolatile() || !MemInst.isUnordered())
1141 return nullptr;
1142 // We can't replace an atomic load with one which isn't also atomic.
1143 if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
1144 return nullptr;
1145 // The value V returned from this function is used differently depending
1146 // on whether MemInst is a load or a store. If it's a load, we will replace
1147 // MemInst with V, if it's a store, we will check if V is the same as the
1148 // available value.
1149 bool MemInstMatching = !MemInst.isLoad();
1150 Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
1151 Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
1152
1153 // For stores check the result values before checking memory generation
1154 // (otherwise isSameMemGeneration may crash).
1155 Value *Result =
1156 MemInst.isStore()
1157 ? getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/false)
1158 : nullptr;
1159 if (MemInst.isStore() && InVal.DefInst != Result)
1160 return nullptr;
1161
1162 // Deal with non-target memory intrinsics.
1163 bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
1164 bool OtherNTI = isHandledNonTargetIntrinsic(Other);
1165 if (OtherNTI != MatchingNTI)
1166 return nullptr;
1167 if (OtherNTI && MatchingNTI) {
1168 if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
1169 cast<IntrinsicInst>(MemInst.get())))
1170 return nullptr;
1171 }
1172
1173 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1174 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1175 MemInst.get()))
1176 return nullptr;
1177
1178 if (!Result)
1179 Result = getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/true);
1180 return Result;
1181}
1182
1183static void combineIRFlags(Instruction &From, Value *To) {
1184 if (auto *I = dyn_cast<Instruction>(To)) {
1185 // If I being poison triggers UB, there is no need to drop those
1186 // flags. Otherwise, only retain flags present on both I and Inst.
1187 // TODO: Currently some fast-math flags are not treated as
1188 // poison-generating even though they should. Until this is fixed,
1189 // always retain flags present on both I and Inst for floating point
1190 // instructions.
1191 if (isa<FPMathOperator>(I) ||
1192 (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
1193 I->andIRFlags(&From);
1194 }
1195 if (isa<CallBase>(&From) && isa<CallBase>(To)) {
1196 // NB: Intersection of attrs between InVal.first and Inst is overly
1197 // conservative. Since we only CSE readonly functions that have the same
1198 // memory state, we can preserve (or possibly in some cases combine)
1199 // more attributes. Likewise this implies when checking equality of
1200 // callsite for CSEing, we can probably ignore more attributes.
1201 // Generally poison generating attributes need to be handled with more
1202 // care as they can create *new* UB if preserved/combined and violated.
1203 // Attributes that imply immediate UB on the other hand would have been
1204 // violated either way.
1205 bool Success =
1206 cast<CallBase>(To)->tryIntersectAttributes(cast<CallBase>(&From));
1207 assert(Success && "Failed to intersect attributes in callsites that "
1208 "passed identical check");
1209 // For NDEBUG Compile.
1210 (void)Success;
1211 }
1212}
1213
1214bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
1215 const ParseMemoryInst &Later) {
1216 // Can we remove Earlier store because of Later store?
1217
1218 assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
1219 "Violated invariant");
1220 if (Earlier.getPointerOperand() != Later.getPointerOperand())
1221 return false;
1222 if (!Earlier.getValueType() || !Later.getValueType() ||
1223 Earlier.getValueType() != Later.getValueType())
1224 return false;
1225 if (Earlier.getMatchingId() != Later.getMatchingId())
1226 return false;
1227 // At the moment, we don't remove ordered stores, but do remove
1228 // unordered atomic stores. There's no special requirement (for
1229 // unordered atomics) about removing atomic stores only in favor of
1230 // other atomic stores since we were going to execute the non-atomic
1231 // one anyway and the atomic one might never have become visible.
1232 if (!Earlier.isUnordered() || !Later.isUnordered())
1233 return false;
1234
1235 // Deal with non-target memory intrinsics.
1236 bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
1237 bool LNTI = isHandledNonTargetIntrinsic(Later.get());
1238 if (ENTI && LNTI)
1239 return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
1240 cast<IntrinsicInst>(Later.get()));
1241
1242 // Because of the check above, at least one of them is false.
1243 // For now disallow matching intrinsics with non-intrinsics,
1244 // so assume that the stores match if neither is an intrinsic.
1245 return ENTI == LNTI;
1246}
1247
1248bool EarlyCSE::processNode(DomTreeNode *Node) {
1249 bool Changed = false;
1250 BasicBlock *BB = Node->getBlock();
1251
1252 // If this block has a single predecessor, then the predecessor is the parent
1253 // of the domtree node and all of the live out memory values are still current
1254 // in this block. If this block has multiple predecessors, then they could
1255 // have invalidated the live-out memory values of our parent value. For now,
1256 // just be conservative and invalidate memory if this block has multiple
1257 // predecessors.
1258 if (!BB->getSinglePredecessor())
1259 ++CurrentGeneration;
1260
1261 // If this node has a single predecessor which ends in a conditional branch,
1262 // we can infer the value of the branch condition given that we took this
1263 // path. We need the single predecessor to ensure there's not another path
1264 // which reaches this block where the condition might hold a different
1265 // value. Since we're adding this to the scoped hash table (like any other
1266 // def), it will have been popped if we encounter a future merge block.
1267 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1268 if (auto *BI = dyn_cast<CondBrInst>(Pred->getTerminator())) {
1269 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
1270 if (CondInst && SimpleValue::canHandle(CondInst))
1271 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
1272 }
1273 }
1274
1275 /// LastStore - Keep track of the last non-volatile store that we saw... for
1276 /// as long as there in no instruction that reads memory. If we see a store
1277 /// to the same location, we delete the dead store. This zaps trivial dead
1278 /// stores which can occur in bitfield code among other things.
1279 Instruction *LastStore = nullptr;
1280
1281 // See if any instructions in the block can be eliminated. If so, do it. If
1282 // not, add them to AvailableValues.
1283 for (Instruction &Inst : make_early_inc_range(*BB)) {
1284 // Dead instructions should just be removed.
1285 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1286 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
1287 if (!DebugCounter::shouldExecute(CSECounter)) {
1288 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1289 continue;
1290 }
1291
1292 salvageKnowledge(&Inst, &AC);
1293 salvageDebugInfo(Inst);
1294 removeMSSA(Inst);
1295 Inst.eraseFromParent();
1296 Changed = true;
1297 ++NumSimplify;
1298 continue;
1299 }
1300
1301 // Skip assume intrinsics, they don't really have side effects (although
1302 // they're marked as such to ensure preservation of control dependencies),
1303 // and this pass will not bother with its removal. However, we should mark
1304 // its condition as true for all dominated blocks.
1305 if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
1306 auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
1307 if (CondI && SimpleValue::canHandle(CondI)) {
1308 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
1309 << '\n');
1310 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1311 } else
1312 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
1313 continue;
1314 }
1315
1316 // Likewise, noalias intrinsics don't actually write.
1317 if (match(&Inst,
1319 LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
1320 << '\n');
1321 continue;
1322 }
1323
1324 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
1326 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
1327 continue;
1328 }
1329
1330 // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
1332 LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
1333 continue;
1334 }
1335
1336 // We can skip all invariant.start intrinsics since they only read memory,
1337 // and we can forward values across it. For invariant starts without
1338 // invariant ends, we can use the fact that the invariantness never ends to
1339 // start a scope in the current generaton which is true for all future
1340 // generations. Also, we dont need to consume the last store since the
1341 // semantics of invariant.start allow us to perform DSE of the last
1342 // store, if there was a store following invariant.start. Consider:
1343 //
1344 // store 30, i8* p
1345 // invariant.start(p)
1346 // store 40, i8* p
1347 // We can DSE the store to 30, since the store 40 to invariant location p
1348 // causes undefined behaviour.
1350 // If there are any uses, the scope might end.
1351 if (!Inst.use_empty())
1352 continue;
1353 MemoryLocation MemLoc =
1355 // Don't start a scope if we already have a better one pushed
1356 if (!AvailableInvariants.count(MemLoc))
1357 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1358 continue;
1359 }
1360
1361 if (isGuard(&Inst)) {
1362 if (auto *CondI =
1363 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1364 if (SimpleValue::canHandle(CondI)) {
1365 // Do we already know the actual value of this condition?
1366 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1367 // Is the condition known to be true?
1368 if (isa<ConstantInt>(KnownCond) &&
1369 cast<ConstantInt>(KnownCond)->isOne()) {
1371 << "EarlyCSE removing guard: " << Inst << '\n');
1372 salvageKnowledge(&Inst, &AC);
1373 removeMSSA(Inst);
1374 Inst.eraseFromParent();
1375 Changed = true;
1376 continue;
1377 } else
1378 // Use the known value if it wasn't true.
1379 cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1380 }
1381 // The condition we're on guarding here is true for all dominated
1382 // locations.
1383 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1384 }
1385 }
1386
1387 // Guard intrinsics read all memory, but don't write any memory.
1388 // Accordingly, don't update the generation but consume the last store (to
1389 // avoid an incorrect DSE).
1390 LastStore = nullptr;
1391 continue;
1392 }
1393
1394 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1395 // its simpler value.
1396 if (Value *V = simplifyInstruction(&Inst, SQ)) {
1397 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V
1398 << '\n');
1399 if (!DebugCounter::shouldExecute(CSECounter)) {
1400 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1401 } else {
1402 bool Killed = false;
1403 if (!Inst.use_empty()) {
1404 Inst.replaceAllUsesWith(V);
1405 Changed = true;
1406 }
1407 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1408 salvageKnowledge(&Inst, &AC);
1409 removeMSSA(Inst);
1410 Inst.eraseFromParent();
1411 Changed = true;
1412 Killed = true;
1413 }
1414 if (Changed)
1415 ++NumSimplify;
1416 if (Killed)
1417 continue;
1418 }
1419 }
1420
1421 // Make sure stores prior to a potential unwind are not removed, as the
1422 // caller may read the memory.
1423 if (Inst.mayThrow())
1424 LastStore = nullptr;
1425
1426 // If this is a simple instruction that we can value number, process it.
1427 if (SimpleValue::canHandle(&Inst)) {
1428 if ([[maybe_unused]] auto *CI = dyn_cast<ConstrainedFPIntrinsic>(&Inst)) {
1429 assert(CI->getExceptionBehavior() != fp::ebStrict &&
1430 "Unexpected ebStrict from SimpleValue::canHandle()");
1431 assert((!CI->getRoundingMode() ||
1432 CI->getRoundingMode() != RoundingMode::Dynamic) &&
1433 "Unexpected dynamic rounding from SimpleValue::canHandle()");
1434 }
1435 // See if the instruction has an available value. If so, use it.
1436 if (Value *V = AvailableValues.lookup(&Inst)) {
1437 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V
1438 << '\n');
1439 if (!DebugCounter::shouldExecute(CSECounter)) {
1440 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1441 continue;
1442 }
1443 combineIRFlags(Inst, V);
1444 Inst.replaceAllUsesWith(V);
1445 salvageKnowledge(&Inst, &AC);
1446 removeMSSA(Inst);
1447 Inst.eraseFromParent();
1448 Changed = true;
1449 ++NumCSE;
1450 continue;
1451 }
1452
1453 // Otherwise, just remember that this value is available.
1454 AvailableValues.insert(&Inst, &Inst);
1455 continue;
1456 }
1457
1458 ParseMemoryInst MemInst(&Inst, TTI);
1459 // If this is a non-volatile load, process it.
1460 if (MemInst.isValid() && MemInst.isLoad()) {
1461 // (conservatively) we can't peak past the ordering implied by this
1462 // operation, but we can add this load to our set of available values
1463 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1464 LastStore = nullptr;
1465 ++CurrentGeneration;
1466 }
1467
1468 if (MemInst.isInvariantLoad()) {
1469 // If we pass an invariant load, we know that memory location is
1470 // indefinitely constant from the moment of first dereferenceability.
1471 // We conservatively treat the invariant_load as that moment. If we
1472 // pass a invariant load after already establishing a scope, don't
1473 // restart it since we want to preserve the earliest point seen.
1474 auto MemLoc = MemoryLocation::get(&Inst);
1475 if (!AvailableInvariants.count(MemLoc))
1476 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1477 }
1478
1479 // If we have an available version of this load, and if it is the right
1480 // generation or the load is known to be from an invariant location,
1481 // replace this instruction.
1482 //
1483 // If either the dominating load or the current load are invariant, then
1484 // we can assume the current load loads the same value as the dominating
1485 // load.
1486 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1487 if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1488 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1489 << " to: " << *InVal.DefInst << '\n');
1490 if (!DebugCounter::shouldExecute(CSECounter)) {
1491 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1492 continue;
1493 }
1494 if (InVal.IsLoad)
1495 if (auto *I = dyn_cast<Instruction>(Op))
1496 combineMetadataForCSE(I, &Inst, false);
1497 if (!Inst.use_empty())
1498 Inst.replaceAllUsesWith(Op);
1499 salvageKnowledge(&Inst, &AC);
1500 removeMSSA(Inst);
1501 Inst.eraseFromParent();
1502 Changed = true;
1503 ++NumCSELoad;
1504 continue;
1505 }
1506
1507 // Otherwise, remember that we have this instruction.
1508 AvailableLoads.insert(MemInst.getPointerOperand(),
1509 LoadValue(&Inst, CurrentGeneration,
1510 MemInst.getMatchingId(),
1511 MemInst.isAtomic(),
1512 MemInst.isLoad()));
1513 LastStore = nullptr;
1514 continue;
1515 }
1516
1517 // If this instruction may read from memory, forget LastStore. Load/store
1518 // intrinsics will indicate both a read and a write to memory. The target
1519 // may override this (e.g. so that a store intrinsic does not read from
1520 // memory, and thus will be treated the same as a regular store for
1521 // commoning purposes).
1522 if (Inst.mayReadFromMemory() &&
1523 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1524 LastStore = nullptr;
1525
1526 // If this is a read-only or write-only call, process it. Skip store
1527 // MemInsts, as they will be more precisely handled later on. Also skip
1528 // memsets, as DSE may be able to optimize them better by removing the
1529 // earlier rather than later store.
1530 if (CallValue::canHandle(&Inst) &&
1531 (!MemInst.isValid() || !MemInst.isStore()) && !isa<MemSetInst>(&Inst)) {
1532 // If we have an available version of this call, and if it is the right
1533 // generation, replace this instruction.
1534 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1535 if (InVal.first != nullptr &&
1536 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1537 &Inst) &&
1538 InVal.first->mayReadFromMemory() == Inst.mayReadFromMemory()) {
1539 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1540 << " to: " << *InVal.first << '\n');
1541 if (!DebugCounter::shouldExecute(CSECounter)) {
1542 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1543 continue;
1544 }
1545 combineIRFlags(Inst, InVal.first);
1546 if (!Inst.use_empty())
1547 Inst.replaceAllUsesWith(InVal.first);
1548 salvageKnowledge(&Inst, &AC);
1549 removeMSSA(Inst);
1550 Inst.eraseFromParent();
1551 Changed = true;
1552 ++NumCSECall;
1553 continue;
1554 }
1555
1556 // Increase memory generation for writes. Do this before inserting
1557 // the call, so it has the generation after the write occurred.
1558 if (Inst.mayWriteToMemory())
1559 ++CurrentGeneration;
1560
1561 // Otherwise, remember that we have this instruction.
1562 AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1563 continue;
1564 }
1565
1566 // Compare GEP instructions based on offset.
1567 if (GEPValue::canHandle(&Inst)) {
1568 auto *GEP = cast<GetElementPtrInst>(&Inst);
1569 APInt Offset = APInt(SQ.DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1570 GEPValue GEPVal(GEP, GEP->accumulateConstantOffset(SQ.DL, Offset)
1571 ? Offset.trySExtValue()
1572 : std::nullopt);
1573 if (Value *V = AvailableGEPs.lookup(GEPVal)) {
1574 LLVM_DEBUG(dbgs() << "EarlyCSE CSE GEP: " << Inst << " to: " << *V
1575 << '\n');
1576 combineIRFlags(Inst, V);
1577 Inst.replaceAllUsesWith(V);
1578 salvageKnowledge(&Inst, &AC);
1579 removeMSSA(Inst);
1580 Inst.eraseFromParent();
1581 Changed = true;
1582 ++NumCSEGEP;
1583 continue;
1584 }
1585
1586 // Otherwise, just remember that we have this GEP.
1587 AvailableGEPs.insert(GEPVal, &Inst);
1588 continue;
1589 }
1590
1591 // A release fence requires that all stores complete before it, but does
1592 // not prevent the reordering of following loads 'before' the fence. As a
1593 // result, we don't need to consider it as writing to memory and don't need
1594 // to advance the generation. We do need to prevent DSE across the fence,
1595 // but that's handled above.
1596 if (auto *FI = dyn_cast<FenceInst>(&Inst))
1597 if (FI->getOrdering() == AtomicOrdering::Release) {
1598 assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1599 continue;
1600 }
1601
1602 // write back DSE - If we write back the same value we just loaded from
1603 // the same location and haven't passed any intervening writes or ordering
1604 // operations, we can remove the write. The primary benefit is in allowing
1605 // the available load table to remain valid and value forward past where
1606 // the store originally was.
1607 if (MemInst.isValid() && MemInst.isStore()) {
1608 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1609 if (InVal.DefInst &&
1610 InVal.DefInst ==
1611 getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1612 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1613 if (!DebugCounter::shouldExecute(CSECounter)) {
1614 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1615 continue;
1616 }
1617 salvageKnowledge(&Inst, &AC);
1618 removeMSSA(Inst);
1619 Inst.eraseFromParent();
1620 Changed = true;
1621 ++NumDSE;
1622 // We can avoid incrementing the generation count since we were able
1623 // to eliminate this store.
1624 continue;
1625 }
1626 }
1627
1628 // Okay, this isn't something we can CSE at all. Check to see if it is
1629 // something that could modify memory. If so, our available memory values
1630 // cannot be used so bump the generation count.
1631 if (Inst.mayWriteToMemory()) {
1632 ++CurrentGeneration;
1633
1634 if (MemInst.isValid() && MemInst.isStore()) {
1635 // We do a trivial form of DSE if there are two stores to the same
1636 // location with no intervening loads. Delete the earlier store.
1637 if (LastStore) {
1638 if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
1639 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1640 << " due to: " << Inst << '\n');
1641 if (!DebugCounter::shouldExecute(CSECounter)) {
1642 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1643 } else {
1644 salvageKnowledge(&Inst, &AC);
1645 removeMSSA(*LastStore);
1646 LastStore->eraseFromParent();
1647 Changed = true;
1648 ++NumDSE;
1649 LastStore = nullptr;
1650 }
1651 }
1652 // fallthrough - we can exploit information about this store
1653 }
1654
1655 // Okay, we just invalidated anything we knew about loaded values. Try
1656 // to salvage *something* by remembering that the stored value is a live
1657 // version of the pointer. It is safe to forward from volatile stores
1658 // to non-volatile loads, so we don't have to check for volatility of
1659 // the store.
1660 AvailableLoads.insert(MemInst.getPointerOperand(),
1661 LoadValue(&Inst, CurrentGeneration,
1662 MemInst.getMatchingId(),
1663 MemInst.isAtomic(),
1664 MemInst.isLoad()));
1665
1666 // Remember that this was the last unordered store we saw for DSE. We
1667 // don't yet handle DSE on ordered or volatile stores since we don't
1668 // have a good way to model the ordering requirement for following
1669 // passes once the store is removed. We could insert a fence, but
1670 // since fences are slightly stronger than stores in their ordering,
1671 // it's not clear this is a profitable transform. Another option would
1672 // be to merge the ordering with that of the post dominating store.
1673 if (MemInst.isUnordered() && !MemInst.isVolatile())
1674 LastStore = &Inst;
1675 else
1676 LastStore = nullptr;
1677 }
1678 }
1679 }
1680
1681 return Changed;
1682}
1683
1684bool EarlyCSE::run() {
1685 // Note, deque is being used here because there is significant performance
1686 // gains over vector when the container becomes very large due to the
1687 // specific access patterns. For more information see the mailing list
1688 // discussion on this:
1689 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1690 std::deque<StackNode *> nodesToProcess;
1691
1692 bool Changed = false;
1693
1694 // Process the root node.
1695 nodesToProcess.push_back(new StackNode(
1696 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1697 AvailableGEPs, CurrentGeneration, DT.getRootNode(),
1698 DT.getRootNode()->begin(), DT.getRootNode()->end()));
1699
1700 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1701
1702 // Process the stack.
1703 while (!nodesToProcess.empty()) {
1704 // Grab the first item off the stack. Set the current generation, remove
1705 // the node from the stack, and process it.
1706 StackNode *NodeToProcess = nodesToProcess.back();
1707
1708 // Initialize class members.
1709 CurrentGeneration = NodeToProcess->currentGeneration();
1710
1711 // Check if the node needs to be processed.
1712 if (!NodeToProcess->isProcessed()) {
1713 // Process the node.
1714 Changed |= processNode(NodeToProcess->node());
1715 NodeToProcess->childGeneration(CurrentGeneration);
1716 NodeToProcess->process();
1717 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1718 // Push the next child onto the stack.
1719 DomTreeNode *child = NodeToProcess->nextChild();
1720 nodesToProcess.push_back(new StackNode(
1721 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1722 AvailableGEPs, NodeToProcess->childGeneration(), child,
1723 child->begin(), child->end()));
1724 } else {
1725 // It has been processed, and there are no more children to process,
1726 // so delete it and pop it off the stack.
1727 delete NodeToProcess;
1728 nodesToProcess.pop_back();
1729 }
1730 } // while (!nodes...)
1731
1732 return Changed;
1733}
1734
1737 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1738 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1739 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1740 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1741 auto *MSSA =
1742 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1743
1744 EarlyCSE CSE(F.getDataLayout(), TLI, TTI, DT, AC, MSSA);
1745
1746 if (!CSE.run())
1747 return PreservedAnalyses::all();
1748
1751 if (UseMemorySSA)
1753 return PA;
1754}
1755
1757 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1758 static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
1759 OS, MapClassName2PassName);
1760 OS << '<';
1761 if (UseMemorySSA)
1762 OS << "memssa";
1763 OS << '>';
1764}
1765
1766namespace {
1767
1768/// A simple and fast domtree-based CSE pass.
1769///
1770/// This pass does a simple depth-first walk over the dominator tree,
1771/// eliminating trivially redundant instructions and using instsimplify to
1772/// canonicalize things as it goes. It is intended to be fast and catch obvious
1773/// cases so that instcombine and other passes are more effective. It is
1774/// expected that a later pass of GVN will catch the interesting/hard cases.
1775template<bool UseMemorySSA>
1776class EarlyCSELegacyCommonPass : public FunctionPass {
1777public:
1778 static char ID;
1779
1780 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1781 if (UseMemorySSA)
1783 else
1785 }
1786
1787 bool runOnFunction(Function &F) override {
1788 if (skipFunction(F))
1789 return false;
1790
1791 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1792 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1793 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1794 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1795 auto *MSSA =
1796 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1797
1798 EarlyCSE CSE(F.getDataLayout(), TLI, TTI, DT, AC, MSSA);
1799
1800 return CSE.run();
1801 }
1802
1803 void getAnalysisUsage(AnalysisUsage &AU) const override {
1804 AU.addRequired<AssumptionCacheTracker>();
1805 AU.addRequired<DominatorTreeWrapperPass>();
1806 AU.addRequired<TargetLibraryInfoWrapperPass>();
1807 AU.addRequired<TargetTransformInfoWrapperPass>();
1808 if (UseMemorySSA) {
1809 AU.addRequired<AAResultsWrapperPass>();
1810 AU.addRequired<MemorySSAWrapperPass>();
1811 AU.addPreserved<MemorySSAWrapperPass>();
1812 }
1813 AU.addPreserved<GlobalsAAWrapperPass>();
1814 AU.addPreserved<AAResultsWrapperPass>();
1815 AU.setPreservesCFG();
1816 }
1817};
1818
1819} // end anonymous namespace
1820
1821using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1822
1823template<>
1824char EarlyCSELegacyPass::ID = 0;
1825
1826INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1827 false)
1832INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1833
1834using EarlyCSEMemSSALegacyPass =
1835 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1836
1837template<>
1838char EarlyCSEMemSSALegacyPass::ID = 0;
1839
1841 if (UseMemorySSA)
1842 return new EarlyCSEMemSSALegacyPass();
1843 else
1844 return new EarlyCSELegacyPass();
1845}
1846
1847INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1848 "Early CSE w/ MemorySSA", false, false)
1855INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1856 "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:857
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
const SmallVectorImpl< MachineOperand > & Cond
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:278
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:314
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:922
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:1035
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:975
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:720
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:553
bool use_empty() const
Definition Value.h:348
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
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
Changed
#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:1677
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 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:406
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
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:3117
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
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