Uploaded image for project: 'Swift'
  1. Swift
  2. SR-15259

Should be possible to statically optimise out calls to swift_isUniquelyReferenced_nonNull_native immediately after retain call

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:
    • Environment:

      Swift 5.5 RELEASE

      Description

      Consider the following function:

      func foo(_ x: Int) -> [Int] {
          var results: [Int] = []
          results.reserveCapacity(x)
      
          for _ in 0..<x {
              results.append(x)
          }
      
          return results
      }
      

      When compiled (see this godbolt page) this includes the following lines of assembly for part of the first two lines:

              mov     r15, qword ptr [rip + _swiftEmptyArrayStorage@GOTPCREL]
              mov     rdi, r15
              call    swift_retain@PLT
              mov     rdi, r15
              call    swift_isUniquelyReferenced_nonNull_native@PLT
              test    al, al
              je      .LBB1_1
      

      In this instance, we load the empty array storage into r15. We then retain r15 and then pass it to swift_isUniquelyReferenced_nonNull_native.

      This pattern has a statically-known result: the call to isUniquelyReferenced can only return false. In this instance, we have issued a retain call on a strong reference and, without any intervening release, we have then asked if it is uniquely referenced. Of course, it cannot be: we just issued a +1 and the object was already held strongly (at +1).

      In principle we could have safely elided the call to isUniquelyReferenced, the jump, and just hit the resize operation in straight-line code. This would be a bit of a code size win.

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            lukasa Cory Benfield
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: