Skip to content

Improve Span bounds check elimination by adding _assumeNonNegative to count #83172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/IRGen/GenBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,9 @@ void irgen::emitBuiltinCall(IRGenFunction &IGF, const BuiltinInfo &Builtin,
llvm::MDNode *range = llvm::MDNode::get(ctx, rangeElems);
I->setMetadata(llvm::LLVMContext::MD_range, range);
}
} else {
auto *cmp = IGF.Builder.CreateICmpSGE(v, llvm::ConstantInt::get(v->getType(), 0));
IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::assume, cmp);
Copy link
Contributor

@stephentyrone stephentyrone Jul 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with taking this as is, but we should talk to LLVM about whether they'd prefer we use range metadata or llvm.assume for these going forward, and then make both paths use the one they want.

}
// Don't generate any code for the builtin.
return out.add(v);
Expand Down
4 changes: 2 additions & 2 deletions stdlib/public/core/Span/Span.swift
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ extension Span where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@_semantics("fixed_storage.get_count")
public var count: Int { _count }
public var count: Int { _assumeNonNegative(_count) }

/// A Boolean value indicating whether the span is empty.
///
Expand All @@ -408,7 +408,7 @@ extension Span where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public var indices: Range<Index> {
unsafe Range(_uncheckedBounds: (0, _count))
unsafe Range(_uncheckedBounds: (0, count))
}
}

Expand Down