Skip to content

[SIL] Hollow out Builtin.copy and deprecate _copy. #73422

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

Merged
merged 1 commit into from
May 4, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,6 @@ extension AddressUseVisitor {

case let builtin as BuiltinInst:
switch builtin.id {
case .Copy where builtin.operands[1] == operand: // source
return loadedAddressUse(of: operand, into: builtin.operands[0])

case .Copy where builtin.operands[0] == operand: // dest
return leafAddressUse(of: operand)

// Builtins that cannot load a nontrivial value.
case .TSanInoutAccess, .ResumeThrowingContinuationReturning,
.ResumeNonThrowingContinuationReturning, .GenericAdd,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -909,12 +909,6 @@ extension LifetimeDependenceDefUseWalker {
case let tai as TupleAddrConstructorInst:
return visitStoredUses(of: operand, into: tai.destinationOperand.value)

case let bi as BuiltinInst where bi.id == .Copy:
// This must be a non-address-lowered form of Builtin.Copy that
// produces an owned value.
assert(bi.ownership == .owned)
return walkDownUses(of: bi, using: operand)

default:
return nonForwardingUse(of: operand)
}
Expand Down
26 changes: 8 additions & 18 deletions include/swift/AST/Builtins.def
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,14 @@ BUILTIN_SIL_OPERATION(HopToActor, "hopToActor", None)
/// Returns the number of items in a pack.
BUILTIN_SIL_OPERATION(PackLength, "packLength", Special)

/// TODO: Remove. Only exists to avoid a reverse condfail.
/// rdar://127516085 (Complete removal of Builtin.copy)
///
/// copy: <T>(T) -> T
///
/// Creates a copy of the source at the destination.
BUILTIN_SIL_OPERATION(Copy, "copy", Special)

// BUILTIN_RUNTIME_CALL - A call into a runtime function.
// These functions accept a single argument of any type.
#ifndef BUILTIN_RUNTIME_CALL
Expand Down Expand Up @@ -804,24 +812,6 @@ BUILTIN_MISC_OPERATION(CreateTaskGroupWithFlags,
BUILTIN_MISC_OPERATION(DestroyTaskGroup,
"destroyTaskGroup", "", Special)

/// A builtin that can only be called from a transparent generic function. Takes
/// two operands, the first operand the result address, the second operand the
/// input address. Transforms into
///
/// %input = load [take] %inputAddr
/// %result = explicit_copy_value %input
/// store %result to [init] %resultAddr
/// store %input to [init] %inputAddr
///
/// transparently inlined into a caller that has the generic of the callee
/// specialized into a loadable type. If the transparent inlining does not
/// specialize the type (due to being inlined into a non-generic context, the
/// SILVerifier will abort).
///
/// Illegal to call except for in Swift._copy in the stdlib. This is enforced by
/// the SILVerifier.
BUILTIN_MISC_OPERATION(Copy, "copy", "", Special)

/// Unchecked pointer alignment assertion. Allows the compiler to assume
/// alignment of the pointer to emit more efficient code.
///
Expand Down
1 change: 0 additions & 1 deletion include/swift/AST/SemanticAttrs.def
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ SEMANTICS_ATTR(FORCE_EMIT_OPT_REMARK_PREFIX, "optremark")
SEMANTICS_ATTR(OBJC_FORBID_ASSOCIATED_OBJECTS, "objc.forbidAssociatedObjects")

SEMANTICS_ATTR(LIFETIMEMANAGEMENT_MOVE, "lifetimemanagement.move")
SEMANTICS_ATTR(LIFETIMEMANAGEMENT_COPY, "lifetimemanagement.copy")

SEMANTICS_ATTR(NO_PERFORMANCE_ANALYSIS, "no_performance_analysis")

Expand Down
1 change: 0 additions & 1 deletion include/swift/SIL/AddressWalker.h
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,6 @@ TransitiveAddressWalker<Impl>::walk(SILValue projectedAddress) && {
case BuiltinValueKind::TSanInoutAccess:
case BuiltinValueKind::ResumeThrowingContinuationReturning:
case BuiltinValueKind::ResumeNonThrowingContinuationReturning:
case BuiltinValueKind::Copy:
case BuiltinValueKind::GenericAdd:
case BuiltinValueKind::GenericFAdd:
case BuiltinValueKind::GenericAnd:
Expand Down
10 changes: 0 additions & 10 deletions lib/IRGen/GenBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1437,16 +1437,6 @@ void irgen::emitBuiltinCall(IRGenFunction &IGF, const BuiltinInfo &Builtin,
return;
}

if (Builtin.ID == BuiltinValueKind::Copy) {
auto input = args.claimNext();
auto result = args.claimNext();
SILType addrTy = argTypes[0];
const TypeInfo &addrTI = IGF.getTypeInfo(addrTy);
Address inputAttr = addrTI.getAddressForPointer(input);
Address resultAttr = addrTI.getAddressForPointer(result);
addrTI.initializeWithCopy(IGF, resultAttr, inputAttr, addrTy, false);
return;
}
if (Builtin.ID == BuiltinValueKind::AssumeAlignment) {
// A no-op pointer cast that passes on its first value. Common occurrences of
// this builtin should already be removed with the alignment guarantee moved
Expand Down
8 changes: 0 additions & 8 deletions lib/SIL/IR/OperandOwnership.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -899,14 +899,6 @@ BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GetEnumTag)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, InjectEnumTag)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, DistributedActorAsAnyActor)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AddressOfRawLayout)
OperandOwnership OperandOwnershipBuiltinClassifier::visitCopy(BuiltinInst *bi,
StringRef) {
if (bi->getFunction()->getConventions().useLoweredAddresses()) {
return OperandOwnership::UnownedInstantaneousUse;
} else {
return OperandOwnership::DestroyingConsume;
}
}
BUILTIN_OPERAND_OWNERSHIP(DestroyingConsume, StartAsyncLet)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, EndAsyncLet)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, EndAsyncLetLifetime)
Expand Down
1 change: 0 additions & 1 deletion lib/SIL/IR/ValueOwnership.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,6 @@ CONSTANT_OWNERSHIP_BUILTIN(None, CreateTaskGroup)
CONSTANT_OWNERSHIP_BUILTIN(None, CreateTaskGroupWithFlags)
CONSTANT_OWNERSHIP_BUILTIN(None, DestroyTaskGroup)
CONSTANT_OWNERSHIP_BUILTIN(None, TaskRunInline)
CONSTANT_OWNERSHIP_BUILTIN(None, Copy)
CONSTANT_OWNERSHIP_BUILTIN(None, GetEnumTag)
CONSTANT_OWNERSHIP_BUILTIN(None, InjectEnumTag)
CONSTANT_OWNERSHIP_BUILTIN(Owned, DistributedActorAsAnyActor)
Expand Down
5 changes: 0 additions & 5 deletions lib/SIL/Utils/MemAccessUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2592,11 +2592,6 @@ static void visitBuiltinAddress(BuiltinInst *builtin,
visitor(&builtin->getAllOperands()[0]);
return;

// These effect both operands.
case BuiltinValueKind::Copy:
visitor(&builtin->getAllOperands()[1]);
return;

// These consume values out of their second operand.
case BuiltinValueKind::ResumeNonThrowingContinuationReturning:
case BuiltinValueKind::ResumeThrowingContinuationReturning:
Expand Down
16 changes: 0 additions & 16 deletions lib/SIL/Verifier/SILVerifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2343,22 +2343,6 @@ class SILVerifier : public SILVerifierBase<SILVerifier> {
return;
}

if (builtinKind == BuiltinValueKind::Copy) {
// We expect that this builtin will be specialized during transparent
// inlining into explicit_copy_value if we inline into a non-generic
// context. If the builtin still remains and is not in the specific copy
// semantic function (which is the only function marked with
// semantics::LIFETIMEMANAGEMENT_COPY), then we know that we did
// transparent inlining into a function that did not result in the Builtin
// being specialized out which is user error.
//
// NOTE: Once we have opaque values, this restriction will go away. This
// is just so we can call Builtin.copy outside of the stdlib.
auto semanticName = semantics::LIFETIMEMANAGEMENT_COPY;
require(BI->getFunction()->hasSemanticsAttr(semanticName),
"_copy used within a generic context");
}

if (builtinKind == BuiltinValueKind::CreateAsyncTask) {
requireType(BI->getType(), _object(_tuple(_nativeObject, _rawPointer)),
"result of createAsyncTask");
Expand Down
17 changes: 17 additions & 0 deletions lib/SILGen/SILGenBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2027,6 +2027,23 @@ static ManagedValue emitBuiltinAddressOfRawLayout(SILGenFunction &SGF,
return ManagedValue::forObjectRValueWithoutOwnership(bi);
}

/// TODO: Remove. Only exists to avoid a reverse condfail.
/// rdar://127516085 (Complete removal of Builtin.copy)
static ManagedValue emitBuiltinCopy(SILGenFunction &SGF, SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args, SGFContext C) {
// Builtin.copy has no uses in current/future swiftinterfaces. It has a
// single use in old swiftinterfaces:
// func _copy<T>(_ t: T) -> T {
// Builtin.copy(t)
// }
// It is sufficient to have the builtin pass the value through. When the
// return is emitted, a copy will be made.
assert(args.size() == 1 && "not two arguments!?");
return ManagedValue::forOwnedAddressRValue(args[0].getValue(),
CleanupHandle::invalid());
}

std::optional<SpecializedEmitter>
SpecializedEmitter::forDecl(SILGenModule &SGM, SILDeclRef function) {
// Only consider standalone declarations in the Builtin module.
Expand Down
13 changes: 0 additions & 13 deletions lib/SILOptimizer/Mandatory/AddressLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3389,11 +3389,6 @@ class UseRewriter : SILInstructionVisitor<UseRewriter> {
bi->setOperand(use->getOperandNumber(), opAddr);
break;
}
case BuiltinValueKind::Copy: {
SILValue opAddr = addrMat.materializeAddress(use->get());
bi->setOperand(0, opAddr);
break;
}
case BuiltinValueKind::AddressOfBorrowOpaque:
visitAddressOfBorrowBuiltinInst(bi, /*stackProtected=*/true);
break;
Expand Down Expand Up @@ -4084,14 +4079,6 @@ class DefRewriter : SILInstructionVisitor<DefRewriter> {

void visitBuiltinInst(BuiltinInst *bi) {
switch (bi->getBuiltinKind().value_or(BuiltinValueKind::None)) {
case BuiltinValueKind::Copy: {
SILValue addr = addrMat.materializeAddress(bi);
builder.createBuiltin(
bi->getLoc(), bi->getName(),
SILType::getEmptyTupleType(bi->getType().getASTContext()),
bi->getSubstitutions(), {addr, bi->getOperand(0)});
break;
}
default:
bi->dump();
llvm::report_fatal_error("^^^ Unimplemented builtin opaque value def.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ static bool isBarrier(SILInstruction *inst) {
case BuiltinValueKind::AssignCopyArrayFrontToBack:
case BuiltinValueKind::AssignCopyArrayBackToFront:
case BuiltinValueKind::AssignTakeArray:
case BuiltinValueKind::Copy:
case BuiltinValueKind::CancelAsyncTask:
case BuiltinValueKind::StartAsyncLet:
case BuiltinValueKind::CreateAsyncTask:
Expand Down
46 changes: 0 additions & 46 deletions lib/SILOptimizer/Utils/SILInliner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,6 @@ class SILInlineCloner
void visitHopToExecutorInst(HopToExecutorInst *Inst);

void visitTerminator(SILBasicBlock *BB);
void visitBuiltinInst(BuiltinInst *BI);

/// This hook is called after either of the top-level visitors:
/// cloneReachableBlocks or cloneSILFunction.
Expand Down Expand Up @@ -820,51 +819,6 @@ static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
Context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}

void SILInlineCloner::visitBuiltinInst(BuiltinInst *Inst) {
if (IKind == InlineKind::MandatoryInline) {
if (auto kind = Inst->getBuiltinKind()) {
if (*kind == BuiltinValueKind::Copy) {
auto otherResultAddr = getOpValue(Inst->getOperand(0));
auto otherSrcAddr = getOpValue(Inst->getOperand(1));
auto otherType = otherSrcAddr->getType();

if (!otherType.isLoadable(*Inst->getFunction())) {
// If otherType is not loadable, emit a diagnostic since it was used
// on a generic or existential value.
diagnose(Inst->getModule().getASTContext(),
getOpLocation(Inst->getLoc()).getSourceLoc(),
diag::copy_operator_used_on_generic_or_existential_value);
return SILCloner<SILInlineCloner>::visitBuiltinInst(Inst);
}

getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
// We stash otherValue in originalOtherValue in case we need to
// perform a writeback.
auto opLoc = getOpLocation(Inst->getLoc());

assert(otherType.isAddress());

// Perform a load_borrow and then copy that.
SILValue otherValue =
getBuilder().emitLoadBorrowOperation(opLoc, otherSrcAddr);

auto *mvi = getBuilder().createExplicitCopyValue(opLoc, otherValue);

getBuilder().emitStoreValueOperation(opLoc, mvi, otherResultAddr,
StoreOwnershipQualifier::Init);
// End the borrowed value.
getBuilder().emitEndBorrowOperation(opLoc, otherValue);

// We know that Inst returns a tuple value that isn't used by anything
// else, so this /should/ be safe.
return recordClonedInstruction(Inst, mvi);
}
}
}

return SILCloner<SILInlineCloner>::visitBuiltinInst(Inst);
}

//===----------------------------------------------------------------------===//
// Cost Model
//===----------------------------------------------------------------------===//
Expand Down
24 changes: 2 additions & 22 deletions stdlib/public/core/LifetimeManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -266,31 +266,11 @@ extension String {
}
#endif

/// Takes in a value at +0 and performs a Builtin.copy upon it.
///
/// IMPLEMENTATION NOTES: During transparent inlining, Builtin.copy becomes the
/// explicit_copy_value instruction if we are inlining into a context where the
/// specialized type is loadable. If the transparent function is called in a
/// context where the inlined function specializes such that the specialized
/// type is still not loadable, the compiler aborts (a). Once we have opaque
/// values, this restriction will be lifted since after that address only types
/// at SILGen time will be loadable objects.
///
/// (a). This is implemented by requiring that Builtin.copy only be called
/// within a function marked with the semantic tag "lifetimemanagement.copy"
/// which conveniently is only the function we are defining here: _copy.
///
/// NOTE: We mark this _alwaysEmitIntoClient to ensure that we are not creating
/// new ABI that the stdlib must maintain if a user calls this ignoring the '_'
/// implying it is stdlib SPI.
@available(*, deprecated, message: "Use the copy operator")
@_alwaysEmitIntoClient
@inlinable
@_transparent
@_semantics("lifetimemanagement.copy")
public func _copy<T>(_ value: T) -> T {
#if $BuiltinCopy
Builtin.copy(value)
#else
value
#endif
copy value
}
Loading