swift: Runtime crash "outlined init with take of any ..."

Describe the bug Crash in Release mode or if Optimization Level of Swift Compiler - Code Generation is Optimize for Speed [-O]. It works as expected in Debug mode.

Steps To Reproduce

  1. Paste the following into a .swift file and run it:
protocol Delegate<T> {
    associatedtype T
    
    func f(t: T)
}

class ConcreteClass: Delegate {
    func f(t: Int) { }
}

class A<T> {

    private let delegate: any Delegate<T>
    
    init(delegate: any Delegate<T>) {
        self.delegate = delegate
    }
}

let a = A(delegate: ConcreteClass())
  1. It crashes with the following:
#0  0x0000000100003b49 in outlined init with take of any Delegate<Self.Delegate.T == Int> ()
#1  0x0000000100003ac4 in specialized A.init(delegate:) [inlined] at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:25
#2  0x0000000100003ab7 in specialized A.__allocating_init(delegate:) [inlined] at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:24
#3  0x0000000100003a96 in main at /Users/plamen/Projects/Tests/TestCrash2/TestCrash2/main.swift:29
#4  0x000000010001952e in start ()

Expected behavior The code runs fine without any crashes when is Optimised for speed

Screenshots [Attached screenshot with the crash] https://i.stack.imgur.com/SgVUk.png

Environment (please fill out the following information)

  • OS: macOS 12.5
  • Xcode Version: 14.0.1

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 10
  • Comments: 22 (8 by maintainers)

Most upvoted comments

@slavapestov - the above requires to have min deployment target of macOS 13.0 or iOS 16.0 in order to compile which is not an option in my case. However if I disable the optimizations only for the init method and seems to work fine:

@_optimize(none)
init(delegate: any Delegate<T>) {
    self.delegate = delegate
}

It is not the best I guess but at least does not require to disable the optimizations for the whole app.

I can also confirm no crash on iOS 15.5 Simulator using Xcode 14.2 (14C18).

But I added the following code and have a warning in the console. Not sure if that’s expected or not:

...
let a = A(delegate: ConcreteClass())
dump(a)

warning: the Swift runtime was unable to demangle the type of field ‘delegate’. the mangled type name is ’ \323,\373\377xXj’: TypeDecoder.h:1282: Node kind 194 " \323,\373\377xXj" - unexpected kind. this field will show up as an empty tuple in Mirrors

I believe this was fixed by https://github.com/apple/swift/pull/61646

Running on any OS that does not have the new runtime support for constrained existential types is a backward deployment scenario.

You have to use an old OS

Note that you don’t necessarily have to be using an old OS - using the current macOS 12 is also considered “back deployment” here.