LLVM 24.0.0git
DeadStoreElimination.cpp
Go to the documentation of this file.
1//===- DeadStoreElimination.cpp - MemorySSA Backed Dead Store Elimination -===//
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// The code below implements dead store elimination using MemorySSA. It uses
10// the following general approach: given a MemoryDef, walk upwards to find
11// clobbering MemoryDefs that may be killed by the starting def. Then check
12// that there are no uses that may read the location of the original MemoryDef
13// in between both MemoryDefs. A bit more concretely:
14//
15// For all MemoryDefs StartDef:
16// 1. Get the next dominating clobbering MemoryDef (MaybeDeadAccess) by walking
17// upwards.
18// 2. Check that there are no reads between MaybeDeadAccess and the StartDef by
19// checking all uses starting at MaybeDeadAccess and walking until we see
20// StartDef.
21// 3. For each found CurrentDef, check that:
22// 1. There are no barrier instructions between CurrentDef and StartDef (like
23// throws or stores with ordering constraints).
24// 2. StartDef is executed whenever CurrentDef is executed.
25// 3. StartDef completely overwrites CurrentDef.
26// 4. Erase CurrentDef from the function and MemorySSA.
27//
28//===----------------------------------------------------------------------===//
29
31#include "ScalarOptions.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SetVector.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/StringRef.h"
48#include "llvm/Analysis/Loads.h"
57#include "llvm/IR/Argument.h"
59#include "llvm/IR/BasicBlock.h"
60#include "llvm/IR/Constant.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DataLayout.h"
64#include "llvm/IR/DebugInfo.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/IRBuilder.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
73#include "llvm/IR/Module.h"
74#include "llvm/IR/PassManager.h"
76#include "llvm/IR/Value.h"
79#include "llvm/Support/Debug.h"
87#include <algorithm>
88#include <cassert>
89#include <cstdint>
90#include <map>
91#include <optional>
92#include <utility>
93
94using namespace llvm;
95using namespace PatternMatch;
96
97#define DEBUG_TYPE "dse"
98
99STATISTIC(NumRemainingStores, "Number of stores remaining after DSE");
100STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
101STATISTIC(NumFastStores, "Number of stores deleted");
102STATISTIC(NumFastOther, "Number of other instrs removed");
103STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
104STATISTIC(NumModifiedStores, "Number of stores modified");
105STATISTIC(NumCFGChecks, "Number of stores modified");
106STATISTIC(NumCFGTries, "Number of stores modified");
107STATISTIC(NumCFGSuccess, "Number of stores modified");
108STATISTIC(NumGetDomMemoryDefPassed,
109 "Number of times a valid candidate is returned from getDomMemoryDef");
110STATISTIC(NumDomMemDefChecks,
111 "Number iterations check for reads in getDomMemoryDef");
112
113DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa",
114 "Controls which MemoryDefs are eliminated.");
115
116//===----------------------------------------------------------------------===//
117// Helper functions
118//===----------------------------------------------------------------------===//
119using OverlapIntervalsTy = std::map<int64_t, int64_t>;
121
122/// Returns true if the end of this instruction can be safely shortened in
123/// length.
125 // Don't shorten stores for now
126 if (isa<StoreInst>(I))
127 return false;
128
130 switch (II->getIntrinsicID()) {
131 default: return false;
132 case Intrinsic::memset:
133 case Intrinsic::memcpy:
134 case Intrinsic::memcpy_element_unordered_atomic:
135 case Intrinsic::memset_element_unordered_atomic:
136 // Do shorten memory intrinsics.
137 // FIXME: Add memmove if it's also safe to transform.
138 return true;
139 }
140 }
141
142 // Don't shorten libcalls calls for now.
143
144 return false;
145}
146
147/// Returns true if the beginning of this instruction can be safely shortened
148/// in length.
150 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
151 // easily done by offsetting the source address.
152 return isa<AnyMemSetInst>(I);
153}
154
155static std::optional<TypeSize> getPointerSize(const Value *V,
156 const DataLayout &DL,
157 const TargetLibraryInfo &TLI,
158 const Function *F) {
160 ObjectSizeOpts Opts;
162
163 if (getObjectSize(V, Size, DL, &TLI, Opts))
164 return TypeSize::getFixed(Size);
165 return std::nullopt;
166}
167
168namespace {
169
170enum OverwriteResult {
171 OW_Begin,
172 OW_Complete,
173 OW_End,
174 OW_PartialEarlierWithFullLater,
175 OW_MaybePartial,
176 OW_None,
177 OW_Unknown
178};
179
180} // end anonymous namespace
181
182/// Check if two instruction are masked stores that completely
183/// overwrite one another. More specifically, \p KillingI has to
184/// overwrite \p DeadI.
185static OverwriteResult isMaskedStoreOverwrite(const Instruction *KillingI,
186 const Instruction *DeadI,
188 const auto *KillingII = dyn_cast<IntrinsicInst>(KillingI);
189 const auto *DeadII = dyn_cast<IntrinsicInst>(DeadI);
190 if (KillingII == nullptr || DeadII == nullptr)
191 return OW_Unknown;
192 if (KillingII->getIntrinsicID() != DeadII->getIntrinsicID())
193 return OW_Unknown;
194
195 switch (KillingII->getIntrinsicID()) {
196 case Intrinsic::masked_store:
197 case Intrinsic::vp_store: {
198 const DataLayout &DL = KillingII->getDataLayout();
199 auto *KillingTy = KillingII->getArgOperand(0)->getType();
200 auto *DeadTy = DeadII->getArgOperand(0)->getType();
201 if (DL.getTypeSizeInBits(KillingTy) != DL.getTypeSizeInBits(DeadTy))
202 return OW_Unknown;
203 // Element count.
204 if (cast<VectorType>(KillingTy)->getElementCount() !=
205 cast<VectorType>(DeadTy)->getElementCount())
206 return OW_Unknown;
207 // Pointers.
208 Value *KillingPtr = KillingII->getArgOperand(1);
209 Value *DeadPtr = DeadII->getArgOperand(1);
210 if (KillingPtr != DeadPtr && !AA.isMustAlias(KillingPtr, DeadPtr))
211 return OW_Unknown;
212 if (KillingII->getIntrinsicID() == Intrinsic::masked_store) {
213 // Masks.
214 // TODO: check that KillingII's mask is a superset of the DeadII's mask.
215 if (KillingII->getArgOperand(2) != DeadII->getArgOperand(2))
216 return OW_Unknown;
217 } else if (KillingII->getIntrinsicID() == Intrinsic::vp_store) {
218 // Masks.
219 // TODO: check that KillingII's mask is a superset of the DeadII's mask.
220 if (KillingII->getArgOperand(2) != DeadII->getArgOperand(2))
221 return OW_Unknown;
222 // Lengths.
223 if (KillingII->getArgOperand(3) != DeadII->getArgOperand(3))
224 return OW_Unknown;
225 }
226 return OW_Complete;
227 }
228 default:
229 return OW_Unknown;
230 }
231}
232
233/// Return 'OW_Complete' if a store to the 'KillingLoc' location completely
234/// overwrites a store to the 'DeadLoc' location, 'OW_End' if the end of the
235/// 'DeadLoc' location is completely overwritten by 'KillingLoc', 'OW_Begin'
236/// if the beginning of the 'DeadLoc' location is overwritten by 'KillingLoc'.
237/// 'OW_PartialEarlierWithFullLater' means that a dead (big) store was
238/// overwritten by a killing (smaller) store which doesn't write outside the big
239/// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
240/// NOTE: This function must only be called if both \p KillingLoc and \p
241/// DeadLoc belong to the same underlying object with valid \p KillingOff and
242/// \p DeadOff.
243static OverwriteResult isPartialOverwrite(const ScalarOptions &Opts,
244 const MemoryLocation &KillingLoc,
245 const MemoryLocation &DeadLoc,
246 int64_t KillingOff, int64_t DeadOff,
247 Instruction *DeadI,
249 const uint64_t KillingSize = KillingLoc.Size.getValue();
250 const uint64_t DeadSize = DeadLoc.Size.getValue();
251 // We may now overlap, although the overlap is not complete. There might also
252 // be other incomplete overlaps, and together, they might cover the complete
253 // dead store.
254 // Note: The correctness of this logic depends on the fact that this function
255 // is not even called providing DepWrite when there are any intervening reads.
256 if (Opts.enable_dse_partial_overwrite_tracking &&
257 KillingOff < int64_t(DeadOff + DeadSize) &&
258 int64_t(KillingOff + KillingSize) >= DeadOff) {
259
260 // Insert our part of the overlap into the map.
261 auto &IM = IOL[DeadI];
262 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: DeadLoc [" << DeadOff << ", "
263 << int64_t(DeadOff + DeadSize) << ") KillingLoc ["
264 << KillingOff << ", " << int64_t(KillingOff + KillingSize)
265 << ")\n");
266
267 // Make sure that we only insert non-overlapping intervals and combine
268 // adjacent intervals. The intervals are stored in the map with the ending
269 // offset as the key (in the half-open sense) and the starting offset as
270 // the value.
271 int64_t KillingIntStart = KillingOff;
272 int64_t KillingIntEnd = KillingOff + KillingSize;
273
274 // Find any intervals ending at, or after, KillingIntStart which start
275 // before KillingIntEnd.
276 auto ILI = IM.lower_bound(KillingIntStart);
277 if (ILI != IM.end() && ILI->second <= KillingIntEnd) {
278 // This existing interval is overlapped with the current store somewhere
279 // in [KillingIntStart, KillingIntEnd]. Merge them by erasing the existing
280 // intervals and adjusting our start and end.
281 KillingIntStart = std::min(KillingIntStart, ILI->second);
282 KillingIntEnd = std::max(KillingIntEnd, ILI->first);
283 ILI = IM.erase(ILI);
284
285 // Continue erasing and adjusting our end in case other previous
286 // intervals are also overlapped with the current store.
287 //
288 // |--- dead 1 ---| |--- dead 2 ---|
289 // |------- killing---------|
290 //
291 while (ILI != IM.end() && ILI->second <= KillingIntEnd) {
292 assert(ILI->second > KillingIntStart && "Unexpected interval");
293 KillingIntEnd = std::max(KillingIntEnd, ILI->first);
294 ILI = IM.erase(ILI);
295 }
296 }
297
298 IM[KillingIntEnd] = KillingIntStart;
299
300 ILI = IM.begin();
301 if (ILI->second <= DeadOff && ILI->first >= int64_t(DeadOff + DeadSize)) {
302 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: DeadLoc ["
303 << DeadOff << ", " << int64_t(DeadOff + DeadSize)
304 << ") Composite KillingLoc [" << ILI->second << ", "
305 << ILI->first << ")\n");
306 ++NumCompletePartials;
307 return OW_Complete;
308 }
309 }
310
311 // Check for a dead store which writes to all the memory locations that
312 // the killing store writes to.
313 if (Opts.enable_dse_partial_store_merging && KillingOff >= DeadOff &&
314 int64_t(DeadOff + DeadSize) > KillingOff &&
315 uint64_t(KillingOff - DeadOff) + KillingSize <= DeadSize) {
316 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite a dead load [" << DeadOff
317 << ", " << int64_t(DeadOff + DeadSize)
318 << ") by a killing store [" << KillingOff << ", "
319 << int64_t(KillingOff + KillingSize) << ")\n");
320 // TODO: Maybe come up with a better name?
321 return OW_PartialEarlierWithFullLater;
322 }
323
324 // Another interesting case is if the killing store overwrites the end of the
325 // dead store.
326 //
327 // |--dead--|
328 // |-- killing --|
329 //
330 // In this case we may want to trim the size of dead store to avoid
331 // generating stores to addresses which will definitely be overwritten killing
332 // store.
333 if (!Opts.enable_dse_partial_overwrite_tracking &&
334 (KillingOff > DeadOff && KillingOff < int64_t(DeadOff + DeadSize) &&
335 int64_t(KillingOff + KillingSize) >= int64_t(DeadOff + DeadSize)))
336 return OW_End;
337
338 // Finally, we also need to check if the killing store overwrites the
339 // beginning of the dead store.
340 //
341 // |--dead--|
342 // |-- killing --|
343 //
344 // In this case we may want to move the destination address and trim the size
345 // of dead store to avoid generating stores to addresses which will definitely
346 // be overwritten killing store.
347 if (!Opts.enable_dse_partial_overwrite_tracking &&
348 (KillingOff <= DeadOff && int64_t(KillingOff + KillingSize) > DeadOff)) {
349 assert(int64_t(KillingOff + KillingSize) < int64_t(DeadOff + DeadSize) &&
350 "Expect to be handled as OW_Complete");
351 return OW_Begin;
352 }
353 // Otherwise, they don't completely overlap.
354 return OW_Unknown;
355}
356
357/// Returns true if the memory which is accessed by the second instruction is not
358/// modified between the first and the second instruction.
359/// Precondition: Second instruction must be dominated by the first
360/// instruction.
361static bool
364 DominatorTree *DT) {
365 // Do a backwards scan through the CFG from SecondI to FirstI. Look for
366 // instructions which can modify the memory location accessed by SecondI.
367 //
368 // While doing the walk keep track of the address to check. It might be
369 // different in different basic blocks due to PHI translation.
370 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>;
372 // Keep track of the address we visited each block with. Bail out if we
373 // visit a block with different addresses.
375
376 BasicBlock::iterator FirstBBI(FirstI);
377 ++FirstBBI;
378 BasicBlock::iterator SecondBBI(SecondI);
379 BasicBlock *FirstBB = FirstI->getParent();
380 BasicBlock *SecondBB = SecondI->getParent();
381 MemoryLocation MemLoc;
382 if (auto *MemSet = dyn_cast<MemSetInst>(SecondI))
383 MemLoc = MemoryLocation::getForDest(MemSet);
384 else
385 MemLoc = MemoryLocation::get(SecondI);
386
387 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr);
388
389 // Start checking the SecondBB.
390 WorkList.push_back(
391 std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr)));
392 bool isFirstBlock = true;
393
394 // Check all blocks going backward until we reach the FirstBB.
395 while (!WorkList.empty()) {
396 BlockAddressPair Current = WorkList.pop_back_val();
397 BasicBlock *B = Current.first;
398 PHITransAddr &Addr = Current.second;
399 Value *Ptr = Addr.getAddr();
400
401 // Ignore instructions before FirstI if this is the FirstBB.
402 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
403
405 if (isFirstBlock) {
406 // Ignore instructions after SecondI if this is the first visit of SecondBB.
407 assert(B == SecondBB && "first block is not the store block");
408 EI = SecondBBI;
409 isFirstBlock = false;
410 } else {
411 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
412 // In this case we also have to look at instructions after SecondI.
413 EI = B->end();
414 }
415 for (; BI != EI; ++BI) {
416 Instruction *I = &*BI;
417 if (I->mayWriteToMemory() && I != SecondI)
418 if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr))))
419 return false;
420 }
421 if (B != FirstBB) {
422 assert(B != &FirstBB->getParent()->getEntryBlock() &&
423 "Should not hit the entry block because SI must be dominated by LI");
424 for (BasicBlock *Pred : predecessors(B)) {
425 PHITransAddr PredAddr = Addr;
426 if (PredAddr.needsPHITranslationFromBlock(B)) {
427 if (!PredAddr.isPotentiallyPHITranslatable())
428 return false;
429 if (!PredAddr.translateValue(B, Pred, DT, false))
430 return false;
431 }
432 Value *TranslatedPtr = PredAddr.getAddr();
433 auto Inserted = Visited.insert(std::make_pair(Pred, TranslatedPtr));
434 if (!Inserted.second) {
435 // We already visited this block before. If it was with a different
436 // address - bail out!
437 if (TranslatedPtr != Inserted.first->second)
438 return false;
439 // ... otherwise just skip it.
440 continue;
441 }
442 WorkList.push_back(std::make_pair(Pred, PredAddr));
443 }
444 }
445 }
446 return true;
447}
448
449static void shortenAssignment(Instruction *Inst, Value *OriginalDest,
450 uint64_t OldSizeInBits, uint64_t NewSizeInBits,
451 bool IsOverwriteEnd) {
452 const DataLayout &DL = Inst->getDataLayout();
453 uint64_t DeadSliceSizeInBits = OldSizeInBits - NewSizeInBits;
454 // The dead slice offset is relative to OriginalDest, the slice start we hand
455 // calculateFragmentIntersect. Shortening the end keeps the front of the
456 // store, so the dead bits start where the new store ends; shortening the
457 // beginning kills the bits at OriginalDest itself. Don't add OriginalDest's
458 // offset from its base object here. calculateFragmentIntersect already
459 // measures that pointer against the marker's address.
460 uint64_t DeadSliceOffsetInBits = IsOverwriteEnd ? NewSizeInBits : 0;
461 auto SetDeadFragExpr = [](auto *Assign,
462 DIExpression::FragmentInfo DeadFragment) {
463 // createFragmentExpression expects an offset relative to the existing
464 // fragment offset if there is one.
465 uint64_t RelativeOffset = DeadFragment.OffsetInBits -
466 Assign->getExpression()
467 ->getFragmentInfo()
468 .value_or(DIExpression::FragmentInfo(0, 0))
469 .OffsetInBits;
471 Assign->getExpression(), RelativeOffset, DeadFragment.SizeInBits)) {
472 Assign->setExpression(*NewExpr);
473 return;
474 }
475 // Failed to create a fragment expression for this so discard the value,
476 // making this a kill location.
478 DIExpression::get(Assign->getContext(), {}), DeadFragment.OffsetInBits,
479 DeadFragment.SizeInBits);
480 Assign->setExpression(Expr);
481 Assign->setKillLocation();
482 };
483
484 // A DIAssignID to use so that the inserted dbg.assign intrinsics do not
485 // link to any instructions. Created in the loop below (once).
486 DIAssignID *LinkToNothing = nullptr;
487 LLVMContext &Ctx = Inst->getContext();
488 auto GetDeadLink = [&Ctx, &LinkToNothing]() {
489 if (!LinkToNothing)
490 LinkToNothing = DIAssignID::getDistinct(Ctx);
491 return LinkToNothing;
492 };
493
494 // Insert an unlinked dbg.assign intrinsic for the dead fragment after each
495 // overlapping dbg.assign intrinsic.
496 for (DbgVariableRecord *Assign : at::getDVRAssignmentMarkers(Inst)) {
497 std::optional<DIExpression::FragmentInfo> NewFragment;
498 if (!at::calculateFragmentIntersect(DL, OriginalDest, DeadSliceOffsetInBits,
499 DeadSliceSizeInBits, Assign,
500 NewFragment) ||
501 !NewFragment) {
502 // Either the intersection couldn't be worked out, or it covers the
503 // entire variable region described by the record. Full coverage leaves
504 // NewFragment empty rather than making calculateFragmentIntersect fail,
505 // so unlink the whole assignment from the store in both cases.
506 Assign->setKillAddress();
507 Assign->setAssignId(GetDeadLink());
508 continue;
509 }
510 // No intersect.
511 if (NewFragment->SizeInBits == 0)
512 continue;
513
514 // Fragments overlap: insert a new dbg.assign for this dead part.
515 auto *NewAssign = static_cast<decltype(Assign)>(Assign->clone());
516 NewAssign->insertAfter(Assign->getIterator());
517 NewAssign->setAssignId(GetDeadLink());
518 if (NewFragment)
519 SetDeadFragExpr(NewAssign, *NewFragment);
520 NewAssign->setKillAddress();
521 }
522}
523
524/// Update the attributes given that a memory access is updated (the
525/// dereferenced pointer could be moved forward when shortening a
526/// mem intrinsic).
527static void adjustArgAttributes(AnyMemIntrinsic *Intrinsic, unsigned ArgNo,
528 uint64_t PtrOffset) {
529 // Remember old attributes.
530 AttributeSet OldAttrs = Intrinsic->getParamAttributes(ArgNo);
531
532 // Find attributes that should be kept, and remove the rest.
533 AttributeMask AttrsToRemove;
534 for (auto &Attr : OldAttrs) {
535 if (Attr.hasKindAsEnum()) {
536 switch (Attr.getKindAsEnum()) {
537 default:
538 break;
539 case Attribute::Alignment:
540 // Only keep alignment if PtrOffset satisfy the alignment.
541 if (isAligned(Attr.getAlignment().valueOrOne(), PtrOffset))
542 continue;
543 break;
544 case Attribute::Dereferenceable:
545 case Attribute::DereferenceableOrNull:
546 // We could reduce the size of these attributes according to
547 // PtrOffset. But we simply drop these for now.
548 break;
549 case Attribute::NonNull:
550 case Attribute::NoUndef:
551 continue;
552 }
553 }
554 AttrsToRemove.addAttribute(Attr);
555 }
556
557 // Remove the attributes that should be dropped.
558 Intrinsic->removeParamAttrs(ArgNo, AttrsToRemove);
559}
560
561static bool tryToShorten(Instruction *DeadI, int64_t &DeadStart,
562 uint64_t &DeadSize, int64_t KillingStart,
563 uint64_t KillingSize, bool IsOverwriteEnd) {
564 auto *DeadIntrinsic = cast<AnyMemIntrinsic>(DeadI);
565 Align PrefAlign = DeadIntrinsic->getDestAlign().valueOrOne();
566
567 // We assume that memet/memcpy operates in chunks of the "largest" native
568 // type size and aligned on the same value. That means optimal start and size
569 // of memset/memcpy should be modulo of preferred alignment of that type. That
570 // is it there is no any sense in trying to reduce store size any further
571 // since any "extra" stores comes for free anyway.
572 // On the other hand, maximum alignment we can achieve is limited by alignment
573 // of initial store.
574
575 // TODO: Limit maximum alignment by preferred (or abi?) alignment of the
576 // "largest" native type.
577 // Note: What is the proper way to get that value?
578 // Should TargetTransformInfo::getRegisterBitWidth be used or anything else?
579 // PrefAlign = std::min(DL.getPrefTypeAlign(LargestType), PrefAlign);
580
581 int64_t ToRemoveStart = 0;
582 uint64_t ToRemoveSize = 0;
583 // Compute start and size of the region to remove. Make sure 'PrefAlign' is
584 // maintained on the remaining store.
585 if (IsOverwriteEnd) {
586 // Calculate required adjustment for 'KillingStart' in order to keep
587 // remaining store size aligned on 'PerfAlign'.
588 uint64_t Off =
589 offsetToAlignment(uint64_t(KillingStart - DeadStart), PrefAlign);
590 ToRemoveStart = KillingStart + Off;
591 if (DeadSize <= uint64_t(ToRemoveStart - DeadStart))
592 return false;
593 ToRemoveSize = DeadSize - uint64_t(ToRemoveStart - DeadStart);
594 } else {
595 ToRemoveStart = DeadStart;
596 assert(KillingSize >= uint64_t(DeadStart - KillingStart) &&
597 "Not overlapping accesses?");
598 ToRemoveSize = KillingSize - uint64_t(DeadStart - KillingStart);
599 // Calculate required adjustment for 'ToRemoveSize'in order to keep
600 // start of the remaining store aligned on 'PerfAlign'.
601 uint64_t Off = offsetToAlignment(ToRemoveSize, PrefAlign);
602 if (Off != 0) {
603 if (ToRemoveSize <= (PrefAlign.value() - Off))
604 return false;
605 ToRemoveSize -= PrefAlign.value() - Off;
606 }
607 assert(isAligned(PrefAlign, ToRemoveSize) &&
608 "Should preserve selected alignment");
609 }
610
611 assert(ToRemoveSize > 0 && "Shouldn't reach here if nothing to remove");
612 assert(DeadSize > ToRemoveSize && "Can't remove more than original size");
613
614 uint64_t NewSize = DeadSize - ToRemoveSize;
615 if (DeadIntrinsic->isAtomic()) {
616 // When shortening an atomic memory intrinsic, the newly shortened
617 // length must remain an integer multiple of the element size.
618 const uint32_t ElementSize = DeadIntrinsic->getElementSizeInBytes();
619 if (0 != NewSize % ElementSize)
620 return false;
621 }
622
623 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
624 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *DeadI
625 << "\n KILLER [" << ToRemoveStart << ", "
626 << int64_t(ToRemoveStart + ToRemoveSize) << ")\n");
627
628 DeadIntrinsic->setLength(NewSize);
629 DeadIntrinsic->setDestAlignment(PrefAlign);
630
631 Value *OrigDest = DeadIntrinsic->getRawDest();
632 if (!IsOverwriteEnd) {
633 Value *Indices[1] = {
634 ConstantInt::get(DeadIntrinsic->getLength()->getType(), ToRemoveSize)};
636 Type::getInt8Ty(DeadIntrinsic->getContext()), OrigDest, Indices, "",
637 DeadI->getIterator());
638 NewDestGEP->setDebugLoc(DeadIntrinsic->getDebugLoc());
639 DeadIntrinsic->setDest(NewDestGEP);
640 adjustArgAttributes(DeadIntrinsic, 0, ToRemoveSize);
641 }
642
643 // Update attached dbg.assign intrinsics. Assume 8-bit byte.
644 shortenAssignment(DeadI, OrigDest, DeadSize * 8, NewSize * 8, IsOverwriteEnd);
645
646 // Finally update start and size of dead access.
647 if (!IsOverwriteEnd)
648 DeadStart += ToRemoveSize;
649 DeadSize = NewSize;
650
651 return true;
652}
653
655 int64_t &DeadStart, uint64_t &DeadSize) {
656 if (IntervalMap.empty() || !isShortenableAtTheEnd(DeadI))
657 return false;
658
659 OverlapIntervalsTy::iterator OII = --IntervalMap.end();
660 int64_t KillingStart = OII->second;
661 uint64_t KillingSize = OII->first - KillingStart;
662
663 assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
664
665 if (KillingStart > DeadStart &&
666 // Note: "KillingStart - KillingStart" is known to be positive due to
667 // preceding check.
668 (uint64_t)(KillingStart - DeadStart) < DeadSize &&
669 // Note: "DeadSize - (uint64_t)(KillingStart - DeadStart)" is known to
670 // be non negative due to preceding checks.
671 KillingSize >= DeadSize - (uint64_t)(KillingStart - DeadStart)) {
672 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
673 true)) {
674 IntervalMap.erase(OII);
675 return true;
676 }
677 }
678 return false;
679}
680
683 int64_t &DeadStart, uint64_t &DeadSize) {
685 return false;
686
687 OverlapIntervalsTy::iterator OII = IntervalMap.begin();
688 int64_t KillingStart = OII->second;
689 uint64_t KillingSize = OII->first - KillingStart;
690
691 assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
692
693 if (KillingStart <= DeadStart &&
694 // Note: "DeadStart - KillingStart" is known to be non negative due to
695 // preceding check.
696 KillingSize > (uint64_t)(DeadStart - KillingStart)) {
697 // Note: "KillingSize - (uint64_t)(DeadStart - DeadStart)" is known to
698 // be positive due to preceding checks.
699 assert(KillingSize - (uint64_t)(DeadStart - KillingStart) < DeadSize &&
700 "Should have been handled as OW_Complete");
701 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
702 false)) {
703 IntervalMap.erase(OII);
704 return true;
705 }
706 }
707 return false;
708}
709
710static Constant *
712 int64_t KillingOffset, int64_t DeadOffset,
714 DominatorTree *DT) {
715 assert(KillingI);
716 assert(DeadI);
717
718 // If the store we find is:
719 // a) partially overwritten by the store to 'Loc'
720 // b) the killing store is fully contained in the dead one and
721 // c) they both have a constant value
722 // d) none of the two stores need padding
723 // Merge the two stores, replacing the dead store's value with a
724 // merge of both values.
725 //
726 // TODO: Deal with other constant types (vectors, etc), and probably
727 // some mem intrinsics (if needed)
728 if (!isa<ConstantInt>(DeadI->getValueOperand()) ||
729 !DL.typeSizeEqualsStoreSize(DeadI->getValueOperand()->getType()) ||
730 !isa<ConstantInt>(KillingI->getValueOperand()) ||
731 !DL.typeSizeEqualsStoreSize(KillingI->getValueOperand()->getType()) ||
732 !memoryIsNotModifiedBetween(DeadI, KillingI, AA, DL, DT))
733 return nullptr;
734
735 // The merge erases KillingI and writes its bytes via DeadI. For that to be
736 // safe:
737 // - KillingI must be deletable (not volatile, ordering at most unordered),
738 // - DeadI must be safe to rewrite, and
739 // - their orderings must match, so the bytes originally written by
740 // KillingI keep the same atomicity after they are folded into DeadI.
741 // This allows merging two simple stores or two unordered-atomic stores with
742 // matching ordering, while leaving volatile and ordered-atomic stores in
743 // place.
744 if (!KillingI->isUnordered() || !DeadI->isUnordered() ||
745 KillingI->getOrdering() != DeadI->getOrdering())
746 return nullptr;
747
748 APInt DeadValue = cast<ConstantInt>(DeadI->getValueOperand())->getValue();
749 APInt KillingValue =
750 cast<ConstantInt>(KillingI->getValueOperand())->getValue();
751 unsigned KillingBits = KillingValue.getBitWidth();
752 assert(DeadValue.getBitWidth() > KillingValue.getBitWidth());
753 KillingValue = KillingValue.zext(DeadValue.getBitWidth());
754
755 // Offset of the smaller store inside the larger store
756 unsigned BitOffsetDiff = (KillingOffset - DeadOffset) * 8;
757 unsigned LShiftAmount =
758 DL.isBigEndian() ? DeadValue.getBitWidth() - BitOffsetDiff - KillingBits
759 : BitOffsetDiff;
760 APInt Mask = APInt::getBitsSet(DeadValue.getBitWidth(), LShiftAmount,
761 LShiftAmount + KillingBits);
762 // Clear the bits we'll be replacing, then OR with the smaller
763 // store, shifted appropriately.
764 APInt Merged = (DeadValue & ~Mask) | (KillingValue << LShiftAmount);
765 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Dead: " << *DeadI
766 << "\n Killing: " << *KillingI
767 << "\n Merged Value: " << Merged << '\n');
768 return ConstantInt::get(DeadI->getValueOperand()->getType(), Merged);
769}
770
771// Returns true if \p I is an intrinsic that does not read or write memory.
774 switch (II->getIntrinsicID()) {
775 case Intrinsic::lifetime_start:
776 case Intrinsic::lifetime_end:
777 case Intrinsic::invariant_end:
778 case Intrinsic::launder_invariant_group:
779 case Intrinsic::assume:
780 return true;
781 default:
782 return false;
783 }
784 }
785 return false;
786}
787
788// Check if we can ignore \p D for DSE.
789static bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) {
790 Instruction *DI = D->getMemoryInst();
791 // Calls that only access inaccessible memory cannot read or write any memory
792 // locations we consider for elimination.
793 if (auto *CB = dyn_cast<CallBase>(DI))
794 if (CB->onlyAccessesInaccessibleMemory())
795 return true;
796
797 // We can eliminate stores to locations not visible to the caller across
798 // throwing instructions.
799 if (DI->mayThrow() && !DefVisibleToCaller)
800 return true;
801
802 // We can remove the dead stores, irrespective of the fence and its ordering
803 // (release/acquire/seq_cst). Fences only constraints the ordering of
804 // already visible stores, it does not make a store visible to other
805 // threads. So, skipping over a fence does not change a store from being
806 // dead.
807 if (isa<FenceInst>(DI))
808 return true;
809
810 // Skip intrinsics that do not really read or modify memory.
811 if (isNoopIntrinsic(DI))
812 return true;
813
814 return false;
815}
816
817namespace {
818
819// A memory location wrapper that represents a MemoryLocation, `MemLoc`,
820// defined by `MemDef`.
821struct MemoryLocationWrapper {
822 MemoryLocationWrapper(MemoryLocation MemLoc, MemoryDef *MemDef,
823 bool DefByInitializesAttr)
824 : MemLoc(MemLoc), MemDef(MemDef),
825 DefByInitializesAttr(DefByInitializesAttr) {
826 assert(MemLoc.Ptr && "MemLoc should be not null");
827 UnderlyingObject = getUnderlyingObject(MemLoc.Ptr);
828 DefInst = MemDef->getMemoryInst();
829 }
830
831 MemoryLocation MemLoc;
832 const Value *UnderlyingObject;
833 MemoryDef *MemDef;
834 Instruction *DefInst;
835 bool DefByInitializesAttr = false;
836};
837
838// A memory def wrapper that represents a MemoryDef and the MemoryLocation(s)
839// defined by this MemoryDef.
840struct MemoryDefWrapper {
841 MemoryDefWrapper(MemoryDef *MemDef,
842 ArrayRef<std::pair<MemoryLocation, bool>> MemLocations) {
843 DefInst = MemDef->getMemoryInst();
844 for (auto &[MemLoc, DefByInitializesAttr] : MemLocations)
845 DefinedLocations.push_back(
846 MemoryLocationWrapper(MemLoc, MemDef, DefByInitializesAttr));
847 }
848 Instruction *DefInst;
850};
851
852struct ArgumentInitInfo {
853 unsigned Idx;
854 bool IsDeadOrInvisibleOnUnwind;
855 ConstantRangeList Inits;
856};
857} // namespace
858
861 return CB && CB->getArgOperandWithAttribute(Attribute::Initializes);
862}
863
864// Return the intersected range list of the initializes attributes of "Args".
865// "Args" are call arguments that alias to each other.
866// If any argument in "Args" doesn't have dead_on_unwind attr and
867// "CallHasNoUnwindAttr" is false, return empty.
870 bool CallHasNoUnwindAttr) {
871 if (Args.empty())
872 return {};
873
874 // To address unwind, the function should have nounwind attribute or the
875 // arguments have dead or invisible on unwind. Otherwise, return empty.
876 for (const auto &Arg : Args) {
877 if (!CallHasNoUnwindAttr && !Arg.IsDeadOrInvisibleOnUnwind)
878 return {};
879 if (Arg.Inits.empty())
880 return {};
881 }
882
883 ConstantRangeList IntersectedIntervals = Args.front().Inits;
884 for (auto &Arg : Args.drop_front())
885 IntersectedIntervals = IntersectedIntervals.intersectWith(Arg.Inits);
886
887 return IntersectedIntervals;
888}
889
890namespace {
891
892struct DSEState {
893 const ScalarOptions &Opts;
894 Function &F;
895 AliasAnalysis &AA;
896 EarliestEscapeAnalysis EA;
897
898 /// The single BatchAA instance that is used to cache AA queries. It will
899 /// not be invalidated over the whole run. This is safe, because:
900 /// 1. Only memory writes are removed, so the alias cache for memory
901 /// locations remains valid.
902 /// 2. No new instructions are added (only instructions removed), so cached
903 /// information for a deleted value cannot be accessed by a re-used new
904 /// value pointer.
905 BatchAAResults BatchAA;
906
907 MemorySSA &MSSA;
908 DominatorTree &DT;
909 PostDominatorTree &PDT;
910 const TargetLibraryInfo &TLI;
911 const DataLayout &DL;
912 const CycleInfo &CI;
913
914 // All MemoryDefs that potentially could kill other MemDefs.
916 // Any that should be skipped as they are already deleted
917 SmallPtrSet<MemoryAccess *, 4> SkipStores;
918 // Keep track whether a given object is captured before return or not.
919 DenseMap<const Value *, bool> CapturedBeforeReturn;
920 // Keep track of all of the objects that are invisible to the caller after
921 // the function returns.
922 DenseMap<const Value *, bool> InvisibleToCallerAfterRet;
923 DenseMap<const Value *, uint64_t> InvisibleToCallerAfterRetBounded;
924 // Keep track of blocks with throwing instructions not modeled in MemorySSA.
925 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks;
926 // Post-order numbers for each basic block. Used to figure out if memory
927 // accesses are executed before another access.
928 DenseMap<BasicBlock *, unsigned> PostOrderNumbers;
929
930 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per
931 /// basic block.
932 MapVector<BasicBlock *, InstOverlapIntervalsTy> IOLs;
933 // Check if there are root nodes that are terminated by UnreachableInst.
934 // Those roots pessimize post-dominance queries. If there are such roots,
935 // fall back to CFG scan starting from all non-unreachable roots.
936 bool AnyUnreachableExit;
937
938 // Whether or not we should iterate on removing dead stores at the end of the
939 // function due to removing a store causing a previously captured pointer to
940 // no longer be captured.
941 bool ShouldIterateEndOfFunctionDSE;
942
943 /// Dead instructions to be removed at the end of DSE.
944 SmallVector<Instruction *> ToRemove;
945
946 // Class contains self-reference, make sure it's not copied/moved.
947 DSEState(const ScalarOptions &Opts, Function &F, AliasAnalysis &AA,
948 MemorySSA &MSSA, DominatorTree &DT, PostDominatorTree &PDT,
949 const TargetLibraryInfo &TLI, const CycleInfo &CI);
950 DSEState(const DSEState &) = delete;
951 DSEState &operator=(const DSEState &) = delete;
952
953 LocationSize strengthenLocationSize(const Instruction *I,
954 LocationSize Size) const;
955
956 /// Return 'OW_Complete' if a store to the 'KillingLoc' location (by \p
957 /// KillingI instruction) completely overwrites a store to the 'DeadLoc'
958 /// location (by \p DeadI instruction).
959 /// Return OW_MaybePartial if \p KillingI does not completely overwrite
960 /// \p DeadI, but they both write to the same underlying object. In that
961 /// case, use isPartialOverwrite to check if \p KillingI partially overwrites
962 /// \p DeadI. Returns 'OR_None' if \p KillingI is known to not overwrite the
963 /// \p DeadI. Returns 'OW_Unknown' if nothing can be determined.
964 OverwriteResult isOverwrite(const Instruction *KillingI,
965 const Instruction *DeadI,
966 const MemoryLocation &KillingLoc,
967 const MemoryLocation &DeadLoc,
968 int64_t &KillingOff, int64_t &DeadOff);
969
970 bool isInvisibleToCallerAfterRet(const Value *V, const Value *Ptr,
971 const LocationSize StoreSize);
972
973 bool isInvisibleToCallerOnUnwind(const Value *V);
974
975 std::optional<MemoryLocation> getLocForWrite(Instruction *I) const;
976
977 // Returns a list of <MemoryLocation, bool> pairs written by I.
978 // The bool means whether the write is from Initializes attr.
980 getLocForInst(Instruction *I, bool ConsiderInitializesAttr);
981
982 /// Assuming this instruction has a dead analyzable write, can we delete
983 /// this instruction?
984 bool isRemovable(Instruction *I);
985
986 /// Returns true if \p UseInst completely overwrites \p DefLoc
987 /// (stored by \p DefInst).
988 bool isCompleteOverwrite(const MemoryLocation &DefLoc, Instruction *DefInst,
989 Instruction *UseInst);
990
991 /// Returns true if \p Def is not read before returning from the function.
992 bool isWriteAtEndOfFunction(MemoryDef *Def, const MemoryLocation &DefLoc);
993
994 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a
995 /// pair with the MemoryLocation terminated by \p I and a boolean flag
996 /// indicating whether \p I is a free-like call.
997 std::optional<std::pair<MemoryLocation, bool>>
998 getLocForTerminator(Instruction *I) const;
999
1000 /// Returns true if \p I is a memory terminator instruction like
1001 /// llvm.lifetime.end or free.
1002 bool isMemTerminatorInst(Instruction *I) const;
1003
1004 /// Returns true if \p MaybeTerm is a memory terminator for \p Loc from
1005 /// instruction \p AccessI.
1006 bool isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI,
1007 Instruction *MaybeTerm);
1008
1009 // Returns true if \p Use may read from \p DefLoc.
1010 bool isReadClobber(const MemoryLocation &DefLoc, Instruction *UseInst);
1011
1012 /// Returns true if a dependency between \p Current and \p KillingDef is
1013 /// guaranteed to be loop invariant for the loops that they are in. Either
1014 /// because they are known to be in the same block, in the same loop level or
1015 /// by guaranteeing that \p CurrentLoc only references a single MemoryLocation
1016 /// during execution of the containing function.
1017 bool isGuaranteedLoopIndependent(const Instruction *Current,
1018 const Instruction *KillingDef,
1019 const MemoryLocation &CurrentLoc);
1020
1021 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1022 /// loop. In particular, this guarantees that it only references a single
1023 /// MemoryLocation during execution of the containing function.
1024 bool isGuaranteedLoopInvariant(const Value *Ptr);
1025
1026 // Find a MemoryDef writing to \p KillingLoc and dominating \p StartAccess,
1027 // with no read access between them or on any other path to a function exit
1028 // block if \p KillingLoc is not accessible after the function returns. If
1029 // there is no such MemoryDef, return std::nullopt. The returned value may not
1030 // (completely) overwrite \p KillingLoc. Currently we bail out when we
1031 // encounter an aliasing MemoryUse (read).
1032 std::optional<MemoryAccess *>
1033 getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess,
1034 const MemoryLocation &KillingLoc, const Value *KillingUndObj,
1035 unsigned &ScanLimit, unsigned &WalkerStepLimit,
1036 bool IsMemTerm, unsigned &PartialLimit,
1037 bool IsInitializesAttrMemLoc);
1038
1039 /// Delete dead memory defs and recursively add their operands to ToRemove if
1040 /// they became dead.
1041 void
1042 deleteDeadInstruction(Instruction *SI,
1043 SmallPtrSetImpl<MemoryAccess *> *Deleted = nullptr);
1044
1045 // Check for any extra throws between \p KillingI and \p DeadI that block
1046 // DSE. This only checks extra maythrows (those that aren't MemoryDef's).
1047 // MemoryDef that may throw are handled during the walk from one def to the
1048 // next.
1049 bool mayThrowBetween(Instruction *KillingI, Instruction *DeadI,
1050 const Value *KillingUndObj);
1051
1052 // Check if \p DeadI acts as a DSE barrier for \p KillingI. The following
1053 // instructions act as barriers:
1054 // * A memory instruction that may throw and \p KillingI accesses a non-stack
1055 // object.
1056 // * Atomic stores stronger that monotonic.
1057 bool isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI);
1058
1059 /// Eliminate writes to objects that are not visible in the caller and are not
1060 /// accessed before returning from the function.
1061 bool eliminateDeadWritesAtEndOfFunction();
1062
1063 /// If we have a zero initializing memset following a call to malloc,
1064 /// try folding it into a call to calloc.
1065 bool tryFoldIntoCalloc(MemoryDef *Def, const Value *DefUO);
1066
1067 /// \returns true if \p Def is a no-op store, either because it
1068 /// directly stores back a loaded value or stores zero to a calloced object.
1069 bool storeIsNoop(MemoryDef *Def, const Value *DefUO);
1070
1071 bool removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL);
1072
1073 /// Eliminates writes to locations where the value that is being written
1074 /// is already stored at the same location.
1075 bool eliminateRedundantStoresOfExistingValues();
1076
1077 /// If there is a dominating condition that implies the value being stored in
1078 /// a pointer, and such a condition appears in a node that dominates the
1079 /// store, then the store may be redundant if no write occurs in between.
1080 bool eliminateRedundantStoresViaDominatingConditions();
1081
1082 // Return the locations written by the initializes attribute.
1083 // Note that this function considers:
1084 // 1. Unwind edge: use "initializes" attribute only if the callee has
1085 // "nounwind" attribute, or the argument has "dead_on_unwind" attribute,
1086 // or the argument is invisible to caller on unwind. That is, we don't
1087 // perform incorrect DSE on unwind edges in the current function.
1088 // 2. Argument alias: for aliasing arguments, the "initializes" attribute is
1089 // the intersected range list of their "initializes" attributes.
1090 SmallVector<MemoryLocation, 1> getInitializesArgMemLoc(const Instruction *I);
1091
1092 // Try to eliminate dead defs that access `KillingLocWrapper.MemLoc` and are
1093 // killed by `KillingLocWrapper.MemDef`. Return whether
1094 // any changes were made, and whether `KillingLocWrapper.DefInst` was deleted.
1095 std::pair<bool, bool>
1096 eliminateDeadDefs(const MemoryLocationWrapper &KillingLocWrapper);
1097
1098 // Try to eliminate dead defs killed by `KillingDefWrapper` and return the
1099 // change state: whether make any change.
1100 bool eliminateDeadDefs(const MemoryDefWrapper &KillingDefWrapper);
1101};
1102
1103} // end anonymous namespace
1104
1105static void pushMemUses(MemoryAccess *Acc,
1108 for (Use &U : Acc->uses()) {
1109 auto *MA = cast<MemoryAccess>(U.getUser());
1110 if (Visited.insert(MA).second)
1111 WorkList.push_back(MA);
1112 }
1113}
1114
1115// Return true if "Arg" is function local and isn't captured before "CB".
1116static bool isFuncLocalAndNotCaptured(Value *Arg, const CallBase *CB,
1118 const Value *UnderlyingObj = getUnderlyingObject(Arg);
1119 return isIdentifiedFunctionLocal(UnderlyingObj) &&
1120 capturesNothing(EA.getCapturesBefore(UnderlyingObj, CB, /*OrAt=*/true,
1121 /*ReturnCaptures=*/false));
1122}
1123
1124DSEState::DSEState(const ScalarOptions &Opts, Function &F, AliasAnalysis &AA,
1125 MemorySSA &MSSA, DominatorTree &DT, PostDominatorTree &PDT,
1126 const TargetLibraryInfo &TLI, const CycleInfo &CI)
1127 : Opts(Opts), F(F), AA(AA), EA(DT, nullptr, &CI), BatchAA(AA, &EA),
1128 MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI), DL(F.getDataLayout()), CI(CI) {
1129 // Collect blocks with throwing instructions not modeled in MemorySSA and
1130 // alloc-like objects.
1131 unsigned PO = 0;
1132 for (BasicBlock *BB : post_order(&F)) {
1133 PostOrderNumbers[BB] = PO++;
1134 for (Instruction &I : *BB) {
1135 MemoryAccess *MA = MSSA.getMemoryAccess(&I);
1136 if (I.mayThrow() && !MA)
1137 ThrowingBlocks.insert(I.getParent());
1138
1139 auto *MD = dyn_cast_or_null<MemoryDef>(MA);
1140 if (MD && MemDefs.size() < Opts.dse_memoryssa_defs_per_block_limit &&
1141 (getLocForWrite(&I) || isMemTerminatorInst(&I) ||
1142 (Opts.enable_dse_initializes_attr_improvement &&
1144 MemDefs.push_back(MD);
1145 }
1146 }
1147
1148 // Treat byval, inalloca or dead on return arguments the same as Allocas,
1149 // stores to them are dead at the end of the function.
1150 for (Argument &AI : F.args()) {
1151 if (AI.hasPassPointeeByValueCopyAttr()) {
1152 InvisibleToCallerAfterRet.insert({&AI, true});
1153 continue;
1154 }
1155
1156 if (!AI.getType()->isPointerTy())
1157 continue;
1158
1159 const DeadOnReturnInfo &Info = AI.getDeadOnReturnInfo();
1160 if (Info.coversAllReachableMemory())
1161 InvisibleToCallerAfterRet.insert({&AI, true});
1162 else if (uint64_t DeadBytes = Info.getNumberOfDeadBytes())
1163 InvisibleToCallerAfterRetBounded.insert({&AI, DeadBytes});
1164 }
1165
1166 AnyUnreachableExit = any_of(PDT.roots(), [](const BasicBlock *E) {
1167 return isa<UnreachableInst>(E->getTerminator());
1168 });
1169}
1170
1171LocationSize DSEState::strengthenLocationSize(const Instruction *I,
1172 LocationSize Size) const {
1173 if (auto *CB = dyn_cast<CallBase>(I)) {
1174 LibFunc F = TLI.getLibFunc(*CB);
1175 if (TLI.has(F) && (F == LibFunc_memset_chk || F == LibFunc_memcpy_chk)) {
1176 // Use the precise location size specified by the 3rd argument
1177 // for determining KillingI overwrites DeadLoc if it is a memset_chk
1178 // instruction. memset_chk will write either the amount specified as 3rd
1179 // argument or the function will immediately abort and exit the program.
1180 // NOTE: AA may determine NoAlias if it can prove that the access size
1181 // is larger than the allocation size due to that being UB. To avoid
1182 // returning potentially invalid NoAlias results by AA, limit the use of
1183 // the precise location size to isOverwrite.
1184 if (const auto *Len = dyn_cast<ConstantInt>(CB->getArgOperand(2)))
1185 return LocationSize::precise(Len->getZExtValue());
1186 }
1187 }
1188 return Size;
1189}
1190
1191OverwriteResult DSEState::isOverwrite(const Instruction *KillingI,
1192 const Instruction *DeadI,
1193 const MemoryLocation &KillingLoc,
1194 const MemoryLocation &DeadLoc,
1195 int64_t &KillingOff, int64_t &DeadOff) {
1196 // AliasAnalysis does not always account for loops. Limit overwrite checks
1197 // to dependencies for which we can guarantee they are independent of any
1198 // loops they are in.
1199 if (!isGuaranteedLoopIndependent(DeadI, KillingI, DeadLoc))
1200 return OW_Unknown;
1201
1202 LocationSize KillingLocSize =
1203 strengthenLocationSize(KillingI, KillingLoc.Size);
1204 const Value *DeadPtr = DeadLoc.Ptr->stripPointerCasts();
1205 const Value *KillingPtr = KillingLoc.Ptr->stripPointerCasts();
1206 const Value *DeadUndObj = getUnderlyingObject(DeadPtr);
1207 const Value *KillingUndObj = getUnderlyingObject(KillingPtr);
1208
1209 // Check whether the killing store overwrites the whole object, in which
1210 // case the size/offset of the dead store does not matter.
1211 if (DeadUndObj == KillingUndObj && KillingLocSize.isPrecise() &&
1212 isIdentifiedObject(KillingUndObj)) {
1213 std::optional<TypeSize> KillingUndObjSize =
1214 getPointerSize(KillingUndObj, DL, TLI, &F);
1215 if (KillingUndObjSize && *KillingUndObjSize == KillingLocSize.getValue())
1216 return OW_Complete;
1217 }
1218
1219 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
1220 // get imprecise values here, though (except for unknown sizes).
1221 if (!KillingLocSize.isPrecise() || !DeadLoc.Size.isPrecise()) {
1222 // In case no constant size is known, try to an IR values for the number
1223 // of bytes written and check if they match.
1224 const auto *KillingMemI = dyn_cast<MemIntrinsic>(KillingI);
1225 const auto *DeadMemI = dyn_cast<MemIntrinsic>(DeadI);
1226 if (KillingMemI && DeadMemI) {
1227 const Value *KillingV = KillingMemI->getLength();
1228 const Value *DeadV = DeadMemI->getLength();
1229 if (KillingV == DeadV && BatchAA.isMustAlias(DeadLoc, KillingLoc))
1230 return OW_Complete;
1231 }
1232
1233 // Masked stores have imprecise locations, but we can reason about them
1234 // to some extent.
1235 return isMaskedStoreOverwrite(KillingI, DeadI, BatchAA);
1236 }
1237
1238 const TypeSize KillingSize = KillingLocSize.getValue();
1239 const TypeSize DeadSize = DeadLoc.Size.getValue();
1240 // Bail on doing Size comparison which depends on AA for now
1241 // TODO: Remove AnyScalable once Alias Analysis deal with scalable vectors
1242 const bool AnyScalable = DeadSize.isScalable() || KillingLocSize.isScalable();
1243
1244 if (AnyScalable)
1245 return OW_Unknown;
1246 // Query the alias information
1247 AliasResult AAR = BatchAA.alias(KillingLoc, DeadLoc);
1248
1249 // If the start pointers are the same, we just have to compare sizes to see if
1250 // the killing store was larger than the dead store.
1251 if (AAR == AliasResult::MustAlias) {
1252 // Make sure that the KillingSize size is >= the DeadSize size.
1253 if (KillingSize >= DeadSize)
1254 return OW_Complete;
1255 }
1256
1257 // If we hit a partial alias we may have a full overwrite
1258 if (AAR == AliasResult::PartialAlias && AAR.hasOffset()) {
1259 int32_t Off = AAR.getOffset();
1260 if (Off >= 0 && (uint64_t)Off + DeadSize <= KillingSize)
1261 return OW_Complete;
1262 }
1263
1264 // If we can't resolve the same pointers to the same object, then we can't
1265 // analyze them at all.
1266 if (DeadUndObj != KillingUndObj) {
1267 // Non aliasing stores to different objects don't overlap. Note that
1268 // if the killing store is known to overwrite whole object (out of
1269 // bounds access overwrites whole object as well) then it is assumed to
1270 // completely overwrite any store to the same object even if they don't
1271 // actually alias (see next check).
1272 if (AAR == AliasResult::NoAlias)
1273 return OW_None;
1274 return OW_Unknown;
1275 }
1276
1277 // Okay, we have stores to two completely different pointers. Try to
1278 // decompose the pointer into a "base + constant_offset" form. If the base
1279 // pointers are equal, then we can reason about the two stores.
1280 DeadOff = 0;
1281 KillingOff = 0;
1282 const Value *DeadBasePtr =
1283 GetPointerBaseWithConstantOffset(DeadPtr, DeadOff, DL);
1284 const Value *KillingBasePtr =
1285 GetPointerBaseWithConstantOffset(KillingPtr, KillingOff, DL);
1286
1287 // If the base pointers still differ, we have two completely different
1288 // stores.
1289 if (DeadBasePtr != KillingBasePtr)
1290 return OW_Unknown;
1291
1292 // The killing access completely overlaps the dead store if and only if
1293 // both start and end of the dead one is "inside" the killing one:
1294 // |<->|--dead--|<->|
1295 // |-----killing------|
1296 // Accesses may overlap if and only if start of one of them is "inside"
1297 // another one:
1298 // |<->|--dead--|<-------->|
1299 // |-------killing--------|
1300 // OR
1301 // |-------dead-------|
1302 // |<->|---killing---|<----->|
1303 //
1304 // We have to be careful here as *Off is signed while *.Size is unsigned.
1305
1306 // Check if the dead access starts "not before" the killing one.
1307 if (DeadOff >= KillingOff) {
1308 // If the dead access ends "not after" the killing access then the
1309 // dead one is completely overwritten by the killing one.
1310 if (uint64_t(DeadOff - KillingOff) + DeadSize <= KillingSize)
1311 return OW_Complete;
1312 // If start of the dead access is "before" end of the killing access
1313 // then accesses overlap.
1314 else if ((uint64_t)(DeadOff - KillingOff) < KillingSize)
1315 return OW_MaybePartial;
1316 }
1317 // If start of the killing access is "before" end of the dead access then
1318 // accesses overlap.
1319 else if ((uint64_t)(KillingOff - DeadOff) < DeadSize) {
1320 return OW_MaybePartial;
1321 }
1322
1323 // Can reach here only if accesses are known not to overlap.
1324 return OW_None;
1325}
1326
1327bool DSEState::isInvisibleToCallerAfterRet(const Value *V, const Value *Ptr,
1328 const LocationSize StoreSize) {
1329 if (isa<AllocaInst>(V))
1330 return true;
1331
1332 auto IBounded = InvisibleToCallerAfterRetBounded.find(V);
1333 if (IBounded != InvisibleToCallerAfterRetBounded.end()) {
1334 int64_t ValueOffset;
1335 [[maybe_unused]] const Value *BaseValue =
1336 GetPointerBaseWithConstantOffset(Ptr, ValueOffset, DL);
1337 // If we are not able to find a constant offset from the UO, we have to
1338 // pessimistically assume that the store writes to memory out of the
1339 // dead_on_return bounds.
1340 if (BaseValue != V)
1341 return false;
1342 // This store is only invisible after return if we are in bounds of the
1343 // range marked dead.
1344 if (StoreSize.hasValue() &&
1345 ValueOffset + StoreSize.getValue() <= IBounded->second &&
1346 ValueOffset >= 0)
1347 return true;
1348 }
1349 auto I = InvisibleToCallerAfterRet.insert({V, false});
1350 if (I.second && isInvisibleToCallerOnUnwind(V) && isNoAliasCall(V))
1351 I.first->second = capturesNothing(
1352 PointerMayBeCaptured(V, CaptureComponents::Provenance).WithRet);
1353 return I.first->second;
1354}
1355
1356bool DSEState::isInvisibleToCallerOnUnwind(const Value *V) {
1357 bool RequiresNoCaptureBeforeUnwind;
1358 if (!isNotVisibleOnUnwind(V, RequiresNoCaptureBeforeUnwind))
1359 return false;
1360 if (!RequiresNoCaptureBeforeUnwind)
1361 return true;
1362
1363 auto I = CapturedBeforeReturn.insert({V, true});
1364 if (I.second)
1365 // NOTE: This could be made more precise by PointerMayBeCapturedBefore
1366 // with the killing MemoryDef. But we refrain from doing so for now to
1367 // limit compile-time and this does not cause any changes to the number
1368 // of stores removed on a large test set in practice.
1369 I.first->second = capturesAnything(
1370 PointerMayBeCaptured(V, CaptureComponents::Provenance).WithoutRet);
1371 return !I.first->second;
1372}
1373
1374std::optional<MemoryLocation> DSEState::getLocForWrite(Instruction *I) const {
1375 if (!I->mayWriteToMemory())
1376 return std::nullopt;
1377
1378 if (auto *CB = dyn_cast<CallBase>(I))
1379 return MemoryLocation::getForDest(CB, TLI);
1380
1382}
1383
1385DSEState::getLocForInst(Instruction *I, bool ConsiderInitializesAttr) {
1387 if (isMemTerminatorInst(I)) {
1388 if (auto Loc = getLocForTerminator(I))
1389 Locations.push_back(std::make_pair(Loc->first, false));
1390 return Locations;
1391 }
1392
1393 if (auto Loc = getLocForWrite(I))
1394 Locations.push_back(std::make_pair(*Loc, false));
1395
1396 if (ConsiderInitializesAttr) {
1397 for (auto &MemLoc : getInitializesArgMemLoc(I)) {
1398 Locations.push_back(std::make_pair(MemLoc, true));
1399 }
1400 }
1401 return Locations;
1402}
1403
1404bool DSEState::isRemovable(Instruction *I) {
1405 assert(getLocForWrite(I) && "Must have analyzable write");
1406
1407 // Don't remove volatile/atomic stores.
1408 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1409 return SI->isUnordered();
1410
1411 if (auto *CB = dyn_cast<CallBase>(I)) {
1412 // Don't remove volatile memory intrinsics.
1413 if (auto *MI = dyn_cast<MemIntrinsic>(CB))
1414 return !MI->isVolatile();
1415
1416 // Never remove dead lifetime intrinsics, e.g. because they are followed
1417 // by a free.
1418 if (CB->isLifetimeStartOrEnd())
1419 return false;
1420
1421 return CB->use_empty() && CB->willReturn() && CB->doesNotThrow() &&
1422 !CB->isTerminator();
1423 }
1424
1425 return false;
1426}
1427
1428bool DSEState::isCompleteOverwrite(const MemoryLocation &DefLoc,
1429 Instruction *DefInst, Instruction *UseInst) {
1430 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a
1431 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a
1432 // MemoryDef.
1433 if (!UseInst->mayWriteToMemory())
1434 return false;
1435
1436 if (auto *CB = dyn_cast<CallBase>(UseInst))
1437 if (CB->onlyAccessesInaccessibleMemory())
1438 return false;
1439
1440 int64_t InstWriteOffset, DepWriteOffset;
1441 if (auto CC = getLocForWrite(UseInst))
1442 return isOverwrite(UseInst, DefInst, *CC, DefLoc, InstWriteOffset,
1443 DepWriteOffset) == OW_Complete;
1444 return false;
1445}
1446
1447bool DSEState::isWriteAtEndOfFunction(MemoryDef *Def,
1448 const MemoryLocation &DefLoc) {
1449 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " ("
1450 << *Def->getMemoryInst()
1451 << ") is at the end the function \n");
1453 SmallPtrSet<MemoryAccess *, 8> Visited;
1454
1455 pushMemUses(Def, WorkList, Visited);
1456 for (unsigned I = 0; I < WorkList.size(); I++) {
1457 if (WorkList.size() >= Opts.dse_memoryssa_scanlimit) {
1458 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n");
1459 return false;
1460 }
1461
1462 MemoryAccess *UseAccess = WorkList[I];
1463 if (isa<MemoryPhi>(UseAccess)) {
1464 // AliasAnalysis does not account for loops. Limit elimination to
1465 // candidates for which we can guarantee they always store to the same
1466 // memory location.
1467 if (!isGuaranteedLoopInvariant(DefLoc.Ptr))
1468 return false;
1469
1470 pushMemUses(cast<MemoryPhi>(UseAccess), WorkList, Visited);
1471 continue;
1472 }
1473 // TODO: Checking for aliasing is expensive. Consider reducing the amount
1474 // of times this is called and/or caching it.
1475 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1476 if (isReadClobber(DefLoc, UseInst)) {
1477 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n");
1478 return false;
1479 }
1480
1481 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess))
1482 pushMemUses(UseDef, WorkList, Visited);
1483 }
1484 return true;
1485}
1486
1487std::optional<std::pair<MemoryLocation, bool>>
1488DSEState::getLocForTerminator(Instruction *I) const {
1489 if (auto *CB = dyn_cast<CallBase>(I)) {
1490 if (CB->getIntrinsicID() == Intrinsic::lifetime_end)
1491 return {
1492 std::make_pair(MemoryLocation::getForArgument(CB, 0, &TLI), false)};
1493 if (Value *FreedOp = getFreedOperand(CB, &TLI))
1494 return {std::make_pair(MemoryLocation::getAfter(FreedOp), true)};
1495 }
1496
1497 return std::nullopt;
1498}
1499
1500bool DSEState::isMemTerminatorInst(Instruction *I) const {
1501 auto *CB = dyn_cast<CallBase>(I);
1502 return CB && (CB->getIntrinsicID() == Intrinsic::lifetime_end ||
1503 getFreedOperand(CB, &TLI) != nullptr);
1504}
1505
1506bool DSEState::isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI,
1507 Instruction *MaybeTerm) {
1508 std::optional<std::pair<MemoryLocation, bool>> MaybeTermLoc =
1509 getLocForTerminator(MaybeTerm);
1510
1511 if (!MaybeTermLoc)
1512 return false;
1513
1514 // If the terminator is a free-like call, all accesses to the underlying
1515 // object can be considered terminated.
1516 if (getUnderlyingObject(Loc.Ptr) !=
1517 getUnderlyingObject(MaybeTermLoc->first.Ptr))
1518 return false;
1519
1520 auto TermLoc = MaybeTermLoc->first;
1521 if (MaybeTermLoc->second) {
1522 const Value *LocUO = getUnderlyingObject(Loc.Ptr);
1523 return BatchAA.isMustAlias(TermLoc.Ptr, LocUO);
1524 }
1525 int64_t InstWriteOffset = 0;
1526 int64_t DepWriteOffset = 0;
1527 return isOverwrite(MaybeTerm, AccessI, TermLoc, Loc, InstWriteOffset,
1528 DepWriteOffset) == OW_Complete;
1529}
1530
1531bool DSEState::isReadClobber(const MemoryLocation &DefLoc,
1532 Instruction *UseInst) {
1533 if (isNoopIntrinsic(UseInst))
1534 return false;
1535
1536 // Monotonic or weaker atomic stores can be re-ordered and do not need to be
1537 // treated as read clobber.
1538 if (auto SI = dyn_cast<StoreInst>(UseInst))
1539 return isStrongerThan(SI->getOrdering(), AtomicOrdering::Monotonic);
1540
1541 if (!UseInst->mayReadFromMemory())
1542 return false;
1543
1544 if (auto *CB = dyn_cast<CallBase>(UseInst))
1545 if (CB->onlyAccessesInaccessibleMemory())
1546 return false;
1547
1548 return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc));
1549}
1550
1551bool DSEState::isGuaranteedLoopIndependent(const Instruction *Current,
1552 const Instruction *KillingDef,
1553 const MemoryLocation &CurrentLoc) {
1554 // If the dependency is within the same block or loop level (being careful
1555 // of irreducible loops), we know that AA will return a valid result for the
1556 // memory dependency. (Both at the function level, outside of any loop,
1557 // would also be valid but we currently disable that to limit compile time).
1558 if (Current->getParent() == KillingDef->getParent())
1559 return true;
1560 CycleRef CurrentC = CI.getCycle(Current->getParent());
1561 if (CurrentC && CurrentC == CI.getCycle(KillingDef->getParent()))
1562 return true;
1563 // Otherwise check the memory location is invariant to any loops.
1564 return isGuaranteedLoopInvariant(CurrentLoc.Ptr);
1565}
1566
1567bool DSEState::isGuaranteedLoopInvariant(const Value *Ptr) {
1568 Ptr = Ptr->stripPointerCasts();
1569 if (auto *GEP = dyn_cast<GEPOperator>(Ptr))
1570 if (GEP->hasAllConstantIndices())
1571 Ptr = GEP->getPointerOperand()->stripPointerCasts();
1572
1573 if (auto *I = dyn_cast<Instruction>(Ptr)) {
1574 return I->getParent()->isEntryBlock() || !CI.getCycle(I->getParent());
1575 }
1576 return true;
1577}
1578
1579std::optional<MemoryAccess *> DSEState::getDomMemoryDef(
1580 MemoryDef *KillingDef, MemoryAccess *StartAccess,
1581 const MemoryLocation &KillingLoc, const Value *KillingUndObj,
1582 unsigned &ScanLimit, unsigned &WalkerStepLimit, bool IsMemTerm,
1583 unsigned &PartialLimit, bool IsInitializesAttrMemLoc) {
1584 if (ScanLimit == 0 || WalkerStepLimit == 0) {
1585 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n");
1586 return std::nullopt;
1587 }
1588
1589 MemoryAccess *Current = StartAccess;
1590 Instruction *KillingI = KillingDef->getMemoryInst();
1591 LLVM_DEBUG(dbgs() << " trying to get dominating access\n");
1592
1593 // Only optimize defining access of KillingDef when directly starting at its
1594 // defining access. The defining access also must only access KillingLoc. At
1595 // the moment we only support instructions with a single write location, so
1596 // it should be sufficient to disable optimizations for instructions that
1597 // also read from memory.
1598 bool CanOptimize = Opts.dse_optimize_memoryssa &&
1599 KillingDef->getDefiningAccess() == StartAccess &&
1600 !KillingI->mayReadFromMemory();
1601
1602 // Find the next clobbering Mod access for DefLoc, starting at StartAccess.
1603 std::optional<MemoryLocation> CurrentLoc;
1604 for (;; Current = cast<MemoryDef>(Current)->getDefiningAccess()) {
1605 LLVM_DEBUG({
1606 dbgs() << " visiting " << *Current;
1607 if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current))
1608 dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst()
1609 << ")";
1610 dbgs() << "\n";
1611 });
1612
1613 // Reached TOP.
1614 if (MSSA.isLiveOnEntryDef(Current)) {
1615 LLVM_DEBUG(dbgs() << " ... found LiveOnEntryDef\n");
1616 if (CanOptimize && Current != KillingDef->getDefiningAccess())
1617 // The first clobbering def is... none.
1618 KillingDef->setOptimized(Current);
1619 return std::nullopt;
1620 }
1621
1622 // Cost of a step. Accesses in the same block are more likely to be valid
1623 // candidates for elimination, hence consider them cheaper.
1624 unsigned StepCost = KillingDef->getBlock() == Current->getBlock()
1625 ? Opts.dse_memoryssa_samebb_cost
1626 : Opts.dse_memoryssa_otherbb_cost;
1627 if (WalkerStepLimit <= StepCost) {
1628 LLVM_DEBUG(dbgs() << " ... hit walker step limit\n");
1629 return std::nullopt;
1630 }
1631 WalkerStepLimit -= StepCost;
1632
1633 // Return for MemoryPhis. They cannot be eliminated directly and the
1634 // caller is responsible for traversing them.
1635 if (isa<MemoryPhi>(Current)) {
1636 LLVM_DEBUG(dbgs() << " ... found MemoryPhi\n");
1637 return Current;
1638 }
1639
1640 // Below, check if CurrentDef is a valid candidate to be eliminated by
1641 // KillingDef. If it is not, check the next candidate.
1642 MemoryDef *CurrentDef = cast<MemoryDef>(Current);
1643 Instruction *CurrentI = CurrentDef->getMemoryInst();
1644
1645 if (canSkipDef(CurrentDef, !isInvisibleToCallerOnUnwind(KillingUndObj))) {
1646 CanOptimize = false;
1647 continue;
1648 }
1649
1650 // Before we try to remove anything, check for any extra throwing
1651 // instructions that block us from DSEing
1652 if (mayThrowBetween(KillingI, CurrentI, KillingUndObj)) {
1653 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n");
1654 return std::nullopt;
1655 }
1656
1657 // Check for anything that looks like it will be a barrier to further
1658 // removal
1659 if (isDSEBarrier(KillingUndObj, CurrentI)) {
1660 LLVM_DEBUG(dbgs() << " ... skip, barrier\n");
1661 return std::nullopt;
1662 }
1663
1664 // If Current is known to be on path that reads DefLoc or is a read
1665 // clobber, bail out, as the path is not profitable. We skip this check
1666 // for intrinsic calls, because the code knows how to handle memcpy
1667 // intrinsics.
1668 if (!isa<IntrinsicInst>(CurrentI) && isReadClobber(KillingLoc, CurrentI))
1669 return std::nullopt;
1670
1671 // Quick check if there are direct uses that are read-clobbers.
1672 if (any_of(Current->uses(), [this, &KillingLoc, StartAccess](Use &U) {
1673 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U.getUser()))
1674 return !MSSA.dominates(StartAccess, UseOrDef) &&
1675 isReadClobber(KillingLoc, UseOrDef->getMemoryInst());
1676 return false;
1677 })) {
1678 LLVM_DEBUG(dbgs() << " ... found a read clobber\n");
1679 return std::nullopt;
1680 }
1681
1682 // If Current does not have an analyzable write location or is not
1683 // removable, skip it.
1684 CurrentLoc = getLocForWrite(CurrentI);
1685 if (!CurrentLoc || !isRemovable(CurrentI)) {
1686 CanOptimize = false;
1687 continue;
1688 }
1689
1690 // AliasAnalysis does not account for loops. Limit elimination to
1691 // candidates for which we can guarantee they always store to the same
1692 // memory location and not located in different loops.
1693 if (!isGuaranteedLoopIndependent(CurrentI, KillingI, *CurrentLoc)) {
1694 LLVM_DEBUG(dbgs() << " ... not guaranteed loop independent\n");
1695 CanOptimize = false;
1696 continue;
1697 }
1698
1699 if (IsMemTerm) {
1700 // If the killing def is a memory terminator (e.g. lifetime.end), check
1701 // the next candidate if the current Current does not write the same
1702 // underlying object as the terminator.
1703 if (!isMemTerminator(*CurrentLoc, CurrentI, KillingI)) {
1704 CanOptimize = false;
1705 continue;
1706 }
1707 } else {
1708 int64_t KillingOffset = 0;
1709 int64_t DeadOffset = 0;
1710 auto OR = isOverwrite(KillingI, CurrentI, KillingLoc, *CurrentLoc,
1711 KillingOffset, DeadOffset);
1712 if (CanOptimize) {
1713 // CurrentDef is the earliest write clobber of KillingDef. Use it as
1714 // optimized access. Do not optimize if CurrentDef is already the
1715 // defining access of KillingDef.
1716 if (CurrentDef != KillingDef->getDefiningAccess() &&
1717 (OR == OW_Complete || OR == OW_MaybePartial))
1718 KillingDef->setOptimized(CurrentDef);
1719
1720 // Once a may-aliasing def is encountered do not set an optimized
1721 // access.
1722 if (OR != OW_None)
1723 CanOptimize = false;
1724 }
1725
1726 // If Current does not write to the same object as KillingDef, check
1727 // the next candidate.
1728 if (OR == OW_Unknown || OR == OW_None)
1729 continue;
1730 else if (OR == OW_MaybePartial) {
1731 // If KillingDef only partially overwrites Current, check the next
1732 // candidate if the partial step limit is exceeded. This aggressively
1733 // limits the number of candidates for partial store elimination,
1734 // which are less likely to be removable in the end.
1735 if (PartialLimit <= 1) {
1736 WalkerStepLimit -= 1;
1737 LLVM_DEBUG(dbgs() << " ... reached partial limit ... continue with "
1738 "next access\n");
1739 continue;
1740 }
1741 PartialLimit -= 1;
1742 }
1743 }
1744 break;
1745 };
1746
1747 // Accesses to objects accessible after the function returns can only be
1748 // eliminated if the access is dead along all paths to the exit. Collect
1749 // the blocks with killing (=completely overwriting MemoryDefs) and check if
1750 // they cover all paths from MaybeDeadAccess to any function exit.
1751 SmallPtrSet<Instruction *, 16> KillingDefs;
1752 KillingDefs.insert(KillingDef->getMemoryInst());
1753 MemoryAccess *MaybeDeadAccess = Current;
1754 MemoryLocation MaybeDeadLoc = *CurrentLoc;
1755 Instruction *MaybeDeadI = cast<MemoryDef>(MaybeDeadAccess)->getMemoryInst();
1756 LLVM_DEBUG(dbgs() << " Checking for reads of " << *MaybeDeadAccess << " ("
1757 << *MaybeDeadI << ")\n");
1758
1760 SmallPtrSet<MemoryAccess *, 32> Visited;
1761 pushMemUses(MaybeDeadAccess, WorkList, Visited);
1762
1763 // Check if DeadDef may be read.
1764 for (unsigned I = 0; I < WorkList.size(); I++) {
1765 MemoryAccess *UseAccess = WorkList[I];
1766
1767 LLVM_DEBUG(dbgs() << " " << *UseAccess);
1768 // Bail out if the number of accesses to check exceeds the scan limit.
1769 if (ScanLimit < (WorkList.size() - I)) {
1770 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n");
1771 return std::nullopt;
1772 }
1773 --ScanLimit;
1774 NumDomMemDefChecks++;
1775
1776 if (isa<MemoryPhi>(UseAccess)) {
1777 if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) {
1778 return DT.properlyDominates(KI->getParent(), UseAccess->getBlock());
1779 })) {
1780 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1781 continue;
1782 }
1783 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n");
1784 pushMemUses(UseAccess, WorkList, Visited);
1785 continue;
1786 }
1787
1788 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1789 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
1790
1791 if (any_of(KillingDefs, [this, UseInst](Instruction *KI) {
1792 return DT.dominates(KI, UseInst);
1793 })) {
1794 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
1795 continue;
1796 }
1797
1798 // A memory terminator kills all preceeding MemoryDefs and all succeeding
1799 // MemoryAccesses. We do not have to check it's users.
1800 if (isMemTerminator(MaybeDeadLoc, MaybeDeadI, UseInst)) {
1801 LLVM_DEBUG(
1802 dbgs()
1803 << " ... skipping, memterminator invalidates following accesses\n");
1804 continue;
1805 }
1806
1807 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess)->getMemoryInst())) {
1808 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n");
1809 pushMemUses(UseAccess, WorkList, Visited);
1810 continue;
1811 }
1812
1813 if (UseInst->mayThrow() && !isInvisibleToCallerOnUnwind(KillingUndObj)) {
1814 LLVM_DEBUG(dbgs() << " ... found throwing instruction\n");
1815 return std::nullopt;
1816 }
1817
1818 // Uses which may read the original MemoryDef mean we cannot eliminate the
1819 // original MD. Stop walk.
1820 // If KillingDef is a CallInst with "initializes" attribute, the reads in
1821 // the callee would be dominated by initializations, so it should be safe.
1822 bool IsKillingDefFromInitAttr = false;
1823 if (IsInitializesAttrMemLoc) {
1824 if (KillingI == UseInst &&
1825 KillingUndObj == getUnderlyingObject(MaybeDeadLoc.Ptr))
1826 IsKillingDefFromInitAttr = true;
1827 }
1828
1829 if (isReadClobber(MaybeDeadLoc, UseInst) && !IsKillingDefFromInitAttr) {
1830 LLVM_DEBUG(dbgs() << " ... found read clobber\n");
1831 return std::nullopt;
1832 }
1833
1834 // If this worklist walks back to the original memory access (and the
1835 // pointer is not guarenteed loop invariant) then we cannot assume that a
1836 // store kills itself.
1837 if (MaybeDeadAccess == UseAccess &&
1838 !isGuaranteedLoopInvariant(MaybeDeadLoc.Ptr)) {
1839 LLVM_DEBUG(dbgs() << " ... found not loop invariant self access\n");
1840 return std::nullopt;
1841 }
1842 // Otherwise, for the KillingDef and MaybeDeadAccess we only have to check
1843 // if it reads the memory location.
1844 // TODO: It would probably be better to check for self-reads before
1845 // calling the function.
1846 if (KillingDef == UseAccess || MaybeDeadAccess == UseAccess) {
1847 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n");
1848 continue;
1849 }
1850
1851 // Check all uses for MemoryDefs, except for defs completely overwriting
1852 // the original location. Otherwise we have to check uses of *all*
1853 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
1854 // miss cases like the following
1855 // 1 = Def(LoE) ; <----- DeadDef stores [0,1]
1856 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3]
1857 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3].
1858 // (The Use points to the *first* Def it may alias)
1859 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias,
1860 // stores [0,1]
1861 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) {
1862 if (isCompleteOverwrite(MaybeDeadLoc, MaybeDeadI, UseInst)) {
1863 BasicBlock *MaybeKillingBlock = UseInst->getParent();
1864 if (PostOrderNumbers.find(MaybeKillingBlock)->second <
1865 PostOrderNumbers.find(MaybeDeadAccess->getBlock())->second) {
1866 if (!isInvisibleToCallerAfterRet(KillingUndObj, KillingLoc.Ptr,
1867 KillingLoc.Size)) {
1869 << " ... found killing def " << *UseInst << "\n");
1870 KillingDefs.insert(UseInst);
1871 }
1872 } else {
1874 << " ... found preceeding def " << *UseInst << "\n");
1875 return std::nullopt;
1876 }
1877 } else
1878 pushMemUses(UseDef, WorkList, Visited);
1879 }
1880 }
1881
1882 // For accesses to locations visible after the function returns, make sure
1883 // that the location is dead (=overwritten) along all paths from
1884 // MaybeDeadAccess to the exit.
1885 if (!isInvisibleToCallerAfterRet(KillingUndObj, KillingLoc.Ptr,
1886 KillingLoc.Size)) {
1887 SmallPtrSet<BasicBlock *, 16> KillingBlocks;
1888 for (Instruction *KD : KillingDefs)
1889 KillingBlocks.insert(KD->getParent());
1890 assert(!KillingBlocks.empty() &&
1891 "Expected at least a single killing block");
1892
1893 // Find the common post-dominator of all killing blocks.
1894 BasicBlock *CommonPred = *KillingBlocks.begin();
1895 for (BasicBlock *BB : llvm::drop_begin(KillingBlocks)) {
1896 if (!CommonPred)
1897 break;
1898 CommonPred = PDT.findNearestCommonDominator(CommonPred, BB);
1899 }
1900
1901 // If the common post-dominator does not post-dominate MaybeDeadAccess,
1902 // there is a path from MaybeDeadAccess to an exit not going through a
1903 // killing block.
1904 if (!PDT.dominates(CommonPred, MaybeDeadAccess->getBlock())) {
1905 if (!AnyUnreachableExit)
1906 return std::nullopt;
1907
1908 // Fall back to CFG scan starting at all non-unreachable roots if not
1909 // all paths to the exit go through CommonPred.
1910 CommonPred = nullptr;
1911 }
1912
1913 // If CommonPred itself is in the set of killing blocks, we're done.
1914 if (KillingBlocks.count(CommonPred))
1915 return {MaybeDeadAccess};
1916
1917 SetVector<BasicBlock *> WorkList;
1918 // If CommonPred is null, there are multiple exits from the function.
1919 // They all have to be added to the worklist.
1920 if (CommonPred)
1921 WorkList.insert(CommonPred);
1922 else
1923 for (BasicBlock *R : PDT.roots()) {
1924 if (!isa<UnreachableInst>(R->getTerminator()))
1925 WorkList.insert(R);
1926 }
1927
1928 NumCFGTries++;
1929 // Check if all paths starting from an exit node go through one of the
1930 // killing blocks before reaching MaybeDeadAccess.
1931 for (unsigned I = 0; I < WorkList.size(); I++) {
1932 NumCFGChecks++;
1933 BasicBlock *Current = WorkList[I];
1934 if (KillingBlocks.count(Current))
1935 continue;
1936 if (Current == MaybeDeadAccess->getBlock())
1937 return std::nullopt;
1938
1939 // MaybeDeadAccess is reachable from the entry, so we don't have to
1940 // explore unreachable blocks further.
1941 if (!DT.isReachableFromEntry(Current))
1942 continue;
1943
1944 WorkList.insert_range(predecessors(Current));
1945
1946 if (WorkList.size() >= Opts.dse_memoryssa_path_check_limit)
1947 return std::nullopt;
1948 }
1949 NumCFGSuccess++;
1950 }
1951
1952 // No aliasing MemoryUses of MaybeDeadAccess found, MaybeDeadAccess is
1953 // potentially dead.
1954 return {MaybeDeadAccess};
1955}
1956
1957void DSEState::deleteDeadInstruction(Instruction *SI,
1958 SmallPtrSetImpl<MemoryAccess *> *Deleted) {
1959 MemorySSAUpdater Updater(&MSSA);
1960 SmallVector<Instruction *, 32> NowDeadInsts;
1961 NowDeadInsts.push_back(SI);
1962 --NumFastOther;
1963
1964 while (!NowDeadInsts.empty()) {
1965 Instruction *DeadInst = NowDeadInsts.pop_back_val();
1966 ++NumFastOther;
1967
1968 // Try to preserve debug information attached to the dead instruction.
1969 salvageDebugInfo(*DeadInst);
1970 salvageKnowledge(DeadInst);
1971
1972 // Remove the Instruction from MSSA.
1973 MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst);
1974 bool IsMemDef = MA && isa<MemoryDef>(MA);
1975 if (MA) {
1976 if (IsMemDef) {
1977 auto *MD = cast<MemoryDef>(MA);
1978 SkipStores.insert(MD);
1979 if (Deleted)
1980 Deleted->insert(MD);
1981 if (auto *SI = dyn_cast<StoreInst>(MD->getMemoryInst())) {
1982 if (SI->getValueOperand()->getType()->isPointerTy()) {
1983 const Value *UO = getUnderlyingObject(SI->getValueOperand());
1984 if (CapturedBeforeReturn.erase(UO))
1985 ShouldIterateEndOfFunctionDSE = true;
1986 InvisibleToCallerAfterRet.erase(UO);
1987 InvisibleToCallerAfterRetBounded.erase(UO);
1988 }
1989 }
1990 }
1991
1992 Updater.removeMemoryAccess(MA);
1993 }
1994
1995 auto I = IOLs.find(DeadInst->getParent());
1996 if (I != IOLs.end())
1997 I->second.erase(DeadInst);
1998 // Remove its operands
1999 for (Use &O : DeadInst->operands())
2000 if (Instruction *OpI = dyn_cast<Instruction>(O)) {
2001 O.set(PoisonValue::get(O->getType()));
2002 if (isInstructionTriviallyDead(OpI, &TLI))
2003 NowDeadInsts.push_back(OpI);
2004 }
2005
2006 EA.removeInstruction(DeadInst);
2007 // Remove memory defs directly if they don't produce results, but only
2008 // queue other dead instructions for later removal. They may have been
2009 // used as memory locations that have been cached by BatchAA. Removing
2010 // them here may lead to newly created instructions to be allocated at the
2011 // same address, yielding stale cache entries.
2012 if (IsMemDef && DeadInst->getType()->isVoidTy())
2013 DeadInst->eraseFromParent();
2014 else
2015 ToRemove.push_back(DeadInst);
2016 }
2017}
2018
2019bool DSEState::mayThrowBetween(Instruction *KillingI, Instruction *DeadI,
2020 const Value *KillingUndObj) {
2021 // First see if we can ignore it by using the fact that KillingI is an
2022 // alloca/alloca like object that is not visible to the caller during
2023 // execution of the function.
2024 if (KillingUndObj && isInvisibleToCallerOnUnwind(KillingUndObj))
2025 return false;
2026
2027 if (KillingI->getParent() == DeadI->getParent())
2028 return ThrowingBlocks.count(KillingI->getParent());
2029 return !ThrowingBlocks.empty();
2030}
2031
2032bool DSEState::isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI) {
2033 // If DeadI may throw it acts as a barrier, unless we are to an
2034 // alloca/alloca like object that does not escape.
2035 if (DeadI->mayThrow() && !isInvisibleToCallerOnUnwind(KillingUndObj))
2036 return true;
2037
2038 // If DeadI is an atomic load/store stronger than monotonic, do not try to
2039 // eliminate/reorder it.
2040 if (DeadI->isAtomic()) {
2041 if (auto *LI = dyn_cast<LoadInst>(DeadI))
2042 return isStrongerThanMonotonic(LI->getOrdering());
2043 if (auto *SI = dyn_cast<StoreInst>(DeadI))
2044 return isStrongerThanMonotonic(SI->getOrdering());
2045 if (auto *ARMW = dyn_cast<AtomicRMWInst>(DeadI))
2046 return isStrongerThanMonotonic(ARMW->getOrdering());
2047 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(DeadI))
2048 return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) ||
2049 isStrongerThanMonotonic(CmpXchg->getFailureOrdering());
2050 llvm_unreachable("other instructions should be skipped in MemorySSA");
2051 }
2052 return false;
2053}
2054
2055bool DSEState::eliminateDeadWritesAtEndOfFunction() {
2056 bool MadeChange = false;
2057 LLVM_DEBUG(
2058 dbgs() << "Trying to eliminate MemoryDefs at the end of the function\n");
2059 do {
2060 ShouldIterateEndOfFunctionDSE = false;
2061 for (MemoryDef *Def : llvm::reverse(MemDefs)) {
2062 if (SkipStores.contains(Def))
2063 continue;
2064
2065 Instruction *DefI = Def->getMemoryInst();
2066 auto DefLoc = getLocForWrite(DefI);
2067 if (!DefLoc || !isRemovable(DefI)) {
2068 LLVM_DEBUG(dbgs() << " ... could not get location for write or "
2069 "instruction not removable.\n");
2070 continue;
2071 }
2072
2073 // NOTE: Currently eliminating writes at the end of a function is
2074 // limited to MemoryDefs with a single underlying object, to save
2075 // compile-time. In practice it appears the case with multiple
2076 // underlying objects is very uncommon. If it turns out to be important,
2077 // we can use getUnderlyingObjects here instead.
2078 const Value *UO = getUnderlyingObject(DefLoc->Ptr);
2079 if (!isInvisibleToCallerAfterRet(UO, DefLoc->Ptr, DefLoc->Size))
2080 continue;
2081
2082 if (isWriteAtEndOfFunction(Def, *DefLoc)) {
2083 // See through pointer-to-pointer bitcasts
2084 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end "
2085 "of the function\n");
2087 ++NumFastStores;
2088 MadeChange = true;
2089 }
2090 }
2091 } while (ShouldIterateEndOfFunctionDSE);
2092 return MadeChange;
2093}
2094
2095bool DSEState::eliminateRedundantStoresViaDominatingConditions() {
2096 bool MadeChange = false;
2097 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs whose value being "
2098 "written is implied by a dominating condition\n");
2099
2100 using ConditionInfo = std::pair<Value *, Value *>;
2101 using ScopedHTType = ScopedHashTable<ConditionInfo, Instruction *>;
2102
2103 // We maintain a scoped hash table of the active dominating conditions for a
2104 // given node.
2105 ScopedHTType ActiveConditions;
2106 auto GetDominatingCondition = [&](BasicBlock *BB)
2107 -> std::optional<std::tuple<ConditionInfo, Instruction *, BasicBlock *>> {
2108 auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
2109 if (!BI)
2110 return std::nullopt;
2111
2112 // In case both blocks are the same, it is not possible to determine
2113 // if optimization is possible. (We would not want to optimize a store
2114 // in the FalseBB if condition is true and vice versa.)
2115 if (BI->getSuccessor(0) == BI->getSuccessor(1))
2116 return std::nullopt;
2117
2118 Instruction *ICmpL;
2119 CmpPredicate Pred;
2120 Value *StorePtr, *StoreVal;
2121 if (!match(BI->getCondition(),
2122 m_c_ICmp(Pred, m_Instruction(ICmpL, m_Load(m_Value(StorePtr))),
2123 m_Value(StoreVal))) ||
2124 !ICmpInst::isEquality(Pred))
2125 return std::nullopt;
2126
2127 // Ensure the replacement is allowed when comparing pointers, as
2128 // the equality compares addresses only, not pointers' provenance.
2129 if (StoreVal->getType()->isPointerTy() &&
2130 !canReplacePointersIfEqual(StoreVal, ICmpL, DL))
2131 return std::nullopt;
2132
2133 unsigned ImpliedSuccIdx = Pred == ICmpInst::ICMP_EQ ? 0 : 1;
2134 BasicBlock *ImpliedSucc = BI->getSuccessor(ImpliedSuccIdx);
2135 return {{ConditionInfo(StorePtr, StoreVal), ICmpL, ImpliedSucc}};
2136 };
2137
2138 auto VisitNode = [&](DomTreeNode *Node, unsigned Depth, auto &Self) -> void {
2139 if (Depth > Opts.dse_max_dom_cond_depth)
2140 return;
2141
2142 BasicBlock *BB = Node->getBlock();
2143 // Check for redundant stores against active known conditions.
2144 if (auto *Accesses = MSSA.getBlockDefs(BB)) {
2145 for (MemoryDef &Def :
2147 auto *SI = dyn_cast<StoreInst>(Def.getMemoryInst());
2148 if (!SI || !SI->isUnordered())
2149 continue;
2150
2151 Instruction *LI = ActiveConditions.lookup(
2152 {SI->getPointerOperand(), SI->getValueOperand()});
2153 if (!LI)
2154 continue;
2155
2156 // Found a dominating condition that may imply the value being stored.
2157 // Make sure there does not exist any clobbering access between the
2158 // load and the potential redundant store.
2159 MemoryAccess *LoadAccess = MSSA.getMemoryAccess(LI);
2160 MemoryAccess *ClobberingAccess =
2161 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(&Def, BatchAA);
2162 if (MSSA.dominates(ClobberingAccess, LoadAccess)) {
2164 << "Removing No-Op Store:\n DEAD: " << *SI << '\n');
2166 NumRedundantStores++;
2167 MadeChange = true;
2168 }
2169 }
2170 }
2171
2172 // See whether this basic block establishes a dominating condition.
2173 auto MaybeCondition = GetDominatingCondition(BB);
2174
2175 for (DomTreeNode *Child : Node->children()) {
2176 // RAII scope for the active conditions.
2177 ScopedHTType::ScopeTy Scope(ActiveConditions);
2178 if (MaybeCondition) {
2179 const auto &[Cond, LI, ImpliedSucc] = *MaybeCondition;
2180 if (DT.dominates(BasicBlockEdge(BB, ImpliedSucc), Child->getBlock())) {
2181 // Found a condition that holds for this child, dominated by the
2182 // current node via the equality edge. Propagate the condition to
2183 // the children by pushing it onto the table.
2184 ActiveConditions.insert(Cond, LI);
2185 }
2186 }
2187
2188 // Recursively visit the children of this node. Upon destruction, the no
2189 // longer active condition before visiting any sibling nodes is popped
2190 // from the active scope.
2191 Self(Child, Depth + 1, Self);
2192 }
2193 };
2194
2195 // Do a DFS walk of the dom-tree.
2197
2198 return MadeChange;
2199}
2200
2201bool DSEState::tryFoldIntoCalloc(MemoryDef *Def, const Value *DefUO) {
2202 Instruction *DefI = Def->getMemoryInst();
2203 MemSetInst *MemSet = dyn_cast<MemSetInst>(DefI);
2204 if (!MemSet)
2205 // TODO: Could handle zero store to small allocation as well.
2206 return false;
2207 Constant *StoredConstant = dyn_cast<Constant>(MemSet->getValue());
2208 if (!StoredConstant || !StoredConstant->isNullValue())
2209 return false;
2210
2211 if (!isRemovable(DefI))
2212 // The memset might be volatile..
2213 return false;
2214
2215 if (F.hasFnAttribute(Attribute::SanitizeMemory) ||
2216 F.hasFnAttribute(Attribute::SanitizeAddress) ||
2217 F.hasFnAttribute(Attribute::SanitizeHWAddress) || F.getName() == "calloc")
2218 return false;
2219 auto *Malloc = const_cast<CallInst *>(dyn_cast<CallInst>(DefUO));
2220 if (!Malloc)
2221 return false;
2222 auto *InnerCallee = Malloc->getCalledFunction();
2223 if (!InnerCallee)
2224 return false;
2225 LibFunc Func = TLI.getLibFunc(*InnerCallee);
2226 StringRef ZeroedVariantName;
2227 if (Func != LibFunc_malloc || !TLI.has(Func)) {
2228 Attribute Attr = Malloc->getFnAttr("alloc-variant-zeroed");
2229 if (!Attr.isValid())
2230 return false;
2231 ZeroedVariantName = Attr.getValueAsString();
2232 if (ZeroedVariantName.empty())
2233 return false;
2234 }
2235
2236 // Gracefully handle malloc with unexpected memory attributes.
2237 auto *MallocDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(Malloc));
2238 if (!MallocDef)
2239 return false;
2240
2241 auto shouldCreateCalloc = [](CallInst *Malloc, CallInst *Memset) {
2242 // Check for br(icmp ptr, null), truebb, falsebb) pattern at the end
2243 // of malloc block
2244 auto *MallocBB = Malloc->getParent(), *MemsetBB = Memset->getParent();
2245 if (MallocBB == MemsetBB)
2246 return true;
2247 auto *Ptr = Memset->getArgOperand(0);
2248 auto *TI = MallocBB->getTerminator();
2249 BasicBlock *TrueBB, *FalseBB;
2250 if (!match(TI, m_Br(m_SpecificICmp(ICmpInst::ICMP_EQ, m_Specific(Ptr),
2251 m_Zero()),
2252 TrueBB, FalseBB)))
2253 return false;
2254 if (MemsetBB != FalseBB)
2255 return false;
2256 return true;
2257 };
2258
2259 if (Malloc->getOperand(0) != MemSet->getLength())
2260 return false;
2261 if (!shouldCreateCalloc(Malloc, MemSet) || !DT.dominates(Malloc, MemSet) ||
2262 !memoryIsNotModifiedBetween(Malloc, MemSet, BatchAA, DL, &DT))
2263 return false;
2264 IRBuilder<> IRB(Malloc);
2265 assert(Func == LibFunc_malloc || !ZeroedVariantName.empty());
2266 Value *Calloc = nullptr;
2267 if (!ZeroedVariantName.empty()) {
2268 LLVMContext &Ctx = Malloc->getContext();
2269 AttributeList Attrs = InnerCallee->getAttributes();
2270 AllocFnKind AllocKind =
2271 Attrs.getFnAttr(Attribute::AllocKind).getAllocKind() |
2272 AllocFnKind::Zeroed;
2273 AllocKind &= ~AllocFnKind::Uninitialized;
2274 Attrs =
2275 Attrs.addFnAttribute(Ctx, Attribute::getWithAllocKind(Ctx, AllocKind))
2276 .removeFnAttribute(Ctx, "alloc-variant-zeroed");
2277 FunctionCallee ZeroedVariant = Malloc->getModule()->getOrInsertFunction(
2278 ZeroedVariantName, InnerCallee->getFunctionType(), Attrs);
2279 cast<Function>(ZeroedVariant.getCallee())
2280 ->setCallingConv(Malloc->getCallingConv());
2282 Args.append(Malloc->arg_begin(), Malloc->arg_end());
2283 CallInst *CI = IRB.CreateCall(ZeroedVariant, Args, ZeroedVariantName);
2284 CI->setCallingConv(Malloc->getCallingConv());
2285 Calloc = CI;
2286 } else {
2287 Type *SizeTTy = Malloc->getArgOperand(0)->getType();
2288 Calloc = emitCalloc(ConstantInt::get(SizeTTy, 1), Malloc->getArgOperand(0),
2289 IRB, TLI, Malloc->getType()->getPointerAddressSpace());
2290 }
2291 if (!Calloc)
2292 return false;
2293
2294 if (MDNode *MD = Malloc->getMetadata(LLVMContext::MD_alloc_token))
2295 cast<Instruction>(Calloc)->setMetadata(LLVMContext::MD_alloc_token, MD);
2296
2297 MemorySSAUpdater Updater(&MSSA);
2298 auto *NewAccess = Updater.createMemoryAccessAfter(cast<Instruction>(Calloc),
2299 nullptr, MallocDef);
2300 auto *NewAccessMD = cast<MemoryDef>(NewAccess);
2301 Updater.insertDef(NewAccessMD, /*RenameUses=*/true);
2302 Malloc->replaceAllUsesWith(Calloc);
2304 return true;
2305}
2306
2307bool DSEState::storeIsNoop(MemoryDef *Def, const Value *DefUO) {
2308 Instruction *DefI = Def->getMemoryInst();
2309 StoreInst *Store = dyn_cast<StoreInst>(DefI);
2310 MemSetInst *MemSet = dyn_cast<MemSetInst>(DefI);
2311 Constant *StoredConstant = nullptr;
2312 if (Store)
2313 StoredConstant = dyn_cast<Constant>(Store->getOperand(0));
2314 else if (MemSet)
2315 StoredConstant = dyn_cast<Constant>(MemSet->getValue());
2316 else
2317 return false;
2318
2319 if (!isRemovable(DefI))
2320 return false;
2321
2322 if (StoredConstant) {
2323 Constant *InitC =
2324 getInitialValueOfAllocation(DefUO, &TLI, StoredConstant->getType());
2325 // If the clobbering access is LiveOnEntry, no instructions between them
2326 // can modify the memory location.
2327 if (InitC && InitC == StoredConstant)
2328 return MSSA.isLiveOnEntryDef(
2329 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def, BatchAA));
2330 }
2331
2332 if (!Store)
2333 return false;
2334
2335 if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) {
2336 if (LoadI->getPointerOperand() == Store->getOperand(1)) {
2337 // Get the defining access for the load.
2338 auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess();
2339 // Fast path: the defining accesses are the same.
2340 if (LoadAccess == Def->getDefiningAccess())
2341 return true;
2342
2343 // Look through phi accesses. Recursively scan all phi accesses by
2344 // adding them to a worklist. Bail when we run into a memory def that
2345 // does not match LoadAccess.
2346 SetVector<MemoryAccess *> ToCheck;
2347 MemoryAccess *Current =
2348 MSSA.getWalker()->getClobberingMemoryAccess(Def, BatchAA);
2349 // We don't want to bail when we run into the store memory def. But,
2350 // the phi access may point to it. So, pretend like we've already
2351 // checked it.
2352 ToCheck.insert(Def);
2353 ToCheck.insert(Current);
2354 // Start at current (1) to simulate already having checked Def.
2355 for (unsigned I = 1; I < ToCheck.size(); ++I) {
2356 Current = ToCheck[I];
2357 if (auto PhiAccess = dyn_cast<MemoryPhi>(Current)) {
2358 // Check all the operands.
2359 for (auto &Use : PhiAccess->incoming_values())
2360 ToCheck.insert(cast<MemoryAccess>(&Use));
2361 continue;
2362 }
2363
2364 // If we found a memory def, bail. This happens when we have an
2365 // unrelated write in between an otherwise noop store.
2366 assert(isa<MemoryDef>(Current) && "Only MemoryDefs should reach here.");
2367 // TODO: Skip no alias MemoryDefs that have no aliasing reads.
2368 // We are searching for the definition of the store's destination.
2369 // So, if that is the same definition as the load, then this is a
2370 // noop. Otherwise, fail.
2371 if (LoadAccess != Current)
2372 return false;
2373 }
2374 return true;
2375 }
2376 }
2377
2378 return false;
2379}
2380
2381bool DSEState::removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL) {
2382 bool Changed = false;
2383 for (auto OI : IOL) {
2384 Instruction *DeadI = OI.first;
2385 MemoryLocation Loc = *getLocForWrite(DeadI);
2386 assert(isRemovable(DeadI) && "Expect only removable instruction");
2387
2388 const Value *Ptr = Loc.Ptr->stripPointerCasts();
2389 int64_t DeadStart = 0;
2390 uint64_t DeadSize = Loc.Size.getValue();
2391 GetPointerBaseWithConstantOffset(Ptr, DeadStart, DL);
2392 OverlapIntervalsTy &IntervalMap = OI.second;
2393 Changed |= tryToShortenEnd(DeadI, IntervalMap, DeadStart, DeadSize);
2394 if (IntervalMap.empty())
2395 continue;
2396 Changed |= tryToShortenBegin(DeadI, IntervalMap, DeadStart, DeadSize);
2397 }
2398 return Changed;
2399}
2400
2401bool DSEState::eliminateRedundantStoresOfExistingValues() {
2402 bool MadeChange = false;
2403 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs that write the "
2404 "already existing value\n");
2405 for (auto *Def : MemDefs) {
2406 if (SkipStores.contains(Def) || MSSA.isLiveOnEntryDef(Def))
2407 continue;
2408
2409 Instruction *DefInst = Def->getMemoryInst();
2410 auto MaybeDefLoc = getLocForWrite(DefInst);
2411 if (!MaybeDefLoc || !isRemovable(DefInst))
2412 continue;
2413
2414 MemoryDef *UpperDef;
2415 // To conserve compile-time, we avoid walking to the next clobbering def.
2416 // Instead, we just try to get the optimized access, if it exists. DSE
2417 // will try to optimize defs during the earlier traversal.
2418 if (Def->isOptimized())
2419 UpperDef = dyn_cast<MemoryDef>(Def->getOptimized());
2420 else
2421 UpperDef = dyn_cast<MemoryDef>(Def->getDefiningAccess());
2422 if (!UpperDef || MSSA.isLiveOnEntryDef(UpperDef))
2423 continue;
2424
2425 Instruction *UpperInst = UpperDef->getMemoryInst();
2426 auto IsRedundantStore = [&]() {
2427 // We don't care about differences in call attributes here.
2428 if (DefInst->isIdenticalToWhenDefined(UpperInst,
2429 /*IntersectAttrs=*/true))
2430 return true;
2431 if (auto *MemSetI = dyn_cast<MemSetInst>(UpperInst)) {
2432 if (auto *SI = dyn_cast<StoreInst>(DefInst)) {
2433 // MemSetInst must have a write location.
2434 auto UpperLoc = getLocForWrite(UpperInst);
2435 if (!UpperLoc)
2436 return false;
2437 int64_t InstWriteOffset = 0;
2438 int64_t DepWriteOffset = 0;
2439 auto OR = isOverwrite(UpperInst, DefInst, *UpperLoc, *MaybeDefLoc,
2440 InstWriteOffset, DepWriteOffset);
2441 Value *StoredByte = isBytewiseValue(SI->getValueOperand(), DL);
2442 return StoredByte && StoredByte == MemSetI->getOperand(1) &&
2443 OR == OW_Complete;
2444 }
2445 }
2446 return false;
2447 };
2448
2449 if (!IsRedundantStore() || isReadClobber(*MaybeDefLoc, DefInst))
2450 continue;
2451 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *DefInst
2452 << '\n');
2453 deleteDeadInstruction(DefInst);
2454 NumRedundantStores++;
2455 MadeChange = true;
2456 }
2457 return MadeChange;
2458}
2459
2461DSEState::getInitializesArgMemLoc(const Instruction *I) {
2462 const CallBase *CB = dyn_cast<CallBase>(I);
2463 if (!CB)
2464 return {};
2465
2466 // Collect aliasing arguments and their initializes ranges.
2467 SmallMapVector<Value *, SmallVector<ArgumentInitInfo, 2>, 2> Arguments;
2468 for (unsigned Idx = 0, Count = CB->arg_size(); Idx < Count; ++Idx) {
2469 Value *CurArg = CB->getArgOperand(Idx);
2470 if (!CurArg->getType()->isPointerTy())
2471 continue;
2472
2473 ConstantRangeList Inits;
2474 Attribute InitializesAttr = CB->getParamAttr(Idx, Attribute::Initializes);
2475 // initializes on byval arguments refers to the callee copy, not the
2476 // original memory the caller passed in.
2477 if (InitializesAttr.isValid() && !CB->isByValArgument(Idx))
2478 Inits = InitializesAttr.getValueAsConstantRangeList();
2479
2480 // Check whether "CurArg" could alias with global variables. We require
2481 // either it's function local and isn't captured before or the "CB" only
2482 // accesses arg or inaccessible mem.
2483 if (!Inits.empty() && !CB->onlyAccessesInaccessibleMemOrArgMem() &&
2484 !isFuncLocalAndNotCaptured(CurArg, CB, EA))
2485 Inits = ConstantRangeList();
2486
2487 // We don't perform incorrect DSE on unwind edges in the current function,
2488 // and use the "initializes" attribute to kill dead stores if:
2489 // - The call does not throw exceptions, "CB->doesNotThrow()".
2490 // - Or the callee parameter has "dead_on_unwind" attribute.
2491 // - Or the argument is invisible to caller on unwind, and there are no
2492 // unwind edges from this call in the current function (e.g. `CallInst`).
2493 bool IsDeadOrInvisibleOnUnwind =
2494 CB->paramHasAttr(Idx, Attribute::DeadOnUnwind) ||
2495 (isa<CallInst>(CB) && isInvisibleToCallerOnUnwind(CurArg));
2496 ArgumentInitInfo InitInfo{Idx, IsDeadOrInvisibleOnUnwind, Inits};
2497 bool FoundAliasing = false;
2498 for (auto &[Arg, AliasList] : Arguments) {
2499 auto AAR = BatchAA.alias(MemoryLocation::getBeforeOrAfter(Arg),
2501 if (AAR == AliasResult::NoAlias) {
2502 continue;
2503 } else if (AAR == AliasResult::MustAlias) {
2504 FoundAliasing = true;
2505 AliasList.push_back(InitInfo);
2506 } else {
2507 // For PartialAlias and MayAlias, there is an offset or may be an
2508 // unknown offset between the arguments and we insert an empty init
2509 // range to discard the entire initializes info while intersecting.
2510 FoundAliasing = true;
2511 AliasList.push_back(ArgumentInitInfo{Idx, IsDeadOrInvisibleOnUnwind,
2512 ConstantRangeList()});
2513 }
2514 }
2515 if (!FoundAliasing)
2516 Arguments[CurArg] = {InitInfo};
2517 }
2518
2520 for (const auto &[_, Args] : Arguments) {
2521 auto IntersectedRanges =
2523 if (IntersectedRanges.empty())
2524 continue;
2525
2526 for (const auto &Arg : Args) {
2527 for (const auto &Range : IntersectedRanges) {
2528 int64_t Start = Range.getLower().getSExtValue();
2529 int64_t End = Range.getUpper().getSExtValue();
2530 // For now, we only handle locations starting at offset 0.
2531 if (Start == 0)
2532 Locations.push_back(MemoryLocation(CB->getArgOperand(Arg.Idx),
2533 LocationSize::precise(End - Start),
2534 CB->getAAMetadata()));
2535 }
2536 }
2537 }
2538 return Locations;
2539}
2540
2541std::pair<bool, bool>
2542DSEState::eliminateDeadDefs(const MemoryLocationWrapper &KillingLocWrapper) {
2543 bool Changed = false;
2544 bool DeletedKillingLoc = false;
2545 unsigned ScanLimit = Opts.dse_memoryssa_scanlimit;
2546 unsigned WalkerStepLimit = Opts.dse_memoryssa_walklimit;
2547 unsigned PartialLimit = Opts.dse_memoryssa_partial_store_limit;
2548 // Worklist of MemoryAccesses that may be killed by
2549 // "KillingLocWrapper.MemDef".
2550 SmallSetVector<MemoryAccess *, 8> ToCheck;
2551 // Track MemoryAccesses that have been deleted in the loop below, so we can
2552 // skip them. Don't use SkipStores for this, which may contain reused
2553 // MemoryAccess addresses.
2554 SmallPtrSet<MemoryAccess *, 8> Deleted;
2555 [[maybe_unused]] unsigned OrigNumSkipStores = SkipStores.size();
2556 ToCheck.insert(KillingLocWrapper.MemDef->getDefiningAccess());
2557
2558 // Check if MemoryAccesses in the worklist are killed by
2559 // "KillingLocWrapper.MemDef".
2560 for (unsigned I = 0; I < ToCheck.size(); I++) {
2561 MemoryAccess *Current = ToCheck[I];
2562 if (Deleted.contains(Current))
2563 continue;
2564 std::optional<MemoryAccess *> MaybeDeadAccess = getDomMemoryDef(
2565 KillingLocWrapper.MemDef, Current, KillingLocWrapper.MemLoc,
2566 KillingLocWrapper.UnderlyingObject, ScanLimit, WalkerStepLimit,
2567 isMemTerminatorInst(KillingLocWrapper.DefInst), PartialLimit,
2568 KillingLocWrapper.DefByInitializesAttr);
2569
2570 if (!MaybeDeadAccess) {
2571 LLVM_DEBUG(dbgs() << " finished walk\n");
2572 continue;
2573 }
2574 MemoryAccess *DeadAccess = *MaybeDeadAccess;
2575 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DeadAccess);
2576 if (isa<MemoryPhi>(DeadAccess)) {
2577 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n");
2578 for (Value *V : cast<MemoryPhi>(DeadAccess)->incoming_values()) {
2579 MemoryAccess *IncomingAccess = cast<MemoryAccess>(V);
2580 BasicBlock *IncomingBlock = IncomingAccess->getBlock();
2581 BasicBlock *PhiBlock = DeadAccess->getBlock();
2582
2583 // We only consider incoming MemoryAccesses that come before the
2584 // MemoryPhi. Otherwise we could discover candidates that do not
2585 // strictly dominate our starting def.
2586 if (PostOrderNumbers[IncomingBlock] > PostOrderNumbers[PhiBlock])
2587 ToCheck.insert(IncomingAccess);
2588 }
2589 continue;
2590 }
2591 // We cannot apply the initializes attribute to DeadAccess/DeadDef.
2592 // It would incorrectly consider a call instruction as redundant store
2593 // and remove this call instruction.
2594 // TODO: this conflates the existence of a MemoryLocation with being able
2595 // to delete the instruction. Fix isRemovable() to consider calls with
2596 // side effects that cannot be removed, e.g. calls with the initializes
2597 // attribute, and remove getLocForInst(ConsiderInitializesAttr = false).
2598 MemoryDefWrapper DeadDefWrapper(
2599 cast<MemoryDef>(DeadAccess),
2600 getLocForInst(cast<MemoryDef>(DeadAccess)->getMemoryInst(),
2601 /*ConsiderInitializesAttr=*/false));
2602 assert(DeadDefWrapper.DefinedLocations.size() == 1);
2603 MemoryLocationWrapper &DeadLocWrapper =
2604 DeadDefWrapper.DefinedLocations.front();
2605 LLVM_DEBUG(dbgs() << " (" << *DeadLocWrapper.DefInst << ")\n");
2606 ToCheck.insert(DeadLocWrapper.MemDef->getDefiningAccess());
2607 NumGetDomMemoryDefPassed++;
2608
2609 if (!DebugCounter::shouldExecute(MemorySSACounter))
2610 continue;
2611 if (isMemTerminatorInst(KillingLocWrapper.DefInst)) {
2612 if (KillingLocWrapper.UnderlyingObject != DeadLocWrapper.UnderlyingObject)
2613 continue;
2614 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
2615 << *DeadLocWrapper.DefInst << "\n KILLER: "
2616 << *KillingLocWrapper.DefInst << '\n');
2617 deleteDeadInstruction(DeadLocWrapper.DefInst, &Deleted);
2618 ++NumFastStores;
2619 Changed = true;
2620 } else {
2621 // Check if DeadI overwrites KillingI.
2622 int64_t KillingOffset = 0;
2623 int64_t DeadOffset = 0;
2624 OverwriteResult OR =
2625 isOverwrite(KillingLocWrapper.DefInst, DeadLocWrapper.DefInst,
2626 KillingLocWrapper.MemLoc, DeadLocWrapper.MemLoc,
2627 KillingOffset, DeadOffset);
2628 if (OR == OW_MaybePartial) {
2629 auto &IOL = IOLs[DeadLocWrapper.DefInst->getParent()];
2630 OR = isPartialOverwrite(Opts, KillingLocWrapper.MemLoc,
2631 DeadLocWrapper.MemLoc, KillingOffset,
2632 DeadOffset, DeadLocWrapper.DefInst, IOL);
2633 }
2634 if (Opts.enable_dse_partial_store_merging &&
2635 OR == OW_PartialEarlierWithFullLater) {
2636 auto *DeadSI = dyn_cast<StoreInst>(DeadLocWrapper.DefInst);
2637 auto *KillingSI = dyn_cast<StoreInst>(KillingLocWrapper.DefInst);
2638 // We are re-using tryToMergePartialOverlappingStores, which requires
2639 // DeadSI to dominate KillingSI.
2640 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
2641 if (DeadSI && KillingSI && DT.dominates(DeadSI, KillingSI)) {
2642 if (Constant *Merged = tryToMergePartialOverlappingStores(
2643 KillingSI, DeadSI, KillingOffset, DeadOffset, DL, BatchAA,
2644 &DT)) {
2645
2646 // Update stored value of earlier store to merged constant.
2647 DeadSI->setOperand(0, Merged);
2648 ++NumModifiedStores;
2649 Changed = true;
2650 DeletedKillingLoc = true;
2651
2652 // Remove killing store and remove any outstanding overlap
2653 // intervals for the updated store.
2654 deleteDeadInstruction(KillingSI, &Deleted);
2655 auto I = IOLs.find(DeadSI->getParent());
2656 if (I != IOLs.end())
2657 I->second.erase(DeadSI);
2658 break;
2659 }
2660 }
2661 }
2662 if (OR == OW_Complete) {
2663 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
2664 << *DeadLocWrapper.DefInst << "\n KILLER: "
2665 << *KillingLocWrapper.DefInst << '\n');
2666 deleteDeadInstruction(DeadLocWrapper.DefInst, &Deleted);
2667 ++NumFastStores;
2668 Changed = true;
2669 }
2670 }
2671 }
2672
2673 assert(SkipStores.size() - OrigNumSkipStores == Deleted.size() &&
2674 "SkipStores and Deleted out of sync?");
2675
2676 return {Changed, DeletedKillingLoc};
2677}
2678
2679bool DSEState::eliminateDeadDefs(const MemoryDefWrapper &KillingDefWrapper) {
2680 if (KillingDefWrapper.DefinedLocations.empty()) {
2681 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
2682 << *KillingDefWrapper.DefInst << "\n");
2683 return false;
2684 }
2685
2686 bool MadeChange = false;
2687 for (auto &KillingLocWrapper : KillingDefWrapper.DefinedLocations) {
2688 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
2689 << *KillingLocWrapper.MemDef << " ("
2690 << *KillingLocWrapper.DefInst << ")\n");
2691 auto [Changed, DeletedKillingLoc] = eliminateDeadDefs(KillingLocWrapper);
2692 MadeChange |= Changed;
2693
2694 // Check if the store is a no-op.
2695 if (!DeletedKillingLoc && storeIsNoop(KillingLocWrapper.MemDef,
2696 KillingLocWrapper.UnderlyingObject)) {
2697 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: "
2698 << *KillingLocWrapper.DefInst << '\n');
2699 deleteDeadInstruction(KillingLocWrapper.DefInst);
2700 NumRedundantStores++;
2701 MadeChange = true;
2702 continue;
2703 }
2704 // Can we form a calloc from a memset/malloc pair?
2705 if (!DeletedKillingLoc &&
2706 tryFoldIntoCalloc(KillingLocWrapper.MemDef,
2707 KillingLocWrapper.UnderlyingObject)) {
2708 LLVM_DEBUG(dbgs() << "DSE: Remove memset after forming calloc:\n"
2709 << " DEAD: " << *KillingLocWrapper.DefInst << '\n');
2710 deleteDeadInstruction(KillingLocWrapper.DefInst);
2711 MadeChange = true;
2712 continue;
2713 }
2714 }
2715 return MadeChange;
2716}
2717
2720 const TargetLibraryInfo &TLI,
2721 const CycleInfo &CI) {
2722 const ScalarOptions &Opts = ScalarOptions::Global;
2723 bool MadeChange = false;
2724 DSEState State(Opts, F, AA, MSSA, DT, PDT, TLI, CI);
2725 // For each store:
2726 for (unsigned I = 0; I < State.MemDefs.size(); I++) {
2727 MemoryDef *KillingDef = State.MemDefs[I];
2728 if (State.SkipStores.count(KillingDef))
2729 continue;
2730
2731 MemoryDefWrapper KillingDefWrapper(
2732 KillingDef,
2733 State.getLocForInst(KillingDef->getMemoryInst(),
2734 Opts.enable_dse_initializes_attr_improvement));
2735 MadeChange |= State.eliminateDeadDefs(KillingDefWrapper);
2736 }
2737
2738 if (Opts.enable_dse_partial_overwrite_tracking)
2739 for (auto &KV : State.IOLs)
2740 MadeChange |= State.removePartiallyOverlappedStores(KV.second);
2741
2742 MadeChange |= State.eliminateRedundantStoresOfExistingValues();
2743 MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2744 MadeChange |= State.eliminateRedundantStoresViaDominatingConditions();
2745
2746 while (!State.ToRemove.empty()) {
2747 Instruction *DeadInst = State.ToRemove.pop_back_val();
2748 DeadInst->eraseFromParent();
2749 }
2750
2751 return MadeChange;
2752}
2753
2754//===----------------------------------------------------------------------===//
2755// DSE Pass
2756//===----------------------------------------------------------------------===//
2761 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2764
2765 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, CI);
2766
2767#ifdef LLVM_ENABLE_STATS
2769 for (auto &I : instructions(F))
2770 NumRemainingStores += isa<StoreInst>(&I);
2771#endif
2772
2773 if (!Changed)
2774 return PreservedAnalyses::all();
2775
2779 return PA;
2780}
2781
2782namespace {
2783
2784/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2785class DSELegacyPass : public FunctionPass {
2786public:
2787 static char ID; // Pass identification, replacement for typeid
2788
2789 DSELegacyPass() : FunctionPass(ID) {
2791 }
2792
2793 bool runOnFunction(Function &F) override {
2794 if (skipFunction(F))
2795 return false;
2796
2797 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2798 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2799 const TargetLibraryInfo &TLI =
2800 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2801 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2802 PostDominatorTree &PDT =
2803 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2804 CycleInfo &CI = getAnalysis<CycleInfoWrapperPass>().getResult();
2805
2806 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, CI);
2807
2808#ifdef LLVM_ENABLE_STATS
2810 for (auto &I : instructions(F))
2811 NumRemainingStores += isa<StoreInst>(&I);
2812#endif
2813
2814 return Changed;
2815 }
2816
2817 void getAnalysisUsage(AnalysisUsage &AU) const override {
2818 AU.setPreservesCFG();
2819 AU.addRequired<AAResultsWrapperPass>();
2820 AU.addRequired<TargetLibraryInfoWrapperPass>();
2821 AU.addPreserved<GlobalsAAWrapperPass>();
2822 AU.addRequired<DominatorTreeWrapperPass>();
2823 AU.addRequired<PostDominatorTreeWrapperPass>();
2824 AU.addRequired<MemorySSAWrapperPass>();
2825 AU.addPreserved<MemorySSAWrapperPass>();
2826 AU.addRequired<CycleInfoWrapperPass>();
2827 AU.addRequired<AssumptionCacheTracker>();
2828 }
2829};
2830
2831} // end anonymous namespace
2832
2833char DSELegacyPass::ID = 0;
2834
2835INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2836 false)
2846INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2847 false)
2848
2850 return new DSELegacyPass();
2851}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Lower Kernel Arguments
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
DXIL Forward Handle Accesses
static void shortenAssignment(Instruction *Inst, Value *OriginalDest, uint64_t OldSizeInBits, uint64_t NewSizeInBits, bool IsOverwriteEnd)
static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, PostDominatorTree &PDT, const TargetLibraryInfo &TLI, const CycleInfo &CI)
MapVector< Instruction *, OverlapIntervalsTy > InstOverlapIntervalsTy
static bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller)
static bool isShortenableAtTheEnd(Instruction *I)
Returns true if the end of this instruction can be safely shortened in length.
static bool isNoopIntrinsic(Instruction *I)
static ConstantRangeList getIntersectedInitRangeList(ArrayRef< ArgumentInitInfo > Args, bool CallHasNoUnwindAttr)
static bool tryToShortenBegin(Instruction *DeadI, OverlapIntervalsTy &IntervalMap, int64_t &DeadStart, uint64_t &DeadSize)
std::map< int64_t, int64_t > OverlapIntervalsTy
static void pushMemUses(MemoryAccess *Acc, SmallVectorImpl< MemoryAccess * > &WorkList, SmallPtrSetImpl< MemoryAccess * > &Visited)
static bool isShortenableAtTheBeginning(Instruction *I)
Returns true if the beginning of this instruction can be safely shortened in length.
static Constant * tryToMergePartialOverlappingStores(StoreInst *KillingI, StoreInst *DeadI, int64_t KillingOffset, int64_t DeadOffset, const DataLayout &DL, BatchAAResults &AA, DominatorTree *DT)
static OverwriteResult isPartialOverwrite(const ScalarOptions &Opts, const MemoryLocation &KillingLoc, const MemoryLocation &DeadLoc, int64_t KillingOff, int64_t DeadOff, Instruction *DeadI, InstOverlapIntervalsTy &IOL)
Return 'OW_Complete' if a store to the 'KillingLoc' location completely overwrites a store to the 'De...
static bool memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, BatchAAResults &AA, const DataLayout &DL, DominatorTree *DT)
Returns true if the memory which is accessed by the second instruction is not modified between the fi...
static OverwriteResult isMaskedStoreOverwrite(const Instruction *KillingI, const Instruction *DeadI, BatchAAResults &AA)
Check if two instruction are masked stores that completely overwrite one another.
static bool tryToShorten(Instruction *DeadI, int64_t &DeadStart, uint64_t &DeadSize, int64_t KillingStart, uint64_t KillingSize, bool IsOverwriteEnd)
static bool isFuncLocalAndNotCaptured(Value *Arg, const CallBase *CB, EarliestEscapeAnalysis &EA)
static std::optional< TypeSize > getPointerSize(const Value *V, const DataLayout &DL, const TargetLibraryInfo &TLI, const Function *F)
static bool tryToShortenEnd(Instruction *DeadI, OverlapIntervalsTy &IntervalMap, int64_t &DeadStart, uint64_t &DeadSize)
static void adjustArgAttributes(AnyMemIntrinsic *Intrinsic, unsigned ArgNo, uint64_t PtrOffset)
Update the attributes given that a memory access is updated (the dereferenced pointer could be moved ...
static bool hasInitializesAttr(Instruction *I)
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static void deleteDeadInstruction(Instruction *I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
#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
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
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 bool VisitNode(MachineDomTreeNode *Node, Register TLSBaseAddrReg)
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
constexpr int32_t getOffset() const
constexpr bool hasOffset() const
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
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An immutable pass that tracks lazily created AssumptionCache objects.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM_ABI ArrayRef< ConstantRange > getValueAsConstantRangeList() const
Return the attribute's value as a ConstantRange array.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
LLVM_ABI bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
LLVM_ABI Value * getArgOperandWithAttribute(Attribute::AttrKind Kind) const
If one of the arguments has the specified attribute, returns its operand value.
unsigned arg_size() const
This class represents a list of constant ranges.
bool empty() const
Return true if this list contains no members.
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
Analysis pass which computes a CycleInfo.
Legacy analysis pass which computes a CycleInfo.
static DIAssignID * getDistinct(LLVMContext &Context)
DbgVariableFragmentInfo FragmentInfo
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Record of a variable value-assignment, aka a non instruction representation of the dbg....
static bool shouldExecute(CounterInfo &Counter)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
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.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
iterator_range< root_iterator > roots()
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Context-sensitive CaptureAnalysis provider, which computes and caches the earliest common dominator c...
void removeInstruction(Instruction *I)
CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) override
Return how Object may be captured before instruction I, considering only provenance captures.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:794
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Legacy wrapper pass to provide the GlobalsAAResult object.
bool isEquality() const
Return true if this predicate is either EQ or NE.
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 bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
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 bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
const_iterator begin() const
bool empty() const
empty - Return true when no intervals are mapped.
const_iterator end() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:71
bool hasValue() const
static LocationSize precise(uint64_t Value)
bool isScalable() const
TypeSize getValue() const
bool isPrecise() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
Value * getLength() const
Value * getValue() const
BasicBlock * getBlock() const
Definition MemorySSA.h:162
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:371
void setOptimized(MemoryAccess *MA)
Definition MemorySSA.h:392
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
MemoryLocation getWithNewPtr(const Value *NewPtr) const
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
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
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:765
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
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
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:260
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition MemorySSA.h:257
PHITransAddr - An address value which tracks and handles phi translation.
LLVM_ABI Value * translateValue(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree *DT, bool MustDominate)
translateValue - PHI translate the current address up the CFG from CurBB to Pred, updating our state ...
LLVM_ABI bool isPotentiallyPHITranslatable() const
isPotentiallyPHITranslatable - If this needs PHI translation, return true if we have some hope of doi...
bool needsPHITranslationFromBlock(BasicBlock *BB) const
needsPHITranslationFromBlock - Return true if moving from the specified BasicBlock to its predecessor...
Value * getAddr() const
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
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
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Value * getValueOperand()
bool isUnordered() const
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
iterator_range< use_iterator > uses()
Definition Value.h:382
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto m_Value()
Match an arbitrary value and ignore it.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI bool calculateFragmentIntersect(const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const DbgVariableRecord *DVRAssign, std::optional< DIExpression::FragmentInfo > &Result)
Calculate the fragment of the variable in DAI covered from (Dest + SliceOffsetInBits) to to (Dest + S...
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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
LLVM_ABI void initializeDSELegacyPassPass(PassRegistry &)
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
@ Uninitialized
Definition Threading.h:60
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
AllocFnKind
Definition Attributes.h:54
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
@ Store
The extracted value is stored (ExtractElement only).
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
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
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
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 getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:942
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
LLVM_ABI Value * emitCalloc(Value *Num, Value *Size, IRBuilderBase &B, const TargetLibraryInfo &TLI, unsigned AddrSpace)
Emit a call to the calloc function.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI FunctionPass * createDeadStoreEliminationPass()
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
auto predecessors(const MachineBasicBlock *BB)
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.