LLVM 24.0.0git
MemoryBuiltins.cpp
Go to the documentation of this file.
1//===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions identifies calls to builtin functions that allocate
10// or free memory.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/Argument.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Operator.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/Value.h"
40#include "llvm/Support/Debug.h"
43#include <cassert>
44#include <cstdint>
45#include <iterator>
46#include <numeric>
47#include <optional>
48#include <utility>
49
50using namespace llvm;
51
52#define DEBUG_TYPE "memory-builtins"
53
54namespace llvm {
56}
57
59 "object-size-offset-visitor-max-visit-instructions",
60 cl::desc("Maximum number of instructions for ObjectSizeOffsetVisitor to "
61 "look at"),
62 cl::init(100));
63
64static bool isStrNDupLike(LibFunc LF) {
65 return LF == LibFunc_strndup || LF == LibFunc_dunder_strndup;
66}
67
68static bool isStrDupLike(LibFunc LF) {
69 return LF == LibFunc_strdup || LF == LibFunc_dunder_strdup ||
70 isStrNDupLike(LF);
71}
72
73static std::pair<Value *, Value *> getAllocSizePair(const CallBase *CB) {
74 Attribute Attr = CB->getFnAttr(Attribute::AllocSize);
75 if (!Attr.isValid())
76 return {nullptr, nullptr};
77
78 std::pair<unsigned, std::optional<unsigned>> Args = Attr.getAllocSizeArgs();
79 Value *FirstArg = CB->getArgOperand(Args.first);
80 Value *SecondArg = Args.second ? CB->getArgOperand(*Args.second) : nullptr;
81 return {FirstArg, SecondArg};
82}
83
85 if (const auto *CB = dyn_cast<CallBase>(V)) {
86 Attribute Attr = CB->getFnAttr(Attribute::AllocKind);
87 if (Attr.isValid())
88 return AllocFnKind(Attr.getValueAsInt());
89 }
91}
92
94 return F->getAttributes().getAllocKind();
95}
96
97static bool checkFnAllocKind(const Value *V, AllocFnKind Wanted) {
98 return (getAllocFnKind(V) & Wanted) != AllocFnKind::Unknown;
99}
100
101static bool checkFnAllocKind(const Function *F, AllocFnKind Wanted) {
102 return (getAllocFnKind(F) & Wanted) != AllocFnKind::Unknown;
103}
104
105/// Tests if a value is a call or invoke to a library function that
106/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
107/// like).
109 // Allocation calls must return ptr. Exit early if this doesn't.
110 if (!V->getType()->isPointerTy())
111 return false;
113}
114
115/// Tests if a value is a call or invoke to a library function that
116/// allocates memory (either malloc, calloc, or strdup like).
118 // Allocation calls must return ptr. Exit early if this doesn't.
119 if (!V->getType()->isPointerTy())
120 return false;
122}
123
124/// Tests if a functions is a call or invoke to a library function that
125/// reallocates memory (e.g., realloc).
129
132 return CB->getArgOperandWithAttribute(Attribute::AllocatedPointer);
133 return nullptr;
134}
135
137 // Note: Removability is highly dependent on the source language. For
138 // example, recent C++ requires direct calls to the global allocation
139 // [basic.stc.dynamic.allocation] to be observable unless part of a new
140 // expression [expr.new paragraph 13].
141
142 // Historically we've treated the C family allocation routines and operator
143 // new as removable
144 return isAllocLikeFn(CB);
145}
146
148 return V->getArgOperandWithAttribute(Attribute::AllocAlign);
149}
150
151/// When we're compiling N-bit code, and the user uses parameters that are
152/// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
153/// trouble with APInt size issues. This function handles resizing + overflow
154/// checks for us. Check and zext or trunc \p I depending on IntTyBits and
155/// I's value.
156static bool checkedZextOrTrunc(APInt &I, unsigned IntTyBits) {
157 // More bits than we can handle. Checking the bit width isn't necessary, but
158 // it's faster than checking active bits, and should give `false` in the
159 // vast majority of cases.
160 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
161 return false;
162 if (I.getBitWidth() != IntTyBits)
163 I = I.zextOrTrunc(IntTyBits);
164 return true;
165}
166
167std::optional<APInt>
169 function_ref<const Value *(const Value *)> Mapper) {
170 // Get the index type for this address space, results and intermediate
171 // computations are performed at that width.
172 auto &DL = CB->getDataLayout();
173 const unsigned IntTyBits = DL.getIndexTypeSizeInBits(CB->getType());
174
175 // Handle allocsize attribute.
176 auto [FirstArg, SecondArg] = getAllocSizePair(CB);
177 if (FirstArg) {
178 const ConstantInt *Arg = dyn_cast<ConstantInt>(Mapper(FirstArg));
179 if (!Arg)
180 return std::nullopt;
181
182 APInt Size = Arg->getValue();
183 if (!checkedZextOrTrunc(Size, IntTyBits))
184 return std::nullopt;
185
186 // Size is determined by just 1 parameter.
187 if (!SecondArg)
188 return Size;
189
190 Arg = dyn_cast<ConstantInt>(Mapper(SecondArg));
191 if (!Arg)
192 return std::nullopt;
193
194 APInt NumElems = Arg->getValue();
195 if (!checkedZextOrTrunc(NumElems, IntTyBits))
196 return std::nullopt;
197
198 bool Overflow;
199 Size = Size.umul_ov(NumElems, Overflow);
200 if (Overflow)
201 return std::nullopt;
202 return Size;
203 }
204
205 // Handle strdup-like functions separately.
206 if (!TLI)
207 return std::nullopt;
208
209 LibFunc LF = TLI->getLibFunc(*CB);
210 if (!isStrDupLike(LF))
211 return std::nullopt;
212
213 APInt Size(IntTyBits, GetStringLength(Mapper(CB->getArgOperand(0))));
214 if (!Size)
215 return std::nullopt;
216
217 // Strndup limits strlen.
218 if (isStrNDupLike(LF)) {
219 const ConstantInt *Arg =
220 dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(1)));
221 if (!Arg)
222 return std::nullopt;
223
224 APInt MaxSize = Arg->getValue().zext(IntTyBits);
225 if (Size.ugt(MaxSize))
226 Size = MaxSize + 1;
227 }
228 return Size;
229}
230
232 if (isa<AllocaInst>(V))
233 return UndefValue::get(Ty);
234
235 auto *Alloc = dyn_cast<CallBase>(V);
236 if (!Alloc)
237 return nullptr;
238
241 return UndefValue::get(Ty);
243 return Constant::getNullValue(Ty);
244
245 return nullptr;
246}
247
248std::optional<StringRef> llvm::getAllocationFamily(const Value *I) {
251 Attribute Attr = cast<CallBase>(I)->getFnAttr("alloc-family");
252 if (Attr.isValid())
253 return Attr.getValueAsString();
254 }
255 return std::nullopt;
256}
257
261
263 // Exit early for functions which don't return void or an integer. The
264 // allockind("free") attribute requires this, and it's cheaper to check than
265 // the attribute.
266 if (!CB->getType()->isVoidTy() && !CB->getType()->isIntegerTy())
267 return nullptr;
268
270 return CB->getArgOperandWithAttribute(Attribute::AllocatedPointer);
271
272 return nullptr;
273}
274
277 return nullptr;
278
279 if (!V->getType()->isIntegerTy())
280 return nullptr;
281
282 // LangRef requires that 0 be returned on free(alloc()).
283 return Constant::getNullValue(V->getType());
284}
285
286//===----------------------------------------------------------------------===//
287// Utility functions to compute size of objects.
288//
290 APInt Size = Data.Size;
291 APInt Offset = Data.Offset;
292
293 if (Offset.isNegative() || Size.ult(Offset))
294 return APInt::getZero(Size.getBitWidth());
295
296 return Size - Offset;
297}
298
299/// Compute the size of the object pointed by Ptr. Returns true and the
300/// object size in Size if successful, and false otherwise.
301/// If RoundToAlign is true, then Size is rounded up to the alignment of
302/// allocas, byval arguments, and global variables.
303bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
304 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
305 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
306 SizeOffsetAPInt Data = Visitor.compute(const_cast<Value *>(Ptr));
307 if (!Data.bothKnown())
308 return false;
309
311 return true;
312}
313
314std::optional<TypeSize> llvm::getBaseObjectSize(const Value *Ptr,
315 const DataLayout &DL,
316 const TargetLibraryInfo *TLI,
317 ObjectSizeOpts Opts) {
319 "Other modes are currently not supported");
320
321 auto Align = [&](TypeSize Size, MaybeAlign Alignment) {
322 if (Opts.RoundToAlign && Alignment && !Size.isScalable())
323 return TypeSize::getFixed(alignTo(Size.getFixedValue(), *Alignment));
324 return Size;
325 };
326
327 if (isa<UndefValue>(Ptr))
328 return TypeSize::getZero();
329
330 if (isa<ConstantPointerNull>(Ptr)) {
332 return std::nullopt;
333 return TypeSize::getZero();
334 }
335
336 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
337 if (!GV->getValueType()->isSized() || GV->hasExternalWeakLinkage() ||
338 !GV->hasInitializer() || GV->isInterposable())
339 return std::nullopt;
340 return Align(TypeSize::getFixed(GV->getGlobalSize(DL)), GV->getAlign());
341 }
342
343 if (auto *A = dyn_cast<Argument>(Ptr)) {
344 Type *MemoryTy = A->getPointeeInMemoryValueType();
345 if (!MemoryTy || !MemoryTy->isSized())
346 return std::nullopt;
347 return Align(DL.getTypeAllocSize(MemoryTy), A->getParamAlign());
348 }
349
350 if (auto *AI = dyn_cast<AllocaInst>(Ptr)) {
351 if (std::optional<TypeSize> Size = AI->getAllocationSize(DL))
352 return Align(*Size, AI->getAlign());
353 return std::nullopt;
354 }
355
356 if (auto *CB = dyn_cast<CallBase>(Ptr)) {
357 if (std::optional<APInt> Size = getAllocSize(CB, TLI)) {
358 if (std::optional<uint64_t> ZExtSize = Size->tryZExtValue())
359 return TypeSize::getFixed(*ZExtSize);
360 }
361 return std::nullopt;
362 }
363
364 return std::nullopt;
365}
366
368 const DataLayout &DL,
369 const TargetLibraryInfo *TLI,
370 bool MustSucceed) {
371 return lowerObjectSizeCall(ObjectSize, DL, TLI, /*AAResults=*/nullptr,
372 MustSucceed);
373}
374
376 IntrinsicInst *ObjectSize, const DataLayout &DL,
377 const TargetLibraryInfo *TLI, AAResults *AA, bool MustSucceed,
378 SmallVectorImpl<Instruction *> *InsertedInstructions) {
379 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
380 "ObjectSize must be a call to llvm.objectsize!");
381
382 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
383 ObjectSizeOpts EvalOptions;
384 EvalOptions.AA = AA;
385
386 // Unless we have to fold this to something, try to be as accurate as
387 // possible.
388 if (MustSucceed)
389 EvalOptions.EvalMode =
391 else
393
394 EvalOptions.NullIsUnknownSize =
395 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
396
397 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
398 bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
399 if (StaticOnly) {
400 // FIXME: Does it make sense to just return a failure value if the size
401 // won't fit in the output and `!MustSucceed`?
402 uint64_t Size;
403 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI,
404 EvalOptions) &&
405 isUIntN(ResultType->getBitWidth(), Size))
406 return ConstantInt::get(ResultType, Size);
407 } else {
408 ObjectSizeOffsetEvaluator Eval(*ObjectSize->getModule(), TLI, EvalOptions);
409 SizeOffsetValue SizeOffsetPair = Eval.compute(ObjectSize->getArgOperand(0));
410
411 if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
413 ObjectSize->getIterator(), TargetFolder(DL),
415 if (InsertedInstructions)
416 InsertedInstructions->push_back(I);
417 }));
418
419 Value *Size = SizeOffsetPair.Size;
420 Value *Offset = SizeOffsetPair.Offset;
421
422 // If we've outside the end of the object, then we can always access
423 // exactly 0 bytes.
424 Value *ResultSize = Builder.CreateSub(Size, Offset);
425 Value *UseZero = Builder.CreateICmpULT(Size, Offset);
426 ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
427 Value *Ret = Builder.CreateSelect(
428 UseZero, ConstantInt::get(ResultType, 0), ResultSize);
429
430 // The non-constant size expression cannot evaluate to -1.
432 Builder.CreateAssumption(Builder.CreateICmpNE(
433 Ret, ConstantInt::getAllOnesValue(ResultType)));
434
435 return Ret;
436 }
437 }
438
439 if (!MustSucceed)
440 return nullptr;
441
442 return MaxVal ? Constant::getAllOnesValue(ResultType)
443 : Constant::getNullValue(ResultType);
444}
445
446STATISTIC(ObjectVisitorArgument,
447 "Number of arguments with unsolved size and offset");
448STATISTIC(ObjectVisitorLoad,
449 "Number of load instructions with unsolved size and offset");
450
451static std::optional<APInt>
453 std::optional<APInt> RHS,
454 ObjectSizeOpts::Mode EvalMode) {
455 if (!LHS || !RHS)
456 return std::nullopt;
457 if (EvalMode == ObjectSizeOpts::Mode::Max)
458 return LHS->sge(*RHS) ? *LHS : *RHS;
459 return LHS->sle(*RHS) ? *LHS : *RHS;
460}
461
462static std::optional<APInt> aggregatePossibleConstantValuesImpl(
463 const Value *V, ObjectSizeOpts::Mode EvalMode, unsigned BitWidth,
464 unsigned RecursionDepth) {
465 constexpr unsigned MaxRecursionDepth = 4;
466 if (RecursionDepth == MaxRecursionDepth)
467 return std::nullopt;
468
469 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
470 return CI->getValue().sextOrTrunc(BitWidth);
471 } else if (const auto *SI = dyn_cast<SelectInst>(V)) {
473 aggregatePossibleConstantValuesImpl(SI->getTrueValue(), EvalMode,
474 BitWidth, RecursionDepth + 1),
475 aggregatePossibleConstantValuesImpl(SI->getFalseValue(), EvalMode,
476 BitWidth, RecursionDepth + 1),
477 EvalMode);
478 } else if (const auto *PN = dyn_cast<PHINode>(V)) {
479 unsigned Count = PN->getNumIncomingValues();
480 if (Count == 0)
481 return std::nullopt;
483 PN->getIncomingValue(0), EvalMode, BitWidth, RecursionDepth + 1);
484 for (unsigned I = 1; Acc && I < Count; ++I) {
486 PN->getIncomingValue(I), EvalMode, BitWidth, RecursionDepth + 1);
487 Acc = combinePossibleConstantValues(Acc, Tmp, EvalMode);
488 }
489 return Acc;
490 }
491
492 return std::nullopt;
493}
494
495static std::optional<APInt>
497 unsigned BitWidth) {
498 if (auto *CI = dyn_cast<ConstantInt>(V))
499 return CI->getValue().sextOrTrunc(BitWidth);
500
501 if (EvalMode != ObjectSizeOpts::Mode::Min &&
502 EvalMode != ObjectSizeOpts::Mode::Max)
503 return std::nullopt;
504
505 // Not using computeConstantRange here because we cannot guarantee it's not
506 // doing optimization based on UB which we want to avoid when expanding
507 // __builtin_object_size.
508 return aggregatePossibleConstantValuesImpl(V, EvalMode, BitWidth, 0u);
509}
510
511/// Align \p Size according to \p Alignment. If \p Size is greater than
512/// getSignedMaxValue(), set it as unknown as we can only represent signed value
513/// in OffsetSpan.
514APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
515 if (Options.RoundToAlign && Alignment)
516 Size = APInt(IntTyBits, alignTo(Size.getZExtValue(), *Alignment));
517
518 return Size.isNegative() ? APInt() : Size;
519}
520
522 const TargetLibraryInfo *TLI,
524 ObjectSizeOpts Options)
525 : DL(DL), TLI(TLI), Options(Options) {
526 // Pointer size must be rechecked for each object visited since it could have
527 // a different address space.
528}
529
531 InstructionsVisited = 0;
532 OffsetSpan Span = computeImpl(V);
533
534 // In ExactSizeFromOffset mode, we don't care about the Before Field, so allow
535 // us to overwrite it if needs be.
536 if (Span.knownAfter() && !Span.knownBefore() &&
538 Span.Before = APInt::getZero(Span.After.getBitWidth());
539
540 if (!Span.bothKnown())
541 return {};
542
543 return {Span.Before + Span.After, Span.Before};
544}
545
546OffsetSpan ObjectSizeOffsetVisitor::computeImpl(Value *V) {
547 unsigned InitialIntTyBits = DL.getIndexTypeSizeInBits(V->getType());
548
549 // Stripping pointer casts can strip address space casts which can change the
550 // index type size. The invariant is that we use the value type to determine
551 // the index type size and if we stripped address space casts we have to
552 // readjust the APInt as we pass it upwards in order for the APInt to match
553 // the type the caller passed in.
554 APInt Offset(InitialIntTyBits, 0);
555 V = V->stripAndAccumulateConstantOffsets(
556 DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
557
558 // Give it another try with approximated analysis. We don't start with this
559 // one because stripAndAccumulateConstantOffsets behaves differently wrt.
560 // overflows if we provide an external Analysis.
561 if ((Options.EvalMode == ObjectSizeOpts::Mode::Min ||
562 Options.EvalMode == ObjectSizeOpts::Mode::Max) &&
563 isa<GEPOperator>(V)) {
564 // External Analysis used to compute the Min/Max value of individual Offsets
565 // within a GEP.
566 ObjectSizeOpts::Mode EvalMode =
570 // For a GEPOperator the indices are first converted to offsets in the
571 // pointer’s index type, so we need to provide the index type to make sure
572 // the min/max operations are performed in correct type.
573 unsigned IdxTyBits = DL.getIndexTypeSizeInBits(V->getType());
574 auto OffsetRangeAnalysis = [EvalMode, IdxTyBits](Value &VOffset,
575 APInt &Offset) {
576 if (auto PossibleOffset =
577 aggregatePossibleConstantValues(&VOffset, EvalMode, IdxTyBits)) {
578 Offset = *PossibleOffset;
579 return true;
580 }
581 return false;
582 };
583
584 V = V->stripAndAccumulateConstantOffsets(
585 DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true,
586 /*ExternalAnalysis=*/OffsetRangeAnalysis);
587 }
588
589 // Later we use the index type size and zero but it will match the type of the
590 // value that is passed to computeImpl.
591 IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
592 Zero = APInt::getZero(IntTyBits);
593 OffsetSpan ORT = computeValue(V);
594
595 bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
596 if (!IndexTypeSizeChanged && Offset.isZero())
597 return ORT;
598
599 // We stripped an address space cast that changed the index type size or we
600 // accumulated some constant offset (or both). Readjust the bit width to match
601 // the argument index type size and apply the offset, as required.
602 if (IndexTypeSizeChanged) {
603 if (ORT.knownBefore() &&
604 !::checkedZextOrTrunc(ORT.Before, InitialIntTyBits))
605 ORT.Before = APInt();
606 if (ORT.knownAfter() && !::checkedZextOrTrunc(ORT.After, InitialIntTyBits))
607 ORT.After = APInt();
608 }
609 // If the computed bound is "unknown" we cannot add the stripped offset.
610 if (ORT.knownBefore()) {
611 bool Overflow;
612 ORT.Before = ORT.Before.sadd_ov(Offset, Overflow);
613 if (Overflow)
614 ORT.Before = APInt();
615 }
616 if (ORT.knownAfter()) {
617 bool Overflow;
618 ORT.After = ORT.After.ssub_ov(Offset, Overflow);
619 if (Overflow)
620 ORT.After = APInt();
621 }
622
623 // We end up pointing on a location that's outside of the original object.
624 if (ORT.knownBefore() && ORT.Before.isNegative()) {
625 // This means that we *may* be accessing memory before the allocation.
626 // Conservatively return an unknown size.
627 //
628 // TODO: working with ranges instead of value would make it possible to take
629 // a better decision.
630 if (Options.EvalMode == ObjectSizeOpts::Mode::Min ||
631 Options.EvalMode == ObjectSizeOpts::Mode::Max) {
632 return ObjectSizeOffsetVisitor::unknown();
633 }
634 // Otherwise it's fine, caller can handle negative offset.
635 }
636 return ORT;
637}
638
639OffsetSpan ObjectSizeOffsetVisitor::computeValue(Value *V) {
640 if (Instruction *I = dyn_cast<Instruction>(V)) {
641 // If we have already seen this instruction, bail out. Cycles can happen in
642 // unreachable code after constant propagation.
643 auto P = SeenInsts.try_emplace(I, ObjectSizeOffsetVisitor::unknown());
644 if (!P.second)
645 return P.first->second;
646 ++InstructionsVisited;
647 if (InstructionsVisited > ObjectSizeOffsetVisitorMaxVisitInstructions)
648 return ObjectSizeOffsetVisitor::unknown();
649 OffsetSpan Res = visit(*I);
650 // Cache the result for later visits. If we happened to visit this during
651 // the above recursion, we would consider it unknown until now.
652 SeenInsts[I] = Res;
653 return Res;
654 }
655 if (Argument *A = dyn_cast<Argument>(V))
656 return visitArgument(*A);
657 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
659 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
660 return visitGlobalAlias(*GA);
661 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
662 return visitGlobalVariable(*GV);
663 if (UndefValue *UV = dyn_cast<UndefValue>(V))
664 return visitUndefValue(*UV);
665
666 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
667 << *V << '\n');
668 return ObjectSizeOffsetVisitor::unknown();
669}
670
671bool ObjectSizeOffsetVisitor::checkedZextOrTrunc(APInt &I) {
672 return ::checkedZextOrTrunc(I, IntTyBits);
673}
674
676 TypeSize ElemSize = I.getAllocationBaseSize(DL);
677 if (ElemSize.isScalable() && Options.EvalMode != ObjectSizeOpts::Mode::Min)
678 return ObjectSizeOffsetVisitor::unknown();
679 if (!isUIntN(IntTyBits, ElemSize.getKnownMinValue()))
680 return ObjectSizeOffsetVisitor::unknown();
681 APInt Size(IntTyBits, ElemSize.getKnownMinValue());
682
683 if (!I.isArrayAllocation())
684 return OffsetSpan(Zero, align(Size, I.getAlign()));
685
686 Value *ArraySize = I.getArraySize();
687 if (auto PossibleSize = aggregatePossibleConstantValues(
688 ArraySize, Options.EvalMode,
689 ArraySize->getType()->getScalarSizeInBits())) {
690 APInt NumElems = *PossibleSize;
691 if (!checkedZextOrTrunc(NumElems))
692 return ObjectSizeOffsetVisitor::unknown();
693
694 bool Overflow;
695 Size = Size.umul_ov(NumElems, Overflow);
696
697 return Overflow ? ObjectSizeOffsetVisitor::unknown()
698 : OffsetSpan(Zero, align(Size, I.getAlign()));
699 }
700 return ObjectSizeOffsetVisitor::unknown();
701}
702
704 Type *MemoryTy = A.getPointeeInMemoryValueType();
705 // No interprocedural analysis is done at the moment.
706 if (!MemoryTy || !MemoryTy->isSized()) {
707 ++ObjectVisitorArgument;
708 return ObjectSizeOffsetVisitor::unknown();
709 }
710
711 APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
712 return OffsetSpan(Zero, align(Size, A.getParamAlign()));
713}
714
716 auto Mapper = [this](const Value *V) -> const Value * {
717 if (!V->getType()->isIntegerTy())
718 return V;
719
720 if (auto PossibleBound = aggregatePossibleConstantValues(
721 V, Options.EvalMode, V->getType()->getScalarSizeInBits()))
722 return ConstantInt::get(V->getType(), *PossibleBound);
723
724 return V;
725 };
726
727 if (std::optional<APInt> Size = getAllocSize(&CB, TLI, Mapper)) {
728 // Very large unsigned value cannot be represented as OffsetSpan.
729 if (Size->isNegative())
730 return ObjectSizeOffsetVisitor::unknown();
731 return OffsetSpan(Zero, *Size);
732 }
733 return ObjectSizeOffsetVisitor::unknown();
734}
735
738 // If null is unknown, there's nothing we can do. Additionally, non-zero
739 // address spaces can make use of null, so we don't presume to know anything
740 // about that.
741 //
742 // TODO: How should this work with address space casts? We currently just drop
743 // them on the floor, but it's unclear what we should do when a NULL from
744 // addrspace(1) gets casted to addrspace(0) (or vice-versa).
745 if (Options.NullIsUnknownSize || CPN.getPointerType()->getAddressSpace())
746 return ObjectSizeOffsetVisitor::unknown();
747 return OffsetSpan(Zero, Zero);
748}
749
752 return ObjectSizeOffsetVisitor::unknown();
753}
754
756 // Easy cases were already folded by previous passes.
757 return ObjectSizeOffsetVisitor::unknown();
758}
759
761 if (GA.isInterposable())
762 return ObjectSizeOffsetVisitor::unknown();
763 return computeImpl(GA.getAliasee());
764}
765
767 if (!GV.getValueType()->isSized() || GV.hasExternalWeakLinkage() ||
768 ((!GV.hasInitializer() || GV.isInterposable()) &&
769 Options.EvalMode != ObjectSizeOpts::Mode::Min))
770 return ObjectSizeOffsetVisitor::unknown();
771
772 APInt Size(IntTyBits, GV.getGlobalSize(DL));
773 return OffsetSpan(Zero, align(Size, GV.getAlign()));
774}
775
777 // clueless
778 return ObjectSizeOffsetVisitor::unknown();
779}
780
781OffsetSpan ObjectSizeOffsetVisitor::findLoadOffsetRange(
784 unsigned &ScannedInstCount) {
785 constexpr unsigned MaxInstsToScan = 128;
786
787 auto Where = VisitedBlocks.find(&BB);
788 if (Where != VisitedBlocks.end())
789 return Where->second;
790
791 auto Unknown = [&BB, &VisitedBlocks]() {
792 return VisitedBlocks[&BB] = ObjectSizeOffsetVisitor::unknown();
793 };
794 auto Known = [&BB, &VisitedBlocks](OffsetSpan SO) {
795 return VisitedBlocks[&BB] = SO;
796 };
797
798 do {
799 Instruction &I = *From;
800
802 continue;
803
804 if (++ScannedInstCount > MaxInstsToScan)
805 return Unknown();
806
807 if (!I.mayWriteToMemory())
808 continue;
809
810 if (auto *SI = dyn_cast<StoreInst>(&I)) {
811 AliasResult AR =
812 Options.AA->alias(SI->getPointerOperand(), Load.getPointerOperand());
813 switch ((AliasResult::Kind)AR) {
815 continue;
817 if (SI->getValueOperand()->getType()->isPointerTy())
818 return Known(computeImpl(SI->getValueOperand()));
819 else
820 return Unknown(); // No handling of non-pointer values by `compute`.
821 default:
822 return Unknown();
823 }
824 }
825
826 if (auto *CB = dyn_cast<CallBase>(&I)) {
828 // Bail out on indirect call.
829 if (!Callee)
830 return Unknown();
831
832 if (!TLI)
833 return Unknown();
834
835 LibFunc TLIFn = TLI->getLibFunc(*CB->getCalledFunction());
836 if (!TLI->has(TLIFn))
837 return Unknown();
838
839 // TODO: There's probably more interesting case to support here.
840 if (TLIFn != LibFunc_posix_memalign)
841 return Unknown();
842
843 AliasResult AR =
844 Options.AA->alias(CB->getOperand(0), Load.getPointerOperand());
845 switch ((AliasResult::Kind)AR) {
847 continue;
849 break;
850 default:
851 return Unknown();
852 }
853
854 // Is the error status of posix_memalign correctly checked? If not it
855 // would be incorrect to assume it succeeds and load doesn't see the
856 // previous value.
857 std::optional<bool> Checked = isImpliedByDomCondition(
858 ICmpInst::ICMP_EQ, CB, ConstantInt::get(CB->getType(), 0), &Load, DL);
859 if (!Checked || !*Checked)
860 return Unknown();
861
862 Value *Size = CB->getOperand(2);
864 if (!C)
865 return Unknown();
866
867 APInt CSize = C->getValue();
868 if (CSize.isNegative())
869 return Unknown();
870
871 return Known({APInt(CSize.getBitWidth(), 0), CSize});
872 }
873
874 return Unknown();
875 } while (From-- != BB.begin());
876
877 SmallVector<OffsetSpan> PredecessorSizeOffsets;
878 for (auto *PredBB : predecessors(&BB)) {
879 PredecessorSizeOffsets.push_back(findLoadOffsetRange(
880 Load, *PredBB, BasicBlock::iterator(PredBB->getTerminator()),
881 VisitedBlocks, ScannedInstCount));
882 if (!PredecessorSizeOffsets.back().bothKnown())
883 return Unknown();
884 }
885
886 if (PredecessorSizeOffsets.empty())
887 return Unknown();
888
889 return Known(std::accumulate(
890 PredecessorSizeOffsets.begin() + 1, PredecessorSizeOffsets.end(),
891 PredecessorSizeOffsets.front(), [this](OffsetSpan LHS, OffsetSpan RHS) {
892 return combineOffsetRange(LHS, RHS);
893 }));
894}
895
897 if (!Options.AA) {
898 ++ObjectVisitorLoad;
899 return ObjectSizeOffsetVisitor::unknown();
900 }
901
903 unsigned ScannedInstCount = 0;
904 OffsetSpan SO =
905 findLoadOffsetRange(LI, *LI.getParent(), BasicBlock::iterator(LI),
906 VisitedBlocks, ScannedInstCount);
907 if (!SO.bothKnown())
908 ++ObjectVisitorLoad;
909 return SO;
910}
911
912OffsetSpan ObjectSizeOffsetVisitor::combineOffsetRange(OffsetSpan LHS,
913 OffsetSpan RHS) {
914 if (!LHS.bothKnown() || !RHS.bothKnown())
915 return ObjectSizeOffsetVisitor::unknown();
916
917 switch (Options.EvalMode) {
919 return {LHS.Before.slt(RHS.Before) ? LHS.Before : RHS.Before,
920 LHS.After.slt(RHS.After) ? LHS.After : RHS.After};
922 return {LHS.Before.sgt(RHS.Before) ? LHS.Before : RHS.Before,
923 LHS.After.sgt(RHS.After) ? LHS.After : RHS.After};
924 }
926 return {LHS.Before.eq(RHS.Before) ? LHS.Before : APInt(),
927 LHS.After.eq(RHS.After) ? LHS.After : APInt()};
929 return (LHS == RHS) ? LHS : ObjectSizeOffsetVisitor::unknown();
930 }
931 llvm_unreachable("missing an eval mode");
932}
933
935 if (PN.getNumIncomingValues() == 0)
936 return ObjectSizeOffsetVisitor::unknown();
937 auto IncomingValues = PN.incoming_values();
938 return std::accumulate(IncomingValues.begin() + 1, IncomingValues.end(),
939 computeImpl(*IncomingValues.begin()),
940 [this](OffsetSpan LHS, Value *VRHS) {
941 return combineOffsetRange(LHS, computeImpl(VRHS));
942 });
943}
944
946 return combineOffsetRange(computeImpl(I.getTrueValue()),
947 computeImpl(I.getFalseValue()));
948}
949
953
955 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
956 << '\n');
957 return ObjectSizeOffsetVisitor::unknown();
958}
959
960// Just set these right here...
963
965 Module &M, const TargetLibraryInfo *TLI, ObjectSizeOpts EvalOpts)
966 : DL(M.getDataLayout()), TLI(TLI), Context(M.getContext()),
967 Builder(M, TargetFolder(DL),
969 [&](Instruction *I) { InsertedInstructions.insert(I); })),
970 EvalOpts(EvalOpts) {
971 // IntTy and Zero must be set for each compute() since the address space may
972 // be different for later objects.
973}
974
976 // XXX - Are vectors of pointers possible here?
977 IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
978 Zero = ConstantInt::get(IntTy, 0);
979
980 SizeOffsetValue Result = compute_(V);
981
982 if (!Result.bothKnown()) {
983 // Erase everything that was computed in this iteration from the cache, so
984 // that no dangling references are left behind. We could be a bit smarter if
985 // we kept a dependency graph. It's probably not worth the complexity.
986 for (const Value *SeenVal : SeenVals) {
987 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
988 // non-computable results can be safely cached
989 if (CacheIt != CacheMap.end() && CacheIt->second.anyKnown())
990 CacheMap.erase(CacheIt);
991 }
992
993 // Erase any instructions we inserted as part of the traversal.
994 for (Instruction *I : InsertedInstructions) {
995 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
996 I->eraseFromParent();
997 }
998 }
999
1000 SeenVals.clear();
1001 InsertedInstructions.clear();
1002 return Result;
1003}
1004
1005SizeOffsetValue ObjectSizeOffsetEvaluator::compute_(Value *V) {
1006
1007 // Only trust ObjectSizeOffsetVisitor in exact mode, otherwise fallback on
1008 // dynamic computation.
1009 ObjectSizeOpts VisitorEvalOpts(EvalOpts);
1010 VisitorEvalOpts.EvalMode = ObjectSizeOpts::Mode::ExactUnderlyingSizeAndOffset;
1011 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, VisitorEvalOpts);
1012
1013 SizeOffsetAPInt Const = Visitor.compute(V);
1014 if (Const.bothKnown())
1015 return SizeOffsetValue(ConstantInt::get(Context, Const.Size),
1016 ConstantInt::get(Context, Const.Offset));
1017
1018 V = V->stripPointerCasts();
1019
1020 // Check cache.
1021 CacheMapTy::iterator CacheIt = CacheMap.find(V);
1022 if (CacheIt != CacheMap.end())
1023 return CacheIt->second;
1024
1025 // Always generate code immediately before the instruction being
1026 // processed, so that the generated code dominates the same BBs.
1027 BuilderTy::InsertPointGuard Guard(Builder);
1029 Builder.SetInsertPoint(I);
1030
1031 // Now compute the size and offset.
1032 SizeOffsetValue Result;
1033
1034 // Record the pointers that were handled in this run, so that they can be
1035 // cleaned later if something fails. We also use this set to break cycles that
1036 // can occur in dead code.
1037 if (!SeenVals.insert(V).second) {
1039 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1040 Result = visitGEPOperator(*GEP);
1041 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
1042 Result = visit(*I);
1043 } else if (isa<Argument>(V) ||
1044 (isa<ConstantExpr>(V) &&
1045 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
1047 // Ignore values where we cannot do more than ObjectSizeVisitor.
1049 } else {
1050 LLVM_DEBUG(
1051 dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
1052 << '\n');
1054 }
1055
1056 // Don't reuse CacheIt since it may be invalid at this point.
1057 CacheMap[V] = SizeOffsetWeakTrackingVH(Result);
1058 return Result;
1059}
1060
1062 // must be a VLA or vscale.
1063 assert(I.isArrayAllocation() || I.isScalable());
1064
1065 // If needed, adjust the alloca's operand size to match the pointer indexing
1066 // size. Subsequent math operations expect the types to match.
1067 Type *IndexTy = DL.getIndexType(I.getContext(), DL.getAllocaAddrSpace());
1068 assert(IndexTy == Zero->getType() &&
1069 "Expected zero constant to have pointer index type");
1070
1071 Value *Size = Builder.CreateAllocationSize(IndexTy, &I);
1072 return SizeOffsetValue(Size, Zero);
1073}
1074
1076 auto [FirstArg, SecondArg] = getAllocSizePair(&CB);
1077 if (!FirstArg)
1079
1080 FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
1081 if (!SecondArg)
1082 return SizeOffsetValue(FirstArg, Zero);
1083
1084 SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
1085 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
1086 return SizeOffsetValue(Size, Zero);
1087}
1088
1093
1098
1100 SizeOffsetValue PtrData = compute_(GEP.getPointerOperand());
1101 if (!PtrData.bothKnown())
1103
1104 Value *Offset = emitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1105 Offset = Builder.CreateAdd(PtrData.Offset, Offset);
1106 return SizeOffsetValue(PtrData.Size, Offset);
1107}
1108
1113
1117
1119 // Create 2 PHIs: one for size and another for offset.
1120 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1121 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1122
1123 // Insert right away in the cache to handle recursive PHIs.
1124 CacheMap[&PHI] = SizeOffsetWeakTrackingVH(SizePHI, OffsetPHI);
1125
1126 // Compute offset/size for each PHI incoming pointer.
1127 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1128 BasicBlock *IncomingBlock = PHI.getIncomingBlock(i);
1129 Builder.SetInsertPoint(IncomingBlock->getFirstInsertionPt());
1130 SizeOffsetValue EdgeData = compute_(PHI.getIncomingValue(i));
1131
1132 if (!EdgeData.bothKnown()) {
1133 OffsetPHI->replaceAllUsesWith(PoisonValue::get(IntTy));
1134 OffsetPHI->eraseFromParent();
1135 InsertedInstructions.erase(OffsetPHI);
1136 SizePHI->replaceAllUsesWith(PoisonValue::get(IntTy));
1137 SizePHI->eraseFromParent();
1138 InsertedInstructions.erase(SizePHI);
1140 }
1141 SizePHI->addIncoming(EdgeData.Size, IncomingBlock);
1142 OffsetPHI->addIncoming(EdgeData.Offset, IncomingBlock);
1143 }
1144
1145 Value *Size = SizePHI, *Offset = OffsetPHI;
1146 if (Value *Tmp = SizePHI->hasConstantValue()) {
1147 Size = Tmp;
1148 SizePHI->replaceAllUsesWith(Size);
1149 SizePHI->eraseFromParent();
1150 InsertedInstructions.erase(SizePHI);
1151 }
1152 if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1153 Offset = Tmp;
1154 OffsetPHI->replaceAllUsesWith(Offset);
1155 OffsetPHI->eraseFromParent();
1156 InsertedInstructions.erase(OffsetPHI);
1157 }
1158 return SizeOffsetValue(Size, Offset);
1159}
1160
1162 SizeOffsetValue TrueSide = compute_(I.getTrueValue());
1163 SizeOffsetValue FalseSide = compute_(I.getFalseValue());
1164
1165 if (!TrueSide.bothKnown() || !FalseSide.bothKnown())
1167 if (TrueSide == FalseSide)
1168 return TrueSide;
1169
1170 Value *Size =
1171 Builder.CreateSelect(I.getCondition(), TrueSide.Size, FalseSide.Size, "",
1172 ProfcheckDisableMetadataFixes ? nullptr : &I);
1173 Value *Offset =
1174 Builder.CreateSelect(I.getCondition(), TrueSide.Offset, FalseSide.Offset,
1175 "", ProfcheckDisableMetadataFixes ? nullptr : &I);
1176 return SizeOffsetValue(Size, Offset);
1177}
1178
1180 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1181 << '\n');
1183}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
Hexagon Common GEP
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isStrDupLike(LibFunc LF)
static std::optional< APInt > combinePossibleConstantValues(std::optional< APInt > LHS, std::optional< APInt > RHS, ObjectSizeOpts::Mode EvalMode)
static AllocFnKind getAllocFnKind(const Value *V)
static std::optional< APInt > aggregatePossibleConstantValuesImpl(const Value *V, ObjectSizeOpts::Mode EvalMode, unsigned BitWidth, unsigned RecursionDepth)
static bool checkedZextOrTrunc(APInt &I, unsigned IntTyBits)
When we're compiling N-bit code, and the user uses parameters that are greater than N bits (e....
static bool checkFnAllocKind(const Value *V, AllocFnKind Wanted)
static bool isStrNDupLike(LibFunc LF)
static cl::opt< unsigned > ObjectSizeOffsetVisitorMaxVisitInstructions("object-size-offset-visitor-max-visit-instructions", cl::desc("Maximum number of instructions for ObjectSizeOffsetVisitor to " "look at"), cl::init(100))
static std::pair< Value *, Value * > getAllocSizePair(const CallBase *CB)
static APInt getSizeWithOverflow(const SizeOffsetAPInt &Data)
static std::optional< APInt > aggregatePossibleConstantValues(const Value *V, ObjectSizeOpts::Mode EvalMode, unsigned BitWidth)
#define P(N)
This file contains the declarations for profiling metadata utility functions.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
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
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
@ NoAlias
The two locations do not alias at all.
@ MustAlias
The two locations precisely alias each other.
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI uint64_t getValueAsInt() const
Return the attribute's value as an integer.
LLVM_ABI std::pair< unsigned, std::optional< unsigned > > getAllocSizeArgs() const
Returns the argument numbers for the allocsize attribute.
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:260
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
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.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A constant pointer value that points to null.
Definition Constants.h:716
PointerType * getPointerType() const
Return the scalar pointer type for this null value.
Definition Constants.h:736
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
const Constant * getAliasee() const
Definition GlobalAlias.h:87
bool hasExternalWeakLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
This class represents a cast from an integer to a pointer.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Evaluate the size and offset of an object pointed to by a Value*.
LLVM_ABI SizeOffsetValue visitExtractValueInst(ExtractValueInst &I)
LLVM_ABI SizeOffsetValue visitExtractElementInst(ExtractElementInst &I)
LLVM_ABI SizeOffsetValue compute(Value *V)
LLVM_ABI SizeOffsetValue visitInstruction(Instruction &I)
LLVM_ABI SizeOffsetValue visitLoadInst(LoadInst &I)
LLVM_ABI SizeOffsetValue visitGEPOperator(GEPOperator &GEP)
LLVM_ABI SizeOffsetValue visitIntToPtrInst(IntToPtrInst &)
LLVM_ABI SizeOffsetValue visitPHINode(PHINode &PHI)
LLVM_ABI SizeOffsetValue visitCallBase(CallBase &CB)
LLVM_ABI ObjectSizeOffsetEvaluator(Module &M, const TargetLibraryInfo *TLI, ObjectSizeOpts EvalOpts={})
LLVM_ABI SizeOffsetValue visitSelectInst(SelectInst &I)
LLVM_ABI SizeOffsetValue visitAllocaInst(AllocaInst &I)
static SizeOffsetValue unknown()
Evaluate the size and offset of an object pointed to by a Value* statically.
LLVM_ABI OffsetSpan visitSelectInst(SelectInst &I)
LLVM_ABI OffsetSpan visitExtractValueInst(ExtractValueInst &I)
LLVM_ABI OffsetSpan visitConstantPointerNull(ConstantPointerNull &)
LLVM_ABI OffsetSpan visitExtractElementInst(ExtractElementInst &I)
LLVM_ABI OffsetSpan visitGlobalVariable(GlobalVariable &GV)
LLVM_ABI OffsetSpan visitCallBase(CallBase &CB)
LLVM_ABI OffsetSpan visitIntToPtrInst(IntToPtrInst &)
LLVM_ABI OffsetSpan visitAllocaInst(AllocaInst &I)
LLVM_ABI ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts Options={})
LLVM_ABI OffsetSpan visitLoadInst(LoadInst &I)
LLVM_ABI OffsetSpan visitPHINode(PHINode &)
LLVM_ABI OffsetSpan visitGlobalAlias(GlobalAlias &GA)
LLVM_ABI OffsetSpan visitInstruction(Instruction &I)
LLVM_ABI SizeOffsetAPInt compute(Value *V)
LLVM_ABI OffsetSpan visitUndefValue(UndefValue &)
LLVM_ABI OffsetSpan visitArgument(Argument &A)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
LLVM_ABI Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value,...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
TargetFolder - Create constants with target dependent folding.
Provides information about what library functions are available for the current target.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getZero()
Definition TypeSize.h:358
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Value * getAllocAlignment(const CallBase *V)
Gets the alignment argument for an aligned_alloc-like function based on the allocalign attribute.
@ Offset
Definition DWP.cpp:577
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI std::optional< StringRef > getAllocationFamily(const Value *I)
If a function is part of an allocation family (e.g.
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
AllocFnKind
Definition Attributes.h:54
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Value * getReallocatedOperand(const CallBase *CB)
If this is a call to a realloc function, return the reallocated operand.
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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.
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
LLVM_ABI bool isAllocLikeFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isFreeLikeFn(const Function *F)
Returns true if the function has allockind(free).
LLVM_ABI bool isReallocLikeFn(const Function *F)
Tests if a function is a call or invoke to a library function that reallocates memory (e....
LLVM_ABI bool isAllocationFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI Constant * getElidedFreeResult(const Value *V)
If this is a call to a free function that returns a value, return the value that will be returned whe...
LLVM_ABI Value * getFreedOperand(const CallBase *CB)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool isRemovableAlloc(const CallBase *V)
Return true if this is a call to an allocation function that does not have side effects that we are r...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
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.
Mode EvalMode
How we want to evaluate this object's size.
AAResults * AA
If set, used for more accurate evaluation.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
Mode
Controls how we handle conditional statements with unknown conditions.
@ ExactUnderlyingSizeAndOffset
All branches must be known and have the same underlying size and offset to be merged.
@ Max
Same as Min, except we pick the maximum size of all of the branches.
@ Min
Evaluate all branches of an unknown condition.
@ ExactSizeFromOffset
All branches must be known and have the same size, starting from the offset, to be merged.
OffsetSpan - Used internally by ObjectSizeOffsetVisitor.
bool knownBefore() const
APInt After
Number of allocated bytes before this point.
bool knownAfter() const
bool bothKnown() const
SizeOffsetAPInt - Used by ObjectSizeOffsetVisitor, which works with APInts.
SizeOffsetWeakTrackingVH - Used by ObjectSizeOffsetEvaluator in a DenseMap.