Skip to content

Commit 9f63578

Browse files
[llvm] Improve llvm.objectsize computation by computing GEP, alloca and malloc parameters bound
Using a naive expression walker, it is possible to compute valuable information for allocation functions, GEP and alloca, even in the presence of some dynamic information. We don't rely on computeConstantRange to avoid taking advantage of undefined behavior, which would be counter-productive wrt. usual llvm.objectsize usage. llvm.objectsize plays an important role in _FORTIFY_SOURCE definitions, so improving its diagnostic in turns improves the security of compiled application. As a side note, as a result of recent optimization improvements, clang no longer passes https://github.com/serge-sans-paille/builtin_object_size-test-suite This commit restores the situation and greatly improves the scope of code handled by the static version of __builtin_object_size.
1 parent 2ec5ced commit 9f63578

File tree

3 files changed

+222
-8
lines changed

3 files changed

+222
-8
lines changed

llvm/include/llvm/IR/Value.h

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -723,12 +723,16 @@ class Value {
723723
bool AllowInvariantGroup = false,
724724
function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
725725
nullptr) const;
726-
Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
727-
bool AllowNonInbounds,
728-
bool AllowInvariantGroup = false) {
726+
727+
Value *stripAndAccumulateConstantOffsets(
728+
const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
729+
bool AllowInvariantGroup = false,
730+
function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
731+
nullptr) {
729732
return const_cast<Value *>(
730733
static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
731-
DL, Offset, AllowNonInbounds, AllowInvariantGroup));
734+
DL, Offset, AllowNonInbounds, AllowInvariantGroup,
735+
ExternalAnalysis));
732736
}
733737

734738
/// This is a wrapper around stripAndAccumulateConstantOffsets with the

llvm/lib/Analysis/MemoryBuiltins.cpp

Lines changed: 104 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,69 @@ STATISTIC(ObjectVisitorArgument,
678678
STATISTIC(ObjectVisitorLoad,
679679
"Number of load instructions with unsolved size and offset");
680680

681+
static std::optional<APInt>
682+
combinePossibleConstantValues(std::optional<APInt> LHS,
683+
std::optional<APInt> RHS,
684+
ObjectSizeOpts::Mode EvalMode) {
685+
if (!LHS || !RHS)
686+
return std::nullopt;
687+
if (EvalMode == ObjectSizeOpts::Mode::Max)
688+
return LHS->sge(*RHS) ? *LHS : *RHS;
689+
else
690+
return LHS->sle(*RHS) ? *LHS : *RHS;
691+
}
692+
693+
static std::optional<APInt> aggregatePossibleConstantValuesImpl(
694+
const Value *V, ObjectSizeOpts::Mode EvalMode, unsigned recursionDepth) {
695+
constexpr unsigned maxRecursionDepth = 4;
696+
if (recursionDepth == maxRecursionDepth)
697+
return std::nullopt;
698+
699+
if (const auto *CI = dyn_cast<ConstantInt>(V)) {
700+
return CI->getValue();
701+
}
702+
703+
else if (const auto *SI = dyn_cast<SelectInst>(V)) {
704+
return combinePossibleConstantValues(
705+
aggregatePossibleConstantValuesImpl(SI->getTrueValue(), EvalMode,
706+
recursionDepth + 1),
707+
aggregatePossibleConstantValuesImpl(SI->getFalseValue(), EvalMode,
708+
recursionDepth + 1),
709+
EvalMode);
710+
}
711+
712+
else if (const auto *PN = dyn_cast<PHINode>(V)) {
713+
unsigned Count = PN->getNumIncomingValues();
714+
if (Count == 0)
715+
return std::nullopt;
716+
auto Acc = aggregatePossibleConstantValuesImpl(
717+
PN->getIncomingValue(0), EvalMode, recursionDepth + 1);
718+
for (unsigned I = 1; Acc && I < Count; ++I) {
719+
auto Tmp = aggregatePossibleConstantValuesImpl(
720+
PN->getIncomingValue(1), EvalMode, recursionDepth + 1);
721+
Acc = combinePossibleConstantValues(Acc, Tmp, EvalMode);
722+
}
723+
return Acc;
724+
}
725+
726+
return std::nullopt;
727+
}
728+
729+
static std::optional<APInt>
730+
aggregatePossibleConstantValues(const Value *V, ObjectSizeOpts::Mode EvalMode) {
731+
if (auto *CI = dyn_cast<ConstantInt>(V))
732+
return CI->getValue();
733+
734+
if (EvalMode != ObjectSizeOpts::Mode::Min &&
735+
EvalMode != ObjectSizeOpts::Mode::Max)
736+
return std::nullopt;
737+
738+
// Not using computeConstantRange here because we cannot guarantee it's not
739+
// doing optimization based on UB which we want to avoid when expanding
740+
// __builtin_object_size.
741+
return aggregatePossibleConstantValuesImpl(V, EvalMode, 0u);
742+
}
743+
681744
/// Align \p Size according to \p Alignment. If \p Size is greater than
682745
/// getSignedMaxValue(), set it as unknown as we can only represent signed value
683746
/// in OffsetSpan.
@@ -725,11 +788,36 @@ OffsetSpan ObjectSizeOffsetVisitor::computeImpl(Value *V) {
725788
V = V->stripAndAccumulateConstantOffsets(
726789
DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
727790

791+
// Give it another try with approximated analysis. We don't start with this
792+
// one because stripAndAccumulateConstantOffsets behaves differently wrt.
793+
// overflows if we provide an external Analysis.
794+
if ((Options.EvalMode == ObjectSizeOpts::Mode::Min ||
795+
Options.EvalMode == ObjectSizeOpts::Mode::Max) &&
796+
isa<GEPOperator>(V)) {
797+
// External Analysis used to compute the Min/Max value of individual Offsets
798+
// within a GEP.
799+
ObjectSizeOpts::Mode EvalMode =
800+
Options.EvalMode == ObjectSizeOpts::Mode::Min
801+
? ObjectSizeOpts::Mode::Max
802+
: ObjectSizeOpts::Mode::Min;
803+
auto OffsetRangeAnalysis = [EvalMode](Value &VOffset, APInt &Offset) {
804+
if (auto PossibleOffset =
805+
aggregatePossibleConstantValues(&VOffset, EvalMode)) {
806+
Offset = *PossibleOffset;
807+
return true;
808+
}
809+
return false;
810+
};
811+
812+
V = V->stripAndAccumulateConstantOffsets(
813+
DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true,
814+
/*ExternalAnalysis=*/OffsetRangeAnalysis);
815+
}
816+
728817
// Later we use the index type size and zero but it will match the type of the
729818
// value that is passed to computeImpl.
730819
IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
731820
Zero = APInt::getZero(IntTyBits);
732-
733821
OffsetSpan ORT = computeValue(V);
734822

735823
bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
@@ -810,8 +898,9 @@ OffsetSpan ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
810898
return OffsetSpan(Zero, align(Size, I.getAlign()));
811899

812900
Value *ArraySize = I.getArraySize();
813-
if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
814-
APInt NumElems = C->getValue();
901+
if (auto PossibleSize =
902+
aggregatePossibleConstantValues(ArraySize, Options.EvalMode)) {
903+
APInt NumElems = *PossibleSize;
815904
if (!CheckedZextOrTrunc(NumElems))
816905
return ObjectSizeOffsetVisitor::unknown();
817906

@@ -837,7 +926,18 @@ OffsetSpan ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
837926
}
838927

839928
OffsetSpan ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
840-
if (std::optional<APInt> Size = getAllocSize(&CB, TLI)) {
929+
auto Mapper = [this](const Value *V) -> const Value * {
930+
if (!V->getType()->isIntegerTy())
931+
return V;
932+
933+
if (auto PossibleBound =
934+
aggregatePossibleConstantValues(V, Options.EvalMode))
935+
return ConstantInt::get(V->getType(), *PossibleBound);
936+
937+
return V;
938+
};
939+
940+
if (std::optional<APInt> Size = getAllocSize(&CB, TLI, Mapper)) {
841941
// Very large unsigned value cannot be represented as OffsetSpan.
842942
if (Size->isNegative())
843943
return ObjectSizeOffsetVisitor::unknown();
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
2+
; RUN: opt -passes=lower-constant-intrinsics -S < %s | FileCheck %s
3+
4+
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
5+
target triple = "x86_64-unknown-linux-gnu"
6+
7+
declare i64 @llvm.objectsize.i64.p0(ptr, i1 immarg, i1 immarg, i1 immarg)
8+
declare noalias ptr @malloc(i64 noundef) #0
9+
10+
define i64 @select_alloc_size(i1 %cond) {
11+
; CHECK-LABEL: @select_alloc_size(
12+
; CHECK-NEXT: [[SIZE:%.*]] = select i1 [[COND:%.*]], i64 3, i64 4
13+
; CHECK-NEXT: [[PTR:%.*]] = alloca i8, i64 [[SIZE]], align 1
14+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[COND]], i64 4, i64 3
15+
; CHECK-NEXT: ret i64 [[RES]]
16+
;
17+
%size = select i1 %cond, i64 3, i64 4
18+
%ptr = alloca i8, i64 %size
19+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr, i1 false, i1 true, i1 false)
20+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr, i1 true, i1 true, i1 false)
21+
%res = select i1 %cond, i64 %objsize_max, i64 %objsize_min
22+
ret i64 %res
23+
}
24+
25+
define i64 @select_malloc_size(i1 %cond) {
26+
; CHECK-LABEL: @select_malloc_size(
27+
; CHECK-NEXT: [[SIZE:%.*]] = select i1 [[COND:%.*]], i64 3, i64 4
28+
; CHECK-NEXT: [[PTR:%.*]] = call noalias ptr @malloc(i64 noundef [[SIZE]])
29+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[COND]], i64 4, i64 3
30+
; CHECK-NEXT: ret i64 [[RES]]
31+
;
32+
%size = select i1 %cond, i64 3, i64 4
33+
%ptr = call noalias ptr @malloc(i64 noundef %size)
34+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr, i1 false, i1 true, i1 false)
35+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr, i1 true, i1 true, i1 false)
36+
%res = select i1 %cond, i64 %objsize_max, i64 %objsize_min
37+
ret i64 %res
38+
}
39+
40+
define i64 @select_gep_offset(i1 %cond) {
41+
; CHECK-LABEL: @select_gep_offset(
42+
; CHECK-NEXT: [[PTR:%.*]] = alloca i8, i64 10, align 1
43+
; CHECK-NEXT: [[OFFSET:%.*]] = select i1 [[COND:%.*]], i64 3, i64 4
44+
; CHECK-NEXT: [[PTR_SLIDE:%.*]] = getelementptr inbounds i8, ptr [[PTR]], i64 [[OFFSET]]
45+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[COND]], i64 7, i64 6
46+
; CHECK-NEXT: ret i64 [[RES]]
47+
;
48+
%ptr = alloca i8, i64 10
49+
%offset = select i1 %cond, i64 3, i64 4
50+
%ptr.slide = getelementptr inbounds i8, ptr %ptr, i64 %offset
51+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 false, i1 true, i1 false)
52+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 true, i1 true, i1 false)
53+
%res = select i1 %cond, i64 %objsize_max, i64 %objsize_min
54+
ret i64 %res
55+
}
56+
57+
define i64 @select_gep_neg_offset(i1 %c0, i1 %c1) {
58+
; CHECK-LABEL: @select_gep_neg_offset(
59+
; CHECK-NEXT: [[PTR:%.*]] = alloca i8, i64 10, align 1
60+
; CHECK-NEXT: [[PTR_SLIDE_1:%.*]] = getelementptr inbounds i8, ptr [[PTR]], i64 5
61+
; CHECK-NEXT: [[OFFSET:%.*]] = select i1 [[COND:%.*]], i64 -3, i64 -4
62+
; CHECK-NEXT: [[PTR_SLIDE_2:%.*]] = getelementptr inbounds i8, ptr [[PTR_SLIDE_1]], i64 [[OFFSET]]
63+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[C1:%.*]], i64 9, i64 8
64+
; CHECK-NEXT: ret i64 [[RES]]
65+
;
66+
%ptr = alloca i8, i64 10
67+
%ptr.slide.1 = getelementptr inbounds i8, ptr %ptr, i64 5
68+
%offset = select i1 %c0, i64 -3, i64 -4
69+
%ptr.slide.2 = getelementptr inbounds i8, ptr %ptr.slide.1, i64 %offset
70+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide.2, i1 false, i1 true, i1 false)
71+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide.2, i1 true, i1 true, i1 false)
72+
%res = select i1 %c1, i64 %objsize_max, i64 %objsize_min
73+
ret i64 %res
74+
}
75+
76+
define i64 @select_neg_oob_offset(i1 %c0, i1 %c1) {
77+
; CHECK-LABEL: @select_neg_oob_offset(
78+
; CHECK-NEXT: [[PTR:%.*]] = alloca i8, i64 10, align 1
79+
; CHECK-NEXT: [[OFFSET:%.*]] = select i1 [[C0:%.*]], i64 -3, i64 -4
80+
; CHECK-NEXT: [[PTR_SLIDE:%.*]] = getelementptr inbounds i8, ptr [[PTR]], i64 [[OFFSET]]
81+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[C1:%.*]], i64 -1, i64 0
82+
; CHECK-NEXT: ret i64 [[RES]]
83+
;
84+
%ptr = alloca i8, i64 10
85+
%offset = select i1 %c0, i64 -3, i64 -4
86+
%ptr.slide = getelementptr inbounds i8, ptr %ptr, i64 %offset
87+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 false, i1 true, i1 false)
88+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 true, i1 true, i1 false)
89+
%res = select i1 %c1, i64 %objsize_max, i64 %objsize_min
90+
ret i64 %res
91+
}
92+
93+
define i64 @select_gep_offsets(i1 %cond) {
94+
; CHECK-LABEL: @select_gep_offsets(
95+
; CHECK-NEXT: [[PTR:%.*]] = alloca [10 x i8], i64 2, align 1
96+
; CHECK-NEXT: [[OFFSET:%.*]] = select i1 [[COND:%.*]], i32 0, i32 1
97+
; CHECK-NEXT: [[PTR_SLIDE:%.*]] = getelementptr inbounds [10 x i8], ptr [[PTR]], i32 [[OFFSET]], i32 5
98+
; CHECK-NEXT: [[RES:%.*]] = select i1 [[COND]], i64 15, i64 5
99+
; CHECK-NEXT: ret i64 [[RES]]
100+
;
101+
%ptr = alloca [10 x i8], i64 2
102+
%offset = select i1 %cond, i32 0, i32 1
103+
%ptr.slide = getelementptr inbounds [10 x i8], ptr %ptr, i32 %offset, i32 5
104+
%objsize_max = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 false, i1 true, i1 false)
105+
%objsize_min = call i64 @llvm.objectsize.i64.p0(ptr %ptr.slide, i1 true, i1 true, i1 false)
106+
%res = select i1 %cond, i64 %objsize_max, i64 %objsize_min
107+
ret i64 %res
108+
}
109+
110+
attributes #0 = { nounwind allocsize(0) }

0 commit comments

Comments
 (0)