File: LetPropertyLowering.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (233 lines) | stat: -rw-r--r-- 8,837 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//===--- LetPropertyLowering.swift -----------------------------------------==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SIL

/// Lowers let property accesses of classes.
///
/// Lowering consists of two tasks:
///
/// * In class initializers, insert `end_init_let_ref` instructions at places where all let-fields are initialized.
///   This strictly separates the life-range of the class into a region where let fields are still written during
///   initialization and a region where let fields are truly immutable.
///
/// * Add the `[immutable]` flag to all `ref_element_addr` instructions (for let-fields) which are in the "immutable"
///   region. This includes the region after an inserted `end_init_let_ref` in an class initializer, but also all
///   let-field accesses in other functions than the initializer and the destructor.
///
/// This pass should run after DefiniteInitialization but before RawSILInstLowering (because it relies on
/// `mark_uninitialized` still present in the class initializer).
///
/// Note that it's not mandatory to run this pass. If it doesn't run, SIL is still correct.
///
/// Simplified example (after lowering):
///
///   bb0(%0 : @owned C):                           // = self of the class initializer
///     %1 = mark_uninitialized %0
///     %2 = ref_element_addr %1, #C.l              // a let-field
///     store %init_value to %2
///     %3 = end_init_let_ref %1                    // inserted by lowering
///     %4 = ref_element_addr [immutable] %3, #C.l  // set to immutable by lowering
///     %5 = load %4
///
let letPropertyLowering = FunctionPass(name: "let-property-lowering") {
  (function: Function, context: FunctionPassContext) in

  assert(context.silStage == .raw, "let-property-lowering must run before RawSILInstLowering")

  if context.hadError {
    // If DefiniteInitialization (or other passes) already reported an error, we cannot assume valid SIL anymore.
    return
  }

  if function.isDestructor {
    // Let-fields are not immutable in the class destructor.
    return
  }

  for inst in function.instructions {
    switch inst {

    // First task of lowering: insert `end_init_let_ref` instructions in class initializers.
    case let markUninitialized as MarkUninitializedInst
         where markUninitialized.type.isClass &&
               // TODO: support move-only classes
               !markUninitialized.type.isMoveOnly &&
               // We only have to do that for root classes because derived classes call the super-initializer
               // _after_ all fields in the derived class are already initialized.
               markUninitialized.kind == .rootSelf:

      insertEndInitInstructions(for: markUninitialized, context)

    // Second task of lowering: set the `immutable` flags.
    case let rea as RefElementAddrInst
         where rea.fieldIsLet && !rea.isInUninitializedRegion &&
               // TODO: support move-only classes
               !rea.instance.type.isMoveOnly:
      rea.set(isImmutable: true, context)

    default:
      break
    }
  }
}

private func insertEndInitInstructions(for markUninitialized: MarkUninitializedInst, _ context: FunctionPassContext) {
  assert(!markUninitialized.type.isAddress, "self of class should not be an address")

  // The region which contains all let-field initializations, including any partial
  // let-field de-initializations (in case of a fail-able or throwing initializer).
  var initRegion = InstructionRange(begin: markUninitialized, context)
  defer { initRegion.deinitialize() }

  constructLetInitRegion(of: markUninitialized, result: &initRegion, context)

  insertEndInitInstructions(for: markUninitialized, atEndOf: initRegion, context)
}

private func insertEndInitInstructions(
  for markUninitialized: MarkUninitializedInst,
  atEndOf initRegion: InstructionRange,
  _ context: FunctionPassContext
) {
  var ssaUpdater = SSAUpdater(function: markUninitialized.parentFunction,
                              type: markUninitialized.type, ownership: .owned, context)
  ssaUpdater.addAvailableValue(markUninitialized, in: markUninitialized.parentBlock)

  for endInst in initRegion.ends {
    let builder = Builder(after: endInst, context)
    let newValue = builder.createEndInitLetRef(operand: markUninitialized)
    ssaUpdater.addAvailableValue(newValue, in: endInst.parentBlock)
  }

  for exitInst in initRegion.exits {
    let builder = Builder(before: exitInst, context)
    let newValue = builder.createEndInitLetRef(operand: markUninitialized)
    ssaUpdater.addAvailableValue(newValue, in: exitInst.parentBlock)
  }

  for use in markUninitialized.uses {
    if !initRegion.inclusiveRangeContains(use.instruction) &&
       !(use.instruction is EndInitLetRefInst)
    {
      use.set(to: ssaUpdater.getValue(atEndOf: use.instruction.parentBlock), context)
    }
  }
}

private func constructLetInitRegion(
  of markUninitialized: MarkUninitializedInst,
  result initRegion: inout InstructionRange,
  _ context: FunctionPassContext
) {
  // Adding the initial `mark_uninitialized` ensures that a single `end_init_let_ref` is inserted (after the
  // `mark_uninitialized`) in case there are no let-field accesses at all.
  // Note that we have to insert an `end_init_let_ref` even if there are no let-field initializations, because
  // derived classes could have let-field initializations in their initializers (which eventually call the
  // root-class initializer).
  initRegion.insert(markUninitialized)

  var borrows = Stack<BorrowIntroducingInstruction>(context)
  defer { borrows.deinitialize() }

  for inst in markUninitialized.parentFunction.instructions {
    switch inst {
    case let assign as AssignInst
         where assign.destination.isLetFieldAddress(of: markUninitialized):
      assert(assign.assignOwnership == .initialize)
      initRegion.insert(inst)

    case let store as StoreInst
         where store.destination.isLetFieldAddress(of: markUninitialized):
      assert(store.storeOwnership != .assign)
      initRegion.insert(inst)

    case let copy as CopyAddrInst
         where copy.destination.isLetFieldAddress(of: markUninitialized):
      assert(copy.isInitializationOfDest)
      initRegion.insert(inst)

    case let beginAccess as BeginAccessInst
         where beginAccess.accessKind == .deinit &&
               beginAccess.address.isLetFieldAddress(of: markUninitialized):
      // Include let-field partial de-initializations in the region.
      initRegion.insert(inst)

    case let beginBorrow as BeginBorrowInst
           where beginBorrow.borrowedValue.isReferenceDerived(from: markUninitialized):
      borrows.append(beginBorrow)

    case let storeBorrow as StoreBorrowInst
           where storeBorrow.source.isReferenceDerived(from: markUninitialized):
      borrows.append(storeBorrow)

    default:
      break
    }
  }

  // Extend the region to whole borrow scopes to avoid that we insert an `end_init_let_ref` in the
  // middle of a borrow scope.
  for borrow in borrows where initRegion.contains(borrow) {
    initRegion.insert(borrowScopeOf: borrow, context)
  }
}

private extension RefElementAddrInst {
  var isInUninitializedRegion: Bool {
    var root = self.instance
    while true {
      switch root {
      case let beginBorrow as BeginBorrowInst:
        root = beginBorrow.borrowedValue
      case let loadBorrow as LoadBorrowInst:
        // Initializers of derived classes store `self` into a stack location from where
        // it's loaded via a `load_borrow`.
        root = loadBorrow.address
      case is MarkUninitializedInst:
        return true
      default:
        return false
      }
    }
  }
}

private extension Value {
  func isReferenceDerived(from root: Value) -> Bool {
    var parent: Value = self
    while true {
      if parent == root {
        return true
      }
      if let operand = parent.forwardingInstruction?.singleForwardedOperand {
        parent = operand.value
        continue
      }
      if let transition = parent.definingInstruction as? OwnershipTransitionInstruction {
        parent = transition.operand.value
        continue
      }
      return false
    }
  }

  func isLetFieldAddress(of markUninitialized: MarkUninitializedInst) -> Bool {
    if case .class(let rea) = self.accessBase,
       rea.fieldIsLet,
       rea.instance.isReferenceDerived(from: markUninitialized)
    {
      return true
    }
    return false
  }
}