File: Argument.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 (545 lines) | stat: -rw-r--r-- 17,085 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//===--- Argument.swift - Defines the Argument classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 Basic
import SILBridging

/// A basic block argument.
///
/// Maps to both, SILPhiArgument and SILFunctionArgument.
public class Argument : Value, Hashable {
  public var definingInstruction: Instruction? { nil }

  public var parentBlock: BasicBlock {
    return bridged.getParent().block
  }

  var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) }
  
  public var index: Int {
    return parentBlock.arguments.firstIndex(of: self)!
  }

  public var isReborrow: Bool { bridged.isReborrow() }

  public var varDecl: VarDecl? { VarDecl(bridged: bridged.getVarDecl()) }

  public var sourceLoc: SourceLoc? { varDecl?.sourceLoc }

  public static func ==(lhs: Argument, rhs: Argument) -> Bool {
    lhs === rhs
  }

  public func hash(into hasher: inout Hasher) {
    hasher.combine(ObjectIdentifier(self))
  }
}

final public class FunctionArgument : Argument {
  public var convention: ArgumentConvention {
    parentFunction.argumentConventions[index]
  }

  public var isSelf: Bool {
    parentFunction.argumentConventions.selfIndex == index
  }

  // FIXME: This is incorrect in two cases: it does not include the
  // indirect error result, and, prior to address lowering, does not
  // include pack results.
  public var isIndirectResult: Bool {
    return index < parentFunction.numIndirectResultArguments
  }

  public var hasResultDependsOn : Bool {
    return bridged.hasResultDependsOn()
  }

  /// If the function's result depends on this argument, return the
  /// kind of dependence.
  public var resultDependence: LifetimeDependenceConvention? {
    parentFunction.argumentConventions[resultDependsOn: index]
  }
}

public struct Phi {
  public let value: Argument

  // TODO: Remove the CondBr case. All passes avoid critical edges. It
  // is only included here for compatibility with .sil tests that have
  // not been migrated.
  public init?(_ value: Value) {
    guard let argument = value as? Argument else { return nil }
    var preds = argument.parentBlock.predecessors
    guard let pred = preds.next() else { return nil }
    let term = pred.terminator
    guard term is BranchInst || term is CondBranchInst else { return nil }
    self.value = argument
  }

  public init?(using operand: Operand) {
    switch operand.instruction {
    case let br as BranchInst:
      self.init(br.getArgument(for: operand))
    case let condBr as CondBranchInst:
      guard let arg = condBr.getArgument(for: operand) else { return nil }
      self.init(arg)
    default:
      return nil
    }
  }

  public var predecessors: PredecessorList {
    return value.parentBlock.predecessors
  }

  public var successor: BasicBlock {
    return value.parentBlock
  }

  public func incomingOperand(inPredecessor predecessor: BasicBlock)
  -> Operand {
    let blockArgIdx = value.index
    switch predecessor.terminator {
    case let br as BranchInst:
      return br.operands[blockArgIdx]
    case let condBr as CondBranchInst:
      if condBr.trueBlock == successor {
        assert(condBr.falseBlock != successor)
        return condBr.trueOperands[blockArgIdx]
      } else {
        assert(condBr.falseBlock == successor)
        return condBr.falseOperands[blockArgIdx]
      }
    default:
      fatalError("wrong terminator for phi-argument")
    }
  }

  public var incomingOperands: LazyMapSequence<PredecessorList, Operand> {
    predecessors.lazy.map { incomingOperand(inPredecessor: $0) }
  }

  public var incomingValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> {
    incomingOperands.lazy.map { $0.value }
  }

  public var isReborrow: Bool { value.isReborrow }

  public var endsLifetime: Bool {
    value.ownership == .owned || value.isReborrow
  }

  public static func ==(lhs: Phi, rhs: Phi) -> Bool {
    lhs.value === rhs.value
  }

  public func hash(into hasher: inout Hasher) {
    value.hash(into: &hasher)
  }
}

public struct TerminatorResult {
  public let value: Argument

  public init?(_ value: Value) {
    guard let argument = value as? Argument else { return nil }
    var preds = argument.parentBlock.predecessors
    guard let pred = preds.next() else { return nil }
    let term = pred.terminator
    if term is BranchInst || term is CondBranchInst { return nil }
    self.value = argument
  }

  public var terminator: TermInst {
    var preds = value.parentBlock.predecessors
    return preds.next()!.terminator
  }
  
  public var predecessor: BasicBlock {
    return terminator.parentBlock
  }

  public var successor: BasicBlock {
    return value.parentBlock
  }

  public static func ==(lhs: TerminatorResult, rhs: TerminatorResult) -> Bool {
    lhs.value == rhs.value
  }

  public func hash(into hasher: inout Hasher) {
    value.hash(into: &hasher)
  }
}

/// ArgumentConventions indexed on a SIL function's argument index.
/// When derived from an ApplySite, this corresponds to the callee
/// function's argument index.
///
/// When derived from an ApplySite, `convention` is the substituted
/// convention. Substitution only affects the type inside ResultInfo
/// and ParameterInfo. It does not change the resulting
/// ArgumentConvention, ResultConvention, or LifetimeDependenceInfo.
public struct ArgumentConventions : Collection, CustomStringConvertible {
  public let convention: FunctionConvention

  public var startIndex: Int { 0 }

  public var endIndex: Int {
    firstParameterIndex + convention.parameters.count
  }

  public func index(after index: Int) -> Int {
    return index + 1
  }

  public subscript(_ argumentIndex: Int) -> ArgumentConvention {
    if let paramIdx = parameterIndex(for: argumentIndex) {
      return convention.parameters[paramIdx].convention
    }
    let resultInfo = convention.indirectSILResults[argumentIndex]
    return ArgumentConvention(result: resultInfo.convention)
  }

  public subscript(result argumentIndex: Int) -> ResultInfo? {
    if parameterIndex(for: argumentIndex) != nil {
      return nil
    }
    return convention.indirectSILResults[argumentIndex]
  }

  public subscript(parameter argumentIndex: Int) -> ParameterInfo? {
    guard let paramIdx = parameterIndex(for: argumentIndex) else {
      return nil
    }
    return convention.parameters[paramIdx]
  }

  /// Return a dependence of the function results on the indexed parameter.
  public subscript(resultDependsOn argumentIndex: Int)
    -> LifetimeDependenceConvention? {
    guard let paramIdx = parameterIndex(for: argumentIndex) else {
      return nil
    }
    return convention.resultDependencies?[paramIdx]
  }

  /// Number of SIL arguments for the function type's results
  /// including the error result. Use this to avoid lazy iteration
  /// over indirectSILResults to find the count.
  var indirectSILResultCount: Int {
    convention.indirectSILResultCount
  }

  /// The SIL argument index of the function type's first parameter.
  public var firstParameterIndex: Int { indirectSILResultCount }

  /// The SIL argument index of the 'self' parameter.
  var selfIndex: Int? {
    guard convention.hasSelfParameter else { return nil }
    // self is the last parameter
    return endIndex - 1
  }

  public var description: String {
    let origTy = convention.bridgedFunctionType
    var str = String(taking: origTy.getDebugDescription())
    for idx in startIndex..<indirectSILResultCount {
      str += "\n[\(idx)]  indirect result: " + self[idx].description
    }
    for idx in indirectSILResultCount..<endIndex {
      str += "\n[\(idx)]        parameter: " + self[idx].description
      if let dep = self[resultDependsOn: idx] {
        str += "resultDependsOn: " + dep.description
      }
    }
    return str
  }
}

extension ArgumentConventions {
  private func parameterIndex(for argIdx: Int) -> Int? {
    let firstParamIdx = firstParameterIndex  // bridging call
    return argIdx < firstParamIdx ? nil : argIdx - firstParamIdx
  }
}

public struct YieldConventions : Collection, CustomStringConvertible {
  public let convention: FunctionConvention

  public var yields: FunctionConvention.Yields {
    return convention.yields
  }

  public var startIndex: Int { 0 }

  public var endIndex: Int { yields.count }

  public func index(after index: Int) -> Int {
    return index + 1
  }

  public subscript(_ index: Int) -> ArgumentConvention {
    return yields[index].convention
  }

  public var description: String {
    var str = String(
      taking: convention.bridgedFunctionType.getDebugDescription())
    yields.forEach {
      str += "\n      yield: " + $0.description
    }
    return str
  }
}

public enum ArgumentConvention : CustomStringConvertible {
  /// This argument is passed indirectly, i.e. by directly passing the address
  /// of an object in memory.  The callee is responsible for destroying the
  /// object.  The callee may assume that the address does not alias any valid
  /// object.
  case indirectIn

  /// This argument is passed indirectly, i.e. by directly passing the address
  /// of an object in memory.  The callee may not modify and does not destroy
  /// the object.
  case indirectInGuaranteed

  /// This argument is passed indirectly, i.e. by directly passing the address
  /// of an object in memory.  The object is always valid, but the callee may
  /// assume that the address does not alias any valid object and reorder loads
  /// stores to the parameter as long as the whole object remains valid. Invalid
  /// single-threaded aliasing may produce inconsistent results, but should
  /// remain memory safe.
  case indirectInout

  /// This argument is passed indirectly, i.e. by directly passing the address
  /// of an object in memory. The object is allowed to be aliased by other
  /// well-typed references, but is not allowed to be escaped. This is the
  /// convention used by mutable captures in @noescape closures.
  case indirectInoutAliasable

  /// This argument represents an indirect return value address. The callee stores
  /// the returned value to this argument. At the time when the function is called,
  /// the memory location referenced by the argument is uninitialized.
  case indirectOut

  /// This argument is passed directly.  Its type is non-trivial, and the callee
  /// is responsible for destroying it.
  case directOwned

  /// This argument is passed directly.  Its type may be trivial, or it may
  /// simply be that the callee is not responsible for destroying it. Its
  /// validity is guaranteed only at the instant the call begins.
  case directUnowned

  /// This argument is passed directly.  Its type is non-trivial, and the caller
  /// guarantees its validity for the entirety of the call.
  case directGuaranteed

  /// This argument is a value pack of mutable references to storage,
  /// which the function is being given exclusive access to.  The elements
  /// must be passed indirectly.
  case packInout

  /// This argument is a value pack, and ownership of the elements is being
  /// transferred into this function.  Whether the elements are passed
  /// indirectly is recorded in the pack type.
  case packOwned

  /// This argument is a value pack, and ownership of the elements is not
  /// being transferred into this function.  Whether the elements are passed
  /// indirectly is recorded in the pack type.
  case packGuaranteed

  /// This argument is a pack of indirect return value addresses.  The
  /// addresses are stored in the pack by the caller and read out by the
  /// callee; within the callee, they are individually treated like
  /// indirectOut arguments.
  case packOut

  public init(result: ResultConvention) {
    switch result {
    case .indirect:
      self = .indirectOut
    case .owned:
      self = .directOwned
    case .unowned, .unownedInnerPointer, .autoreleased:
      self = .directUnowned
    case .pack:
      self = .packOut
    }
  }

  public var isIndirect: Bool {
    switch self {
    case .indirectIn, .indirectInGuaranteed,
         .indirectInout, .indirectInoutAliasable, .indirectOut,
         .packOut, .packInout, .packOwned, .packGuaranteed:
      return true
    case .directOwned, .directUnowned, .directGuaranteed:
      return false
    }
  }

  public var isIndirectIn: Bool {
    switch self {
    case .indirectIn, .indirectInGuaranteed,
         .packOwned, .packGuaranteed:
      return true
    case .directOwned, .directUnowned, .directGuaranteed,
         .indirectInout, .indirectInoutAliasable, .indirectOut,
         .packOut, .packInout:
      return false
    }
  }

  public var isIndirectOut: Bool {
    switch self {
    case .indirectOut, .packOut:
      return true
    case .indirectInGuaranteed, .directGuaranteed, .packGuaranteed,
         .indirectIn, .directOwned, .directUnowned,
         .indirectInout, .indirectInoutAliasable,
         .packInout, .packOwned:
      return false
    }
  }

  public var isGuaranteed: Bool {
    switch self {
    case .indirectInGuaranteed, .directGuaranteed, .packGuaranteed:
      return true
    case .indirectIn, .directOwned, .directUnowned,
         .indirectInout, .indirectInoutAliasable, .indirectOut,
         .packOut, .packInout, .packOwned:
      return false
    }
  }

  public var isExclusiveIndirect: Bool {
    switch self {
    case .indirectIn,
         .indirectOut,
         .indirectInGuaranteed,
         .indirectInout,
         .packOut,
         .packInout,
         .packOwned,
         .packGuaranteed:
      return true

    case .indirectInoutAliasable,
         .directUnowned,
         .directGuaranteed,
         .directOwned:
      return false
    }
  }

  public var isInout: Bool {
    switch self {
    case .indirectInout,
         .indirectInoutAliasable,
         .packInout:
      return true

    case .indirectIn,
         .indirectOut,
         .indirectInGuaranteed,
         .directUnowned,
         .directGuaranteed,
         .directOwned,
         .packOut,
         .packOwned,
         .packGuaranteed:
      return false
    }
  }

  public var description: String {
    switch self {
    case .indirectIn:
      return "indirectIn"
    case .indirectInGuaranteed:
      return "indirectInGuaranteed"
    case .indirectInout:
      return "indirectInout"
    case .indirectInoutAliasable:
      return "indirectInoutAliasable"
    case .indirectOut:
      return "indirectOut"
    case .directOwned:
      return "directOwned"
    case .directUnowned:
      return "directUnowned"
    case .directGuaranteed:
      return "directGuaranteed"
    case .packInout:
      return "packInout"
    case .packOwned:
      return "packOwned"
    case .packGuaranteed:
      return "packGuaranteed"
    case .packOut:
      return "packOut"
    }
  }
}

// Bridging utilities

extension BridgedArgument {
  public var argument: Argument { obj.getAs(Argument.self) }
  public var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) }
}

extension BridgedArgumentConvention {
  var convention: ArgumentConvention {
    switch self {
      case .Indirect_In:             return .indirectIn
      case .Indirect_In_Guaranteed:  return .indirectInGuaranteed
      case .Indirect_Inout:          return .indirectInout
      case .Indirect_InoutAliasable: return .indirectInoutAliasable
      case .Indirect_Out:            return .indirectOut
      case .Direct_Owned:            return .directOwned
      case .Direct_Unowned:          return .directUnowned
      case .Direct_Guaranteed:       return .directGuaranteed
      case .Pack_Out:                return .packOut
      case .Pack_Inout:              return .packInout
      case .Pack_Owned:              return .packOwned
      case .Pack_Guaranteed:         return .packGuaranteed
      default:
        fatalError("unsupported argument convention")
    }
  }
}

extension ArgumentConvention {
  var bridged: BridgedArgumentConvention {
    switch self {
      case .indirectIn:             return .Indirect_In
      case .indirectInGuaranteed:   return .Indirect_In_Guaranteed
      case .indirectInout:          return .Indirect_Inout
      case .indirectInoutAliasable: return .Indirect_InoutAliasable
      case .indirectOut:            return .Indirect_Out
      case .directOwned:            return .Direct_Owned
      case .directUnowned:          return .Direct_Unowned
      case .directGuaranteed:       return .Direct_Guaranteed
      case .packOut:                return .Pack_Out
      case .packInout:              return .Pack_Inout
      case .packOwned:              return .Pack_Owned
      case .packGuaranteed:         return .Pack_Guaranteed
    }
  }
}