content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
//===--- SimplifyBeginCOWMutation.swift - Simplify begin_cow_mutation -----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension BeginCOWMutationInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n /// The buffer of an empty Array/Set/Dictionary singleton is known to be not\n /// unique. Replace the uniqueness result of such a\n /// `begin_cow_mutation` with a zero `integer_literal`, e.g.\n ///\n /// %3 = global_addr @_swiftEmptyArrayStorage\n /// %4 = address_to_pointer %3\n /// %5 = raw_pointer_to_ref %4\n /// %6 = unchecked_ref_cast %5\n /// (%u, %b) = begin_cow_mutation %6\n /// ->\n /// [...]\n /// (%not_used, %b) = begin_cow_mutation %6\n /// %u = integer_literal $Builtin.Int1, 0\n ///\n optimizeEmptySingleton(context)\n\n /// If the only use of the `begin_cow_instruction` is an `end_cow_instruction`,\n /// remove the pair, e.g.\n ///\n /// (%u, %b) = begin_cow_mutation %0 : $Buffer\n /// %e = end_cow_mutation %b : $Buffer\n ///\n if optimizeEmptyBeginEndPair(context) {\n return\n }\n\n /// If the operand of the `begin_cow_instruction` is an `end_cow_instruction`,\n /// which has no other uses, remove the pair, e.g.\n ///\n /// %e = end_cow_mutation %0 : $Buffer\n /// (%u, %b) = begin_cow_mutation %e : $Buffer\n ///\n if optimizeEmptyEndBeginPair(context) {\n return\n }\n }\n}\n\nprivate extension BeginCOWMutationInst {\n\n func optimizeEmptySingleton(_ context: SimplifyContext) {\n if !isEmptyCOWSingleton(instance) {\n return\n }\n if uniquenessResult.uses.ignoreDebugUses.isEmpty {\n /// Don't create an integer_literal which would be dead. This would result\n /// in an infinite loop in SILCombine.\n return\n }\n let builder = Builder(before: self, location: location, context)\n let zero = builder.createIntegerLiteral(0, type: uniquenessResult.type);\n uniquenessResult.uses.replaceAll(with: zero, context)\n }\n\n func optimizeEmptyBeginEndPair(_ context: SimplifyContext) -> Bool {\n if !uniquenessResult.uses.ignoreDebugUses.isEmpty {\n return false\n }\n let buffer = instanceResult\n guard buffer.uses.ignoreDebugUses.allSatisfy({\n if let endCOW = $0.instruction as? EndCOWMutationInst {\n return !endCOW.doKeepUnique\n }\n return false\n }) else\n {\n return false\n }\n\n for use in buffer.uses.ignoreDebugUses {\n let endCOW = use.instruction as! EndCOWMutationInst\n endCOW.replace(with: instance, context)\n }\n context.erase(instructionIncludingDebugUses: self)\n return true\n }\n\n func optimizeEmptyEndBeginPair(_ context: SimplifyContext) -> Bool {\n if !uniquenessResult.uses.ignoreDebugUses.isEmpty {\n return false\n }\n guard let endCOW = instance as? EndCOWMutationInst,\n !endCOW.doKeepUnique else {\n return false\n }\n if endCOW.uses.ignoreDebugUses.contains(where: { $0.instruction != self }) {\n return false\n }\n\n instanceResult.uses.replaceAll(with: endCOW.instance, context)\n context.erase(instructionIncludingDebugUses: self)\n context.erase(instructionIncludingDebugUses: endCOW)\n return true\n }\n}\n\nprivate func isEmptyCOWSingleton(_ value: Value) -> Bool {\n var v = value\n while true {\n switch v {\n case is UncheckedRefCastInst,\n is UpcastInst,\n is RawPointerToRefInst,\n is AddressToPointerInst,\n is CopyValueInst:\n v = (v as! UnaryInstruction).operand.value\n case let globalAddr as GlobalAddrInst:\n let name = globalAddr.global.name\n return name == "_swiftEmptyArrayStorage" ||\n name == "_swiftEmptyDictionarySingleton" ||\n name == "_swiftEmptySetSingleton"\n default:\n return false\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBeginCOWMutation.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBeginCOWMutation.swift
Swift
4,259
0.95
0.097744
0.322314
vue-tools
959
2024-02-08T07:33:59.792881
Apache-2.0
false
7351d22309d4d9929f33d68ac29af323
//===--- SimplifyBranch.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension BranchInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n tryMergeWithTargetBlock(context)\n }\n}\n\nprivate extension BranchInst {\n func tryMergeWithTargetBlock(_ context: SimplifyContext) {\n if canMergeWithTargetBlock {\n mergeWithTargetBlock(context)\n }\n }\n\n var canMergeWithTargetBlock: Bool {\n // We can only merge if there is a 1:1 relation to the target block.\n guard let pred = targetBlock.singlePredecessor else {\n return false\n }\n assert(pred == parentBlock)\n\n // Ignore self cycles\n if targetBlock == parentBlock {\n return false\n }\n\n if hasInvalidDominanceCycle {\n return false\n }\n\n return true\n }\n\n func mergeWithTargetBlock(_ context: SimplifyContext) {\n let targetBB = targetBlock\n let parentBB = parentBlock\n\n for (argIdx, op) in operands.enumerated() {\n let arg = targetBB.arguments[argIdx]\n if let phi = Phi(arg),\n let bfi = phi.borrowedFrom\n {\n bfi.replace(with: op.value, context)\n } else {\n arg.uses.replaceAll(with: op.value, context)\n }\n }\n targetBB.eraseAllArguments(context)\n\n if context.preserveDebugInfo {\n let builder = Builder(before: self, context)\n builder.createDebugStep()\n }\n context.erase(instruction: self)\n\n // Move instruction from the smaller block to the larger block.\n // The order is essential because if many blocks are merged and this is done\n // in the wrong order, we end up with quadratic complexity.\n //\n if parentBB.hasLessInstructions(than: targetBB) &&\n parentBB != parentBB.parentFunction.entryBlock {\n for pred in parentBB.predecessors {\n pred.terminator.replaceBranchTarget(from: parentBB, to: targetBB, context)\n }\n parentBB.moveAllInstructions(toBeginOf: targetBB, context)\n parentBB.moveAllArguments(to: targetBB, context)\n context.erase(block: parentBB)\n } else {\n targetBB.moveAllInstructions(toEndOf: parentBB, context)\n context.erase(block: targetBB)\n }\n }\n}\n\nprivate extension BasicBlock {\n func hasLessInstructions(than otherBlock: BasicBlock) -> Bool {\n var insts = instructions\n var otherInsts = otherBlock.instructions\n while true {\n if otherInsts.next() == nil {\n return false\n }\n if insts.next() == nil {\n return true\n }\n }\n }\n}\n\nprivate extension BranchInst {\n\n // True if this block is part of an unreachable cfg cycle, where an argument dominates itself.\n // For example:\n // ```\n // bb1(arg1): // preds: bb2\n // br bb2\n //\n // bb2: // preds: bb1\n // br bb1(arg1)\n // ```\n var hasInvalidDominanceCycle: Bool {\n for (argIdx, op) in operands.enumerated() {\n if targetBlock.arguments[argIdx] == op.value {\n return true\n }\n }\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBranch.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBranch.swift
Swift
3,375
0.95
0.147541
0.240741
python-kit
958
2025-02-05T23:27:11.016467
Apache-2.0
false
33be83bdd31a7a5ff9b280f8f870210b
//===--- SimplifyBuiltin.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension BuiltinInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n switch id {\n case .IsConcrete:\n // Don't constant fold a Builtin.isConcrete of a type with archetypes in the middle\n // of the pipeline, because a generic specializer might run afterwards which turns the\n // type into a concrete type.\n optimizeIsConcrete(allowArchetypes: false, context)\n case .IsSameMetatype:\n optimizeIsSameMetatype(context)\n case .Once:\n optimizeBuiltinOnce(context)\n case .CanBeObjCClass:\n optimizeCanBeClass(context)\n case .AssertConf:\n optimizeAssertConfig(context)\n case .Sizeof,\n .Strideof,\n .Alignof:\n optimizeTargetTypeConst(context)\n case .DestroyArray:\n let elementType = substitutionMap.replacementType.loweredType(in: parentFunction, maximallyAbstracted: true)\n if elementType.isTrivial(in: parentFunction) {\n context.erase(instruction: self)\n return\n }\n optimizeArgumentToThinMetatype(argument: 0, context)\n case .CopyArray,\n .TakeArrayNoAlias,\n .TakeArrayFrontToBack,\n .TakeArrayBackToFront,\n .AssignCopyArrayNoAlias,\n .AssignCopyArrayFrontToBack,\n .AssignCopyArrayBackToFront,\n .AssignTakeArray,\n .IsPOD:\n optimizeArgumentToThinMetatype(argument: 0, context)\n case .ICMP_EQ:\n constantFoldIntegerEquality(isEqual: true, context)\n case .ICMP_NE:\n constantFoldIntegerEquality(isEqual: false, context)\n default:\n if let literal = constantFold(context) {\n uses.replaceAll(with: literal, context)\n }\n }\n }\n}\n\nextension BuiltinInst : LateOnoneSimplifiable {\n func simplifyLate(_ context: SimplifyContext) {\n if id == .IsConcrete {\n // At the end of the pipeline we can be sure that the isConcrete's type doesn't get "more" concrete.\n optimizeIsConcrete(allowArchetypes: true, context)\n } else {\n simplify(context)\n }\n }\n}\n\nprivate extension BuiltinInst {\n func optimizeIsConcrete(allowArchetypes: Bool, _ context: SimplifyContext) {\n let hasArchetype = operands[0].value.type.hasArchetype\n if hasArchetype && !allowArchetypes {\n return\n }\n let builder = Builder(before: self, context)\n let result = builder.createIntegerLiteral(hasArchetype ? 0 : 1, type: type)\n uses.replaceAll(with: result, context)\n context.erase(instruction: self)\n }\n\n func optimizeIsSameMetatype(_ context: SimplifyContext) {\n let lhs = operands[0].value\n let rhs = operands[1].value\n\n guard let equal = typesOfValuesAreEqual(lhs, rhs, in: parentFunction) else {\n return\n }\n let builder = Builder(before: self, context)\n let result = builder.createIntegerLiteral(equal ? 1 : 0, type: type)\n\n uses.replaceAll(with: result, context)\n }\n\n func optimizeBuiltinOnce(_ context: SimplifyContext) {\n guard let callee = calleeOfOnce, callee.isDefinition else {\n return\n }\n context.notifyDependency(onBodyOf: callee)\n\n // If the callee is side effect-free we can remove the whole builtin "once".\n // We don't use the callee's memory effects but instead look at all callee instructions\n // because memory effects are not computed in the Onone pipeline, yet.\n // This is no problem because the callee (usually a global init function )is mostly very small,\n // or contains the side-effect instruction `alloc_global` right at the beginning.\n if callee.instructions.contains(where: hasSideEffectForBuiltinOnce) {\n return\n }\n for use in uses {\n let ga = use.instruction as! GlobalAddrInst\n ga.clearToken(context)\n }\n context.erase(instruction: self)\n }\n\n var calleeOfOnce: Function? {\n let callee = operands[1].value\n if let fri = callee as? FunctionRefInst {\n return fri.referencedFunction\n }\n return nil\n }\n\n func optimizeCanBeClass(_ context: SimplifyContext) {\n let literal: IntegerLiteralInst\n switch substitutionMap.replacementType.canonical.canBeClass {\n case .isNot:\n let builder = Builder(before: self, context)\n literal = builder.createIntegerLiteral(0, type: type)\n case .is:\n let builder = Builder(before: self, context)\n literal = builder.createIntegerLiteral(1, type: type)\n case .canBe:\n return\n }\n self.replace(with: literal, context)\n }\n\n func optimizeAssertConfig(_ context: SimplifyContext) {\n // The values for the assert_configuration call are:\n // 0: Debug\n // 1: Release\n // 2: Fast / Unchecked\n let config = context.options.assertConfiguration\n switch config {\n case .debug, .release, .unchecked:\n let builder = Builder(before: self, context)\n let literal = builder.createIntegerLiteral(config.integerValue, type: type)\n uses.replaceAll(with: literal, context)\n context.erase(instruction: self)\n case .unknown:\n return\n }\n }\n \n func optimizeTargetTypeConst(_ context: SimplifyContext) {\n let ty = substitutionMap.replacementType.loweredType(in: parentFunction, maximallyAbstracted: true)\n let value: Int?\n switch id {\n case .Sizeof:\n value = ty.getStaticSize(context: context)\n case .Strideof:\n value = ty.getStaticStride(context: context)\n case .Alignof:\n value = ty.getStaticAlignment(context: context)\n default:\n fatalError()\n }\n \n guard let value else {\n return\n }\n \n let builder = Builder(before: self, context)\n let literal = builder.createIntegerLiteral(value, type: type)\n uses.replaceAll(with: literal, context)\n context.erase(instruction: self)\n }\n \n func optimizeArgumentToThinMetatype(argument: Int, _ context: SimplifyContext) {\n let type: Type\n\n if let metatypeInst = operands[argument].value as? MetatypeInst {\n type = metatypeInst.type\n } else if let initExistentialInst = operands[argument].value as? InitExistentialMetatypeInst {\n type = initExistentialInst.metatype.type\n } else {\n return\n }\n\n guard type.representationOfMetatype == .thick else {\n return\n }\n \n let builder = Builder(before: self, context)\n let newMetatype = builder.createMetatype(ofInstanceType: type.canonicalType.instanceTypeOfMetatype,\n representation: .thin)\n operands[argument].set(to: newMetatype, context)\n }\n\n func constantFoldIntegerEquality(isEqual: Bool, _ context: SimplifyContext) {\n if constantFoldStringNullPointerCheck(isEqual: isEqual, context) {\n return\n }\n if let literal = constantFold(context) {\n uses.replaceAll(with: literal, context)\n }\n }\n\n func constantFoldStringNullPointerCheck(isEqual: Bool, _ context: SimplifyContext) -> Bool {\n if operands[1].value.isZeroInteger &&\n operands[0].value.lookThroughScalarCasts is StringLiteralInst\n {\n let builder = Builder(before: self, context)\n let result = builder.createIntegerLiteral(isEqual ? 0 : 1, type: type)\n uses.replaceAll(with: result, context)\n context.erase(instruction: self)\n return true\n }\n return false\n }\n}\n\nprivate extension Value {\n var isZeroInteger: Bool {\n if let literal = self as? IntegerLiteralInst,\n let value = literal.value\n {\n return value == 0\n }\n return false\n }\n\n var lookThroughScalarCasts: Value {\n guard let bi = self as? BuiltinInst else {\n return self\n }\n switch bi.id {\n case .ZExt, .ZExtOrBitCast, .PtrToInt:\n return bi.operands[0].value.lookThroughScalarCasts\n default:\n return self\n }\n }\n}\n\nprivate func hasSideEffectForBuiltinOnce(_ instruction: Instruction) -> Bool {\n switch instruction {\n case is DebugStepInst, is DebugValueInst:\n return false\n default:\n return instruction.mayReadOrWriteMemory ||\n instruction.hasUnspecifiedSideEffects\n }\n}\n\nprivate func typesOfValuesAreEqual(_ lhs: Value, _ rhs: Value, in function: Function) -> Bool? {\n if lhs == rhs {\n return true\n }\n\n guard let lhsExistential = lhs as? InitExistentialMetatypeInst,\n let rhsExistential = rhs as? InitExistentialMetatypeInst else {\n return nil\n }\n\n let lhsTy = lhsExistential.metatype.type.canonicalType.instanceTypeOfMetatype\n let rhsTy = rhsExistential.metatype.type.canonicalType.instanceTypeOfMetatype\n if lhsTy.isDynamicSelf != rhsTy.isDynamicSelf {\n return nil\n }\n\n // Do we know the exact types? This is not the case e.g. if a type is passed as metatype\n // to the function.\n let typesAreExact = lhsExistential.metatype is MetatypeInst &&\n rhsExistential.metatype is MetatypeInst\n\n if typesAreExact {\n // We need to compare the not lowered types, because function types may differ in their original version\n // but are equal in the lowered version, e.g.\n // ((Int, Int) -> ())\n // (((Int, Int)) -> ())\n //\n if lhsTy == rhsTy {\n return true\n }\n // Comparing types of different classes which are in a sub-class relation is not handled by the\n // cast optimizer (below).\n if lhsTy.isClass && rhsTy.isClass && lhsTy.nominal != rhsTy.nominal {\n return false\n }\n\n // Failing function casts are not supported by the cast optimizer (below).\n // (Reason: "Be conservative about function type relationships we may add in the future.")\n if lhsTy.isFunction && rhsTy.isFunction && lhsTy != rhsTy && !lhsTy.hasArchetype && !rhsTy.hasArchetype {\n return false\n }\n }\n\n // If casting in either direction doesn't work, the types cannot be equal.\n if !(canDynamicallyCast(from: lhsTy, to: rhsTy, in: function, sourceTypeIsExact: typesAreExact) ?? true) ||\n !(canDynamicallyCast(from: rhsTy, to: lhsTy, in: function, sourceTypeIsExact: typesAreExact) ?? true) {\n return false\n }\n return nil\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBuiltin.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyBuiltin.swift
Swift
10,415
0.95
0.125402
0.128571
node-utils
819
2025-07-08T00:34:18.375765
GPL-3.0
false
0a14666d37344ec3fbd17f464c3ebd99
//===--- SimplifyCheckedCast.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport AST\n\nextension CheckedCastAddrBranchInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n guard let castWillSucceed = self.dynamicCastResult else {\n return\n }\n if castWillSucceed {\n // TODO: handle cases where the operand address types are different.\n if source.type == destination.type {\n replaceSuccess(context)\n }\n } else {\n replaceFailure(context)\n }\n }\n}\n\nprivate extension CheckedCastAddrBranchInst {\n func replaceSuccess(_ context: SimplifyContext) {\n let builder = Builder(before: self, context)\n switch consumptionKind {\n case .TakeAlways, .TakeOnSuccess:\n builder.createCopyAddr(from: source, to: destination, takeSource: true, initializeDest: true)\n case .CopyOnSuccess:\n builder.createCopyAddr(from: source, to: destination, takeSource: false, initializeDest: true)\n }\n builder.createBranch(to: successBlock)\n context.erase(instruction: self)\n }\n\n func replaceFailure(_ context: SimplifyContext) {\n let builder = Builder(before: self, context)\n switch consumptionKind {\n case .TakeAlways:\n builder.createDestroyAddr(address: source)\n case .CopyOnSuccess, .TakeOnSuccess:\n break\n }\n builder.createBranch(to: failureBlock)\n context.erase(instruction: self)\n }\n}\n\nextension UnconditionalCheckedCastInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n tryOptimizeCastToExistentialMetatype(context)\n }\n}\n\nprivate extension UnconditionalCheckedCastInst {\n // Replace\n // %1 = unconditional_checked_cast %0 : $@thick T.Type to any P.Type\n // with\n // %1 = init_existential_metatype %0 : $@thick S.Type, $@thick any P.Type\n // if type T conforms to protocol P.\n // Note that init_existential_metatype is better than unconditional_checked_cast because it does not need\n // to do any runtime casting.\n func tryOptimizeCastToExistentialMetatype(_ context: SimplifyContext) {\n guard targetFormalType.isExistentialMetatype, sourceFormalType.isMetatype else {\n return\n }\n \n let instanceTy = targetFormalType.instanceTypeOfMetatype\n guard let nominal = instanceTy.nominal,\n let proto = nominal as? ProtocolDecl\n else {\n return\n }\n let conformance = sourceFormalType.instanceTypeOfMetatype.checkConformance(to: proto)\n guard conformance.isValid,\n conformance.matchesActorIsolation(in: parentFunction)\n else {\n return\n }\n \n let builder = Builder(before: self, context)\n let iemt = builder.createInitExistentialMetatype(metatype: operand.value, existentialType: self.type, conformances: [conformance])\n self.replace(with: iemt, context)\n } \n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCheckedCast.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCheckedCast.swift
Swift
3,250
0.95
0.074468
0.22093
node-utils
884
2024-03-28T07:15:08.235126
BSD-3-Clause
false
60118fcf69273baa3dca66c5aeb4acf2
//===--- SimplifyClassifyBridgeObject.swift -------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\nextension ClassifyBridgeObjectInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n // Constant fold `classify_bridge_object` to `(false, false)` if the operand is known\n // to be a swift class.\n var walker = CheckForSwiftClasses();\n if walker.walkUp(value: operand.value, path: UnusedWalkingPath()) == .abortWalk {\n return\n }\n\n let builder = Builder(before: self, context)\n let falseLiteral = builder.createIntegerLiteral(0, type: context.getBuiltinIntegerType(bitWidth: 1))\n let tp = builder.createTuple(type: self.type, elements: [falseLiteral, falseLiteral])\n uses.replaceAll(with: tp, context)\n context.erase(instruction: self)\n }\n}\n\nprivate struct CheckForSwiftClasses: ValueUseDefWalker {\n mutating func walkUp(value: Value, path: UnusedWalkingPath) -> WalkResult {\n if let nominal = value.type.nominal,\n let classDecl = nominal as? ClassDecl,\n !classDecl.isObjC\n {\n // Stop this use-def walk if the value is known to be a swift class.\n return .continueWalk\n }\n return walkUpDefault(value: value, path: path)\n }\n\n mutating func rootDef(value: Value, path: UnusedWalkingPath) -> WalkResult {\n return .abortWalk\n }\n\n var walkUpCache = WalkerCache<UnusedWalkingPath>()\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyClassifyBridgeObject.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyClassifyBridgeObject.swift
Swift
1,840
0.95
0.18
0.318182
node-utils
436
2024-08-03T04:34:31.098521
MIT
false
29da4f053bfc76b7d7fbf03ac3101d76
//===--- SimplifyCondBranch.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension CondBranchInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n tryConstantFold(context)\n }\n}\n\nprivate extension CondBranchInst {\n func tryConstantFold(_ context: SimplifyContext) {\n guard let literal = condition as? IntegerLiteralInst,\n let conditionValue = literal.value else\n {\n return\n }\n let builder = Builder(before: self, context)\n if conditionValue == 0 {\n builder.createBranch(to: falseBlock, arguments: Array(falseOperands.map { $0.value }))\n } else {\n builder.createBranch(to: trueBlock, arguments: Array(trueOperands.map { $0.value }))\n }\n context.erase(instruction: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCondBranch.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCondBranch.swift
Swift
1,206
0.95
0.083333
0.333333
node-utils
520
2024-05-07T00:47:22.367726
BSD-3-Clause
false
98dd9e42be0a66fd19714cd9fc6fd090
//===--- SimplifyCondFail.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension CondFailInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n /// Eliminates\n /// ```\n /// %0 = integer_literal 0\n /// cond_fail %0, "message"\n /// ```\n if let literal = condition as? IntegerLiteralInst,\n let value = literal.value,\n value == 0\n {\n context.erase(instruction: self)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCondFail.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCondFail.swift
Swift
898
0.95
0.1
0.592593
vue-tools
632
2025-02-21T18:58:20.235776
Apache-2.0
false
f850485c20921a4bd10e8c27fbf87560
//===--- SimplifyConvertEscapeToNoEscape.swift ----------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension ConvertEscapeToNoEscapeInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n tryCombineWithThinToThickOperand(context)\n }\n}\n\nprivate extension ConvertEscapeToNoEscapeInst {\n\n /// Combine with a thin_to_thick_function operand:\n ///\n /// %2 = thin_to_thick_function %1 to $() -> ()\n /// %3 = convert_escape_to_noescape %2 : $() -> () to $@noescape () -> ()\n /// ->\n /// %3 = thin_to_thick_function %1 to $@noescape () -> ()\n\n func tryCombineWithThinToThickOperand(_ context: SimplifyContext) {\n if let thinToThick = fromFunction as? ThinToThickFunctionInst {\n let builder = Builder(before: self, context)\n let noEscapeFnType = thinToThick.type.getFunctionType(withNoEscape: true)\n let newThinToThick = builder.createThinToThickFunction(thinFunction: thinToThick.operand.value,\n resultType: noEscapeFnType)\n uses.replaceAll(with: newThinToThick, context)\n context.erase(instruction: self)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyConvertEscapeToNoEscape.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyConvertEscapeToNoEscape.swift
Swift
1,565
0.95
0.075
0.485714
react-lib
403
2023-08-15T18:16:56.900150
MIT
false
fa02a5eecae654b94e6aa6b6dd4834fa
//===--- SimplifyCopyBlock.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension CopyBlockInst : Simplifiable, SILCombineSimplifiable {\n\n /// Removes a `copy_block` if its only uses, beside ownership instructions, are callees of function calls\n /// ```\n /// %2 = copy_block %0\n /// %3 = begin_borrow [lexical] %2\n /// %4 = apply %3() : $@convention(block) @noescape () -> ()\n /// end_borrow %3\n /// destroy_value %2\n /// ```\n /// ->\n /// ```\n /// %4 = apply %0() : $@convention(block) @noescape () -> ()\n /// ```\n ///\n func simplify(_ context: SimplifyContext) {\n if hasValidUses(block: self) {\n replaceBlock( self, with: operand.value, context)\n context.erase(instruction: self)\n }\n }\n}\n\nprivate func hasValidUses(block: Value) -> Bool {\n for use in block.uses {\n switch use.instruction {\n case let beginBorrow as BeginBorrowInst:\n if !hasValidUses(block: beginBorrow) {\n return false\n }\n case let apply as FullApplySite where apply.isCallee(operand: use):\n break\n case is EndBorrowInst, is DestroyValueInst:\n break\n default:\n return false\n }\n }\n return true\n}\n\nprivate func replaceBlock(_ block: Value, with original: Value, _ context: SimplifyContext) {\n for use in block.uses {\n switch use.instruction {\n case let beginBorrow as BeginBorrowInst:\n replaceBlock(beginBorrow, with: original, context)\n context.erase(instruction: beginBorrow)\n case is FullApplySite:\n use.set(to: original, context)\n case is EndBorrowInst, is DestroyValueInst:\n context.erase(instruction: use.instruction)\n default:\n fatalError("unhandled use")\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCopyBlock.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCopyBlock.swift
Swift
2,138
0.95
0.142857
0.369231
vue-tools
939
2025-06-18T08:49:37.648341
BSD-3-Clause
false
462366d137bc45e1d751663b158024e5
//===--- SimplifyCopyValue.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension CopyValueInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n if fromValue.ownership == .none {\n uses.replaceAll(with: fromValue, context)\n context.erase(instruction: self)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCopyValue.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyCopyValue.swift
Swift
785
0.95
0.136364
0.55
react-lib
946
2023-08-08T15:36:29.230654
BSD-3-Clause
false
bb8e4e2412cf926404a08051e3bdd883
//===--- SimplifyDebugStep.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension DebugStepInst : Simplifiable {\n func simplify(_ context: SimplifyContext) {\n // When compiling with optimizations (note: it's not a OnoneSimplifiable transformation),\n // unconditionally remove debug_step instructions.\n context.erase(instruction: self)\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDebugStep.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDebugStep.swift
Swift
812
0.95
0.090909
0.684211
node-utils
338
2025-05-07T10:10:45.933228
Apache-2.0
false
184b94c2910620866490adb043d9e077
//===--- SimplifyDestroyValue.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension DestroyValueInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n if destroyedValue.ownership == .none {\n context.erase(instruction: self)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDestroyValue.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDestroyValue.swift
Swift
745
0.95
0.142857
0.578947
node-utils
590
2024-06-01T03:26:19.942862
MIT
false
a8ae03d7d710745518a0398ddc204480
//===--- SimplifyDestructure.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension DestructureTupleInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // If the tuple is trivial, replace\n // ```\n // (%1, %2) = destructure_tuple %t\n // ```\n // ->\n // ```\n // %1 = tuple_extract %t, 0\n // %2 = tuple_extract %t, 1\n // ```\n // This canonicalization helps other optimizations to e.g. CSE tuple_extracts.\n //\n if replaceWithTupleExtract(context) {\n return\n }\n\n // Eliminate the redundant instruction pair\n // ```\n // %t = tuple (%0, %1, %2)\n // (%3, %4, %5) = destructure_tuple %t\n // ```\n // and replace the results %3, %4, %5 with %0, %1, %2, respectively\n //\n if let tuple = self.tuple as? TupleInst {\n tryReplaceConstructDestructPair(construct: tuple, destruct: self, context)\n }\n }\n\n private func replaceWithTupleExtract(_ context: SimplifyContext) -> Bool {\n guard self.tuple.type.isTrivial(in: parentFunction) else {\n return false\n }\n let builder = Builder(before: self, context)\n for (elementIdx, result) in results.enumerated() {\n let elementValue = builder.createTupleExtract(tuple: self.tuple, elementIndex: elementIdx)\n result.uses.replaceAll(with: elementValue, context)\n }\n context.erase(instruction: self)\n return true\n }\n}\n\nextension DestructureStructInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // If the struct is trivial, replace\n // ```\n // (%1, %2) = destructure_struct %s\n // ```\n // ->\n // ```\n // %1 = struct_extract %s, #S.field0\n // %2 = struct_extract %s, #S.field1\n // ```\n // This canonicalization helps other optimizations to e.g. CSE tuple_extracts.\n //\n if replaceWithStructExtract(context) {\n return\n }\n\n switch self.struct {\n case let str as StructInst:\n // Eliminate the redundant instruction pair\n // ```\n // %s = struct (%0, %1, %2)\n // (%3, %4, %5) = destructure_struct %s\n // ```\n // and replace the results %3, %4, %5 with %0, %1, %2, respectively\n //\n tryReplaceConstructDestructPair(construct: str, destruct: self, context)\n\n case let copy as CopyValueInst:\n // Similar to the pattern above, but with a copy_value:\n // Replace\n // ```\n // %s = struct (%0, %1, %2)\n // %c = copy_value %s // can also be a chain of multiple copies\n // (%3, %4, %5) = destructure_struct %c\n // ```\n // with\n // ```\n // %c0 = copy_value %0\n // %c1 = copy_value %1\n // %c2 = copy_value %2\n // %s = struct (%0, %1, %2) // keep the original struct\n // ```\n // and replace the results %3, %4, %5 with %c0, %c1, %c2, respectively.\n //\n // This transformation has the advantage that we can do it even if the `struct` instruction\n // has other uses than the `copy_value`.\n //\n if copy.uses.singleUse?.instruction == self,\n let structInst = copy.fromValue.lookThroughCopy as? StructInst,\n structInst.parentBlock == self.parentBlock\n {\n for (result, operand) in zip(self.results, structInst.operands) {\n if operand.value.type.isTrivial(in: parentFunction) {\n result.uses.replaceAll(with: operand.value, context)\n } else {\n let builder = Builder(before: structInst, context)\n let copiedOperand = builder.createCopyValue(operand: operand.value)\n result.uses.replaceAll(with: copiedOperand, context)\n }\n }\n context.erase(instruction: self)\n context.erase(instruction: copy)\n }\n default:\n break\n }\n }\n\n private func replaceWithStructExtract(_ context: SimplifyContext) -> Bool {\n guard self.struct.type.isTrivial(in: parentFunction) else {\n return false\n }\n let builder = Builder(before: self, context)\n for (fieldIdx, result) in results.enumerated() {\n let fieldValue = builder.createStructExtract(struct: self.struct, fieldIndex: fieldIdx)\n result.uses.replaceAll(with: fieldValue, context)\n }\n context.erase(instruction: self)\n return true\n }\n}\n\nprivate func tryReplaceConstructDestructPair(construct: SingleValueInstruction,\n destruct: MultipleValueInstruction,\n _ context: SimplifyContext) {\n let singleUse = context.preserveDebugInfo ? construct.uses.singleUse : construct.uses.ignoreDebugUses.singleUse\n let canEraseFirst = singleUse?.instruction == destruct\n\n if !canEraseFirst && construct.parentFunction.hasOwnership && construct.ownership == .owned {\n // We cannot add more uses to this tuple without inserting a copy.\n return\n }\n\n for (result, operand) in zip(destruct.results, construct.operands) {\n result.uses.replaceAll(with: operand.value, context)\n }\n\n if canEraseFirst {\n context.erase(instructionIncludingDebugUses: destruct)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDestructure.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyDestructure.swift
Swift
5,552
0.95
0.093168
0.455782
awesome-app
856
2023-08-28T10:07:08.879131
MIT
false
abcff78fa2fd6f881eade72f9d1cf97b
//===--- SimplifyFixLifetime.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n/// Canonicalize a `fix_lifetime` from an address to a `load` + `fix_lifetime`:\n/// ```\n/// %1 = alloc_stack $T\n/// ...\n/// fix_lifetime %1\n/// ```\n/// ->\n/// ```\n/// %1 = alloc_stack $T\n/// ...\n/// %2 = load %1\n/// fix_lifetime %2\n/// ```\n///\n/// This transformation is done for `alloc_stack` and `store_borrow` (which always has an `alloc_stack`\n/// operand).\n/// The benefit of this transformation is that it enables other optimizations, like mem2reg.\n///\nextension FixLifetimeInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n let opValue = operand.value\n guard opValue is AllocStackInst || opValue is StoreBorrowInst,\n opValue.type.isLoadable(in: parentFunction)\n else {\n return\n }\n\n let builder = Builder(before: self, context)\n let loadedValue: Value\n if !parentFunction.hasOwnership {\n loadedValue = builder.createLoad(fromAddress: opValue, ownership: .unqualified)\n } else if opValue.type.isTrivial(in: parentFunction) {\n loadedValue = builder.createLoad(fromAddress: opValue, ownership: .trivial)\n } else {\n loadedValue = builder.createLoadBorrow(fromAddress: opValue)\n Builder(after: self, context).createEndBorrow(of: loadedValue)\n }\n operand.set(to: loadedValue, context)\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyFixLifetime.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyFixLifetime.swift
Swift
1,854
0.95
0.090909
0.568627
vue-tools
655
2025-01-26T23:53:49.763786
BSD-3-Clause
false
adb37c57a8ecce6097bb16b0fcbd6b11
//===--- SimplifyGlobalValue.swift - Simplify global_value instruction ----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n// Removes all reference counting instructions of a `global_value` instruction\n// if it does not escape.\n//\n// Note that `simplifyStrongRetainPass` and `simplifyStrongReleasePass` can\n// even remove "unbalanced" retains/releases of a `global_value`, but this\n// requires a minimum deployment target.\nextension GlobalValueInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n var users = Stack<Instruction>(context)\n defer { users.deinitialize() }\n\n if checkUsers(of: self, users: &users) {\n for inst in users {\n context.erase(instruction: inst)\n }\n }\n }\n}\n\n/// Returns true if reference counting and debug_value users of a global_value\n/// can be deleted.\nprivate func checkUsers(of val: Value, users: inout Stack<Instruction>) -> Bool {\n for use in val.uses {\n let user = use.instruction\n switch user {\n case is RefCountingInst, is DebugValueInst, is FixLifetimeInst:\n users.push(user)\n case let upCast as UpcastInst:\n if !checkUsers(of: upCast, users: &users) {\n return false\n }\n case is RefElementAddrInst, is RefTailAddrInst:\n // Projection instructions don't access the object header, so they don't\n // prevent deleting reference counting instructions.\n break\n default:\n return false\n }\n }\n return true\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyGlobalValue.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyGlobalValue.swift
Swift
1,901
0.95
0.163636
0.411765
node-utils
529
2025-04-15T00:51:10.754456
BSD-3-Clause
false
307af9e6b534ab43d5dde2a32139b7f8
//===--- SimplifyInitEnumDataAddr.swift -----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension InitEnumDataAddrInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Optimize the sequence\n // ```\n // %1 = init_enum_data_addr %enum_addr, #someCaseWithPayload\n // ...\n // store %payload to %1\n // inject_enum_addr %enum_addr, #someCaseWithPayload\n // ```\n // to\n // ```\n // %1 = enum $E, #someCaseWithPayload, %payload\n // store %1 to %enum_addr\n // ```\n // This store and inject instructions must appear in consecutive order.\n // But usually this is the case, because it's generated this way by SILGen.\n // We also check that between the init and the store, no instruction writes to memory.\n //\n if let store = self.uses.singleUse?.instruction as? StoreInst,\n store.destination == self,\n let inject = store.next as? InjectEnumAddrInst,\n inject.enum == self.enum,\n inject.enum.type.isLoadable(in: parentFunction),\n !anyInstructionMayWriteToMemory(between: self, and: store) {\n\n assert(self.caseIndex == inject.caseIndex, "mismatching case indices when creating an enum")\n\n let builder = Builder(before: store, context)\n let enumInst = builder.createEnum(caseIndex: self.caseIndex, payload: store.source, enumType: self.enum.type.objectType)\n let storeOwnership = StoreInst.StoreOwnership(for: self.enum.type, in: parentFunction, initialize: true)\n builder.createStore(source: enumInst, destination: self.enum, ownership: storeOwnership)\n context.erase(instruction: store)\n context.erase(instruction: inject)\n context.erase(instruction: self)\n }\n }\n}\n\n// Returns false if `first` and `last` are in the same basic block and no instructions between them write to memory. True otherwise.\nprivate func anyInstructionMayWriteToMemory(between first: Instruction, and last: Instruction) -> Bool {\n var nextInstruction = first.next\n while let i = nextInstruction {\n if i == last {\n return false\n }\n if i.mayWriteToMemory {\n return true\n }\n nextInstruction = i.next\n }\n // End of basic block, and we did not find `last`\n return true\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyInitEnumDataAddr.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyInitEnumDataAddr.swift
Swift
2,661
0.95
0.117647
0.467742
awesome-app
827
2024-10-06T14:13:21.144283
GPL-3.0
false
1c8b4d1812f87e32e4700652c94df1e0
//===--- SimplifyKeyPath.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension KeyPathInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n if allUsesRemovable(instruction: self) {\n if parentFunction.hasOwnership {\n let builder = Builder(after: self, context)\n for operand in self.operands {\n if !operand.value.type.isTrivial(in: parentFunction) {\n if operand.value.type.isAddress {\n builder.createDestroyAddr(address: operand.value)\n } else {\n builder.createDestroyValue(operand: operand.value)\n }\n }\n }\n }\n context.erase(instructionIncludingAllUsers: self)\n }\n }\n}\n\nfileprivate func allUsesRemovable(instruction: Instruction) -> Bool {\n for result in instruction.results {\n for use in result.uses {\n switch use.instruction {\n case is UpcastInst,\n is DestroyValueInst,\n is StrongReleaseInst,\n is BeginBorrowInst,\n is EndBorrowInst,\n is MoveValueInst,\n is CopyValueInst:\n // This is a removable instruction type, continue descending into uses\n if !allUsesRemovable(instruction: use.instruction) {\n return false\n }\n\n default:\n return false\n }\n }\n }\n return true\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyKeyPath.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyKeyPath.swift
Swift
1,792
0.95
0.192982
0.226415
python-kit
943
2025-03-22T07:48:19.815622
MIT
false
4967267b673c6199a87a7a39f85e678d
//===--- SimplifyLoad.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension LoadInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n if optimizeLoadOfAddrUpcast(context) {\n return\n }\n if optimizeLoadFromStringLiteral(context) {\n return\n }\n if optimizeLoadFromEmptyCollection(context) {\n return\n }\n if replaceLoadOfGlobalLet(context) {\n return\n }\n removeIfDead(context)\n }\n\n /// ```\n /// %1 = unchecked_addr_cast %0 : $*DerivedClass to $*BaseClass\n /// %2 = load %1\n /// ```\n /// is transformed to\n /// ```\n /// %1 = load %0 : $*BaseClass\n /// %2 = upcast %1 : $DerivedClass to $BaseClass\n /// ```\n private func optimizeLoadOfAddrUpcast(_ context: SimplifyContext) -> Bool {\n if let uac = address as? UncheckedAddrCastInst,\n uac.type.isExactSuperclass(of: uac.fromAddress.type),\n uac.type != uac.fromAddress.type {\n\n operand.set(to: uac.fromAddress, context)\n let builder = Builder(before: self, context)\n let newLoad = builder.createLoad(fromAddress: uac.fromAddress, ownership: loadOwnership)\n let cast = builder.createUpcast(from: newLoad, to: type)\n uses.replaceAll(with: cast, context)\n context.erase(instruction: self)\n return true\n }\n return false\n }\n\n /// The load from a string literal element, e.g.\n /// ```\n /// %0 = string_literal utf8 "abc"\n /// %1 = integer_literal $Builtin.Word, 1\n /// %2 = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*UInt8\n /// %3 = index_addr %2 : $*UInt8, %1 : $Builtin.Word\n /// %4 = struct_element_addr %3 : $*UInt8, #UInt8._value\n /// %5 = load %4 : $*Builtin.Int8\n /// ```\n /// is replaced by the character value, e.g. `98` in this example.\n ///\n private func optimizeLoadFromStringLiteral(_ context: SimplifyContext) -> Bool {\n if self.type.isBuiltinInteger(withFixedWidth: 8),\n let sea = self.address as? StructElementAddrInst,\n let (baseAddr, index) = sea.struct.getBaseAddressAndOffset(),\n let pta = baseAddr as? PointerToAddressInst,\n let stringLiteral = pta.pointer as? StringLiteralInst,\n stringLiteral.encoding == .UTF8,\n index < stringLiteral.value.count {\n\n let builder = Builder(before: self, context)\n let charLiteral = builder.createIntegerLiteral(Int(stringLiteral.value[index]), type: type)\n uses.replaceAll(with: charLiteral, context)\n context.erase(instruction: self)\n return true\n }\n return false\n }\n\n /// Loading `count` or `capacity` from the empty `Array`, `Set` or `Dictionary` singleton\n /// is replaced by a 0 literal.\n private func optimizeLoadFromEmptyCollection(_ context: SimplifyContext) -> Bool {\n if self.isZeroLoadFromEmptyCollection() {\n let builder = Builder(before: self, context)\n let zeroLiteral = builder.createIntegerLiteral(0, type: type)\n uses.replaceAll(with: zeroLiteral, context)\n context.erase(instruction: self)\n return true\n }\n return false\n }\n\n /// The load of a global let variable is replaced by its static initializer value.\n private func replaceLoadOfGlobalLet(_ context: SimplifyContext) -> Bool {\n guard let globalInitVal = getGlobalInitValue(address: address, context) else {\n return false\n }\n if !globalInitVal.canBeCopied(into: parentFunction, context) {\n return false\n }\n var cloner = StaticInitCloner(cloneBefore: self, context)\n defer { cloner.deinitialize() }\n\n let initVal = cloner.clone(globalInitVal)\n\n uses.replaceAll(with: initVal, context)\n // Also erases a builtin "once" on which the global_addr depends on. This is fine\n // because we only replace the load if the global init function doesn't have any side effect.\n transitivelyErase(load: self, context)\n return true\n }\n\n private func isZeroLoadFromEmptyCollection() -> Bool {\n if !type.isBuiltinInteger {\n return false\n }\n var addr = address\n\n // Find the root object of the load-address.\n while true {\n switch addr {\n case let ga as GlobalAddrInst:\n switch ga.global.name {\n case "_swiftEmptyArrayStorage",\n "_swiftEmptyDictionarySingleton",\n "_swiftEmptySetSingleton":\n return true\n default:\n return false\n }\n case let sea as StructElementAddrInst:\n let structType = sea.struct.type\n if structType.nominal!.name == "_SwiftArrayBodyStorage" {\n guard let fields = structType.getNominalFields(in: parentFunction) else {\n return false\n }\n switch fields.getNameOfField(withIndex: sea.fieldIndex) {\n case "count":\n break\n case "_capacityAndFlags":\n if uses.contains(where: { !$0.instruction.isShiftRightByAtLeastOne }) {\n return false\n }\n default:\n return false\n }\n }\n addr = sea.struct\n case let rea as RefElementAddrInst:\n let classType = rea.instance.type\n switch classType.nominal!.name {\n case "__RawDictionaryStorage",\n "__RawSetStorage":\n // For Dictionary and Set we support "count" and "capacity".\n guard let fields = classType.getNominalFields(in: parentFunction) else {\n return false\n }\n switch fields.getNameOfField(withIndex: rea.fieldIndex) {\n case "_count", "_capacity":\n break\n default:\n return false\n }\n default:\n break\n }\n addr = rea.instance\n case is UncheckedRefCastInst,\n is UpcastInst,\n is RawPointerToRefInst,\n is AddressToPointerInst,\n is BeginBorrowInst,\n is CopyValueInst,\n is EndCOWMutationInst:\n addr = (addr as! UnaryInstruction).operand.value\n case let mviResult as MultipleValueInstructionResult:\n guard let bci = mviResult.parentInstruction as? BeginCOWMutationInst else {\n return false\n }\n addr = bci.instance\n default:\n return false\n }\n }\n }\n\n /// Removes the `load [copy]` if the loaded value is just destroyed.\n private func removeIfDead(_ context: SimplifyContext) {\n if loadOwnership == .copy,\n loadedValueIsDead(context) {\n for use in uses {\n context.erase(instruction: use.instruction)\n }\n context.erase(instruction: self)\n }\n }\n\n private func loadedValueIsDead(_ context: SimplifyContext) -> Bool {\n if context.preserveDebugInfo {\n return !uses.contains { !($0.instruction is DestroyValueInst) }\n } else {\n return !uses.ignoreDebugUses.contains { !($0.instruction is DestroyValueInst) }\n }\n }\n}\n\n/// Returns the init value of a global which is loaded from `address`.\nprivate func getGlobalInitValue(address: Value, _ context: SimplifyContext) -> Value? {\n switch address {\n case let gai as GlobalAddrInst:\n if gai.global.isLet {\n if let staticInitValue = gai.global.staticInitValue {\n return staticInitValue\n }\n if let staticInitValue = getInitializerFromInitFunction(of: gai, context) {\n return staticInitValue\n }\n }\n case let pta as PointerToAddressInst:\n return globalLoadedViaAddressor(pointer: pta.pointer)?.staticInitValue\n case let sea as StructElementAddrInst:\n if let structVal = getGlobalInitValue(address: sea.struct, context) as? StructInst {\n return structVal.operands[sea.fieldIndex].value\n }\n case let tea as TupleElementAddrInst:\n if let tupleVal = getGlobalInitValue(address: tea.tuple, context) as? TupleInst {\n return tupleVal.operands[tea.fieldIndex].value\n }\n case let bai as BeginAccessInst:\n return getGlobalInitValue(address: bai.address, context)\n case let rta as RefTailAddrInst:\n return getGlobalTailElement(of: rta, index: 0)\n case let ia as IndexAddrInst:\n if let rta = ia.base as? RefTailAddrInst,\n let literal = ia.index as? IntegerLiteralInst,\n let index = literal.value\n {\n return getGlobalTailElement(of: rta, index: index)\n }\n case let rea as RefElementAddrInst:\n if let object = rea.instance.immutableGlobalObjectRoot {\n return object.baseOperands[rea.fieldIndex].value\n }\n default:\n break\n }\n return nil\n}\n\nprivate func getGlobalTailElement(of refTailAddr: RefTailAddrInst, index: Int) -> Value? {\n if let object = refTailAddr.instance.immutableGlobalObjectRoot,\n index >= 0 && index < object.tailOperands.count\n {\n return object.tailOperands[index].value\n }\n return nil\n}\n\nprivate func getInitializerFromInitFunction(of globalAddr: GlobalAddrInst, _ context: SimplifyContext) -> Value? {\n guard let dependentOn = globalAddr.dependencyToken,\n let builtinOnce = dependentOn as? BuiltinInst,\n builtinOnce.id == .Once,\n let initFnRef = builtinOnce.operands[1].value as? FunctionRefInst else\n {\n return nil\n }\n let initFn = initFnRef.referencedFunction\n context.notifyDependency(onBodyOf: initFn)\n guard let (_, storeToGlobal) = getGlobalInitialization(of: initFn, context, handleUnknownInstruction: {\n // Accept `global_value` because the class header can be initialized at runtime by the `global_value` instruction.\n return $0 is GlobalValueInst\n }) else {\n return nil\n }\n return storeToGlobal.source\n}\n\nprivate func globalLoadedViaAddressor(pointer: Value) -> GlobalVariable? {\n if let ai = pointer as? ApplyInst,\n let callee = ai.referencedFunction,\n let global = callee.globalOfGlobalInitFunction,\n global.isLet {\n return global\n }\n return nil\n}\n\nprivate func transitivelyErase(load: LoadInst, _ context: SimplifyContext) {\n var inst: SingleValueInstruction = load\n while inst.uses.isEmpty {\n if inst.operands.count != 1 {\n context.erase(instruction: inst)\n return\n }\n guard let operandInst = inst.operands[0].value as? SingleValueInstruction else {\n return\n }\n context.erase(instruction: inst)\n inst = operandInst\n }\n}\n\nprivate extension Value {\n func canBeCopied(into function: Function, _ context: SimplifyContext) -> Bool {\n // Can't use `ValueSet` because the this value is inside a global initializer and\n // not inside a function.\n var worklist = Stack<Value>(context)\n defer { worklist.deinitialize() }\n\n var handled = Set<ObjectIdentifier>()\n\n worklist.push(self)\n handled.insert(ObjectIdentifier(self))\n\n while let value = worklist.pop() {\n if value is VectorInst {\n return false\n }\n if let fri = value as? FunctionRefInst {\n if function.isAnySerialized, \n !fri.referencedFunction.hasValidLinkageForFragileRef(function.serializedKind)\n {\n return false\n }\n }\n for op in value.definingInstruction!.operands {\n if handled.insert(ObjectIdentifier(op.value)).inserted {\n worklist.push(op.value)\n }\n }\n }\n return true\n }\n\n func getBaseAddressAndOffset() -> (baseAddress: Value, offset: Int)? {\n if let indexAddr = self as? IndexAddrInst {\n guard let indexLiteral = indexAddr.index as? IntegerLiteralInst,\n let indexValue = indexLiteral.value else\n {\n return nil\n }\n return (baseAddress: indexAddr.base, offset: indexValue)\n }\n return (baseAddress: self, offset: 0)\n }\n\n // If the reference-root of self references a global object, returns the `object` instruction of the\n // global's initializer. But only if the global is a let-global.\n var immutableGlobalObjectRoot: ObjectInst? {\n if let gv = self.referenceRoot as? GlobalValueInst,\n gv.global.isLet,\n let initval = gv.global.staticInitValue,\n let object = initval as? ObjectInst\n {\n return object\n }\n return nil\n }\n}\n\nprivate extension Instruction {\n var isShiftRightByAtLeastOne: Bool {\n guard let bi = self as? BuiltinInst,\n bi.id == .LShr,\n let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst,\n let shiftValue = shiftLiteral.value else\n {\n return false\n }\n return shiftValue > 0\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyLoad.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyLoad.swift
Swift
12,634
0.95
0.134921
0.127841
awesome-app
695
2024-02-29T06:34:50.289135
GPL-3.0
false
f25581746d78914644d931f081f02d00
//===--- SimplifyMisc.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension TypeValueInst: OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n // If our parameter is not known statically, then bail.\n guard paramType.isInteger else {\n return\n }\n\n // Note: Right now, value generics only support 'Int'. If we ever expand the\n // scope of types supported, then this should change.\n let fieldType = type.getNominalFields(in: parentFunction)![0]\n\n let builder = Builder(before: self, context)\n let intLiteral = builder.createIntegerLiteral(value, type: fieldType)\n let structInst = builder.createStruct(type: type, elements: [intLiteral])\n uses.replaceAll(with: structInst, context)\n context.erase(instruction: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyMisc.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyMisc.swift
Swift
1,254
0.95
0.0625
0.5
python-kit
566
2024-12-12T00:47:18.055179
GPL-3.0
false
3d92b39748764cbcef76e9324f596784
//===--- SimplifyPartialApply.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension PartialApplyInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n let optimizedApplyOfPartialApply = context.tryOptimizeApplyOfPartialApply(closure: self)\n if optimizedApplyOfPartialApply {\n context.notifyInvalidatedStackNesting()\n }\n\n if context.preserveDebugInfo && uses.contains(where: { $0.instruction is DebugValueInst }) {\n return\n }\n\n // Try to delete the partial_apply.\n // In case it became dead because of tryOptimizeApplyOfPartialApply, we don't\n // need to copy all arguments again (to extend their lifetimes), because it\n // was already done in tryOptimizeApplyOfPartialApply.\n if context.tryDeleteDeadClosure(closure: self, needKeepArgsAlive: !optimizedApplyOfPartialApply) {\n context.notifyInvalidatedStackNesting()\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyPartialApply.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyPartialApply.swift
Swift
1,350
0.95
0.147059
0.5
node-utils
777
2024-01-26T01:59:11.250241
MIT
false
4f28c7824694db995118d29a6271b9a1
//===--- SimplifyPointerToAddress.swift -----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension PointerToAddressInst : OnoneSimplifiable, SILCombineSimplifiable {\n\n func simplify(_ context: SimplifyContext) {\n if removeAddressToPointerToAddressPair(of: self, context) {\n return\n }\n if simplifyIndexRawPointer(of: self, context) {\n return\n }\n _ = optimizeAlignment(of: self, context)\n }\n}\n\n/// Remove a redundant pair of pointer-address conversions:\n/// ```\n/// %2 = address_to_pointer %1\n/// %3 = pointer_to_address %2 [strict]\n/// ```\n/// -> replace all uses of %3 with %1.\n///\nprivate func removeAddressToPointerToAddressPair(\n of ptr2Addr: PointerToAddressInst,\n _ context: SimplifyContext\n) -> Bool {\n guard let addr2Ptr = ptr2Addr.pointer as? AddressToPointerInst,\n ptr2Addr.isStrict,\n !ptr2Addr.hasIllegalUsesAfterLifetime(of: addr2Ptr, context)\n else {\n return false\n }\n\n if ptr2Addr.type == addr2Ptr.address.type {\n ptr2Addr.replace(with: addr2Ptr.address, context)\n } else {\n let cast = Builder(before: ptr2Addr, context).createUncheckedAddrCast(from: addr2Ptr.address, to: ptr2Addr.type)\n ptr2Addr.replace(with: cast, context)\n }\n return true\n}\n\n/// Replace an `index_raw_pointer` with a manually computed stride with `index_addr`:\n/// ```\n/// %1 = metatype $T.Type\n/// %2 = builtin "strideof"<T>(%1) :\n/// %3 = builtin "smul_with_overflow_Int64"(%idx, %2)\n/// %4 = tuple_extract %3, 0\n/// %5 = index_raw_pointer %ptr, %4\n/// %6 = pointer_to_address %5 to [strict] $*T\n/// ```\n/// ->\n/// ```\n/// %2 = pointer_to_address %ptr to [strict] $*T\n/// %3 = index_addr %2, %idx\n/// ```\n///\nprivate func simplifyIndexRawPointer(of ptr2Addr: PointerToAddressInst, _ context: SimplifyContext) -> Bool {\n guard let indexRawPtr = ptr2Addr.pointer as? IndexRawPointerInst,\n let tupleExtract = indexRawPtr.index.lookThroughTruncOrBitCast as? TupleExtractInst,\n let strideMul = tupleExtract.tuple as? BuiltinInst, strideMul.id == .SMulOver,\n let (index, strideType) = strideMul.indexAndStrideOfMultiplication,\n strideType == ptr2Addr.type.objectType\n else {\n return false\n }\n\n let builder = Builder(before: ptr2Addr, context)\n let newPtr2Addr = builder.createPointerToAddress(pointer: indexRawPtr.base, addressType: ptr2Addr.type,\n isStrict: ptr2Addr.isStrict, isInvariant: ptr2Addr.isInvariant)\n let newIndex = builder.createCastIfNeeded(of: index, toIndexTypeOf: indexRawPtr)\n let indexAddr = builder.createIndexAddr(base: newPtr2Addr, index: newIndex, needStackProtection: false)\n ptr2Addr.replace(with: indexAddr, context)\n return true\n}\n\n/// Optimize the alignment of a `pointer_to_address` based on `Builtin.assumeAlignment`\n/// ```\n/// %1 = builtin "assumeAlignment"(%ptr, %align)\n/// %2 = pointer_to_address %1 to [align=1] $*T\n/// ```\n/// ->\n/// ```\n/// %2 = pointer_to_address %ptr to [align=8] $*T\n/// ```\n/// or\n/// ```\n/// %2 = pointer_to_address %ptr to $*T\n/// ```\n///\n/// The goal is to increase the alignment or to remove the attribute completely, which means that\n/// the resulting address is naturaly aligned to its type.\n///\nprivate func optimizeAlignment(of ptr2Addr: PointerToAddressInst, _ context: SimplifyContext) -> Bool {\n guard let assumeAlign = ptr2Addr.pointer as? BuiltinInst, assumeAlign.id == .AssumeAlignment else {\n return false\n }\n\n if optimizeConstantAlignment(of: ptr2Addr, assumed: assumeAlign, context) {\n return true\n }\n return optimizeTypeAlignment(of: ptr2Addr, assumed: assumeAlign, context)\n}\n\n/// Optimize the alignment based on an integer literal\n/// ```\n/// %align = integer_literal $Builtin.Int64, 16\n/// %1 = builtin "assumeAlignment"(%ptr, %align)\n/// %2 = pointer_to_address %1 to [align=1] $*T\n/// ```\n/// ->\n/// ```\n/// %2 = pointer_to_address %ptr to [align=16] $*T\n/// ```\nprivate func optimizeConstantAlignment(\n of ptr2Addr: PointerToAddressInst,\n assumed assumeAlign: BuiltinInst,\n _ context: SimplifyContext\n) -> Bool {\n guard let alignLiteral = assumeAlign.arguments[1] as? IntegerLiteralInst,\n let assumedAlignment = alignLiteral.value\n else {\n return false\n }\n\n ptr2Addr.operand.set(to: assumeAlign.arguments[0], context)\n\n if assumedAlignment == 0 {\n // A zero alignment means that the pointer is aligned to the natural alignment of the address type.\n ptr2Addr.set(alignment: nil, context)\n } else {\n if let oldAlignment = ptr2Addr.alignment, assumedAlignment <= oldAlignment {\n // Avoid decreasing the alignment, which would be a pessimisation.\n return true\n }\n ptr2Addr.set(alignment: assumedAlignment, context)\n }\n return true\n}\n\n/// Remove the alignment attribute if the alignment is assumed to be the natural alignment of the address type.\n/// ```\n// %align = builtin "alignof"<T>(%0 : $@thin T.Type)\n/// %1 = builtin "assumeAlignment"(%ptr, %align)\n/// %2 = pointer_to_address %1 to [align=1] $*T\n/// ```\n/// ->\n/// ```\n/// %2 = pointer_to_address %ptr to $*T\n/// ```\nprivate func optimizeTypeAlignment(\n of ptr2Addr: PointerToAddressInst,\n assumed assumeAlign: BuiltinInst,\n _ context: SimplifyContext\n) -> Bool {\n guard let alignOf = assumeAlign.arguments[1].lookThroughIntCasts as? BuiltinInst, alignOf.id == .Alignof,\n alignOf.alignOrStrideType == ptr2Addr.type.objectType\n else {\n return false\n }\n let pointer = assumeAlign.arguments[0]\n ptr2Addr.set(alignment: nil, context)\n ptr2Addr.operand.set(to: pointer, context)\n return true\n}\n\nprivate extension PointerToAddressInst {\n\n /// Checks if the `pointer_to_address` has uses outside the scope of the `baseAddress`.\n /// In such a case removing the `address_to_pointer`-`pointer_to_address` pair would result in\n /// invalid SIL. For example:\n /// ```\n /// %1 = alloc_stack $T\n /// %2 = address_to_pointer %1\n /// dealloc_stack %1\n /// %3 = pointer_to_address %2\n /// %4 = load %3\n /// ```\n /// or\n /// ```\n /// %1 = begin_borrow %0\n /// %2 = ref_element_addr %1, #C.x\n /// %3 = address_to_pointer %2\n /// end_borrow %1\n /// %4 = pointer_to_address %3\n /// %5 = load %4\n /// ```\n func hasIllegalUsesAfterLifetime(of baseAddress: AddressToPointerInst, _ context: SimplifyContext) -> Bool {\n \n var lifetimeFrontier = InstructionSet(context)\n defer { lifetimeFrontier.deinitialize() }\n\n switch baseAddress.address.accessBase.addEndLifetimeUses(to: &lifetimeFrontier, context) {\n case .unknownLifetime:\n return true\n case .unlimitedLifetime:\n return false\n case .limitedLifetime:\n var addressUses = AddressUses(of: self, context)\n defer { addressUses.deinitialize() }\n return addressUses.hasUsesOutside(of: lifetimeFrontier, beginInstruction: baseAddress)\n }\n }\n}\n\nprivate extension AccessBase {\n func addEndLifetimeUses(to frontier: inout InstructionSet, _ context: SimplifyContext) -> Result {\n switch self {\n case .stack(let allocStack):\n frontier.insert(contentsOf: allocStack.deallocations)\n return .limitedLifetime\n case .global, .argument, .pointer:\n return .unlimitedLifetime\n case .storeBorrow(let storeBorrow):\n frontier.insert(contentsOf: storeBorrow.endBorrows)\n return .limitedLifetime\n default:\n guard let ref = reference else {\n return .unknownLifetime\n }\n switch ref.ownership {\n case .owned:\n frontier.insert(contentsOf: ref.uses.endingLifetime.users)\n return .limitedLifetime\n case .guaranteed:\n for borrowIntroducer in ref.getBorrowIntroducers(context) {\n frontier.insert(contentsOf: borrowIntroducer.scopeEndingOperands.users)\n }\n return .limitedLifetime\n case .none:\n // Not in an OSSA function.\n return .unlimitedLifetime\n case .unowned:\n return .unknownLifetime\n }\n }\n }\n\n enum Result {\n case unknownLifetime, unlimitedLifetime, limitedLifetime\n }\n}\n\nprivate struct AddressUses : AddressDefUseWalker {\n var users: InstructionWorklist\n\n init(of address: Value, _ context: SimplifyContext) {\n users = InstructionWorklist(context)\n _ = walkDownUses(ofAddress: address, path: UnusedWalkingPath())\n }\n\n mutating func deinitialize() {\n users.deinitialize()\n }\n\n mutating func leafUse(address: Operand, path: UnusedWalkingPath) -> WalkResult {\n users.pushIfNotVisited(address.instruction)\n return .continueWalk\n }\n\n mutating func hasUsesOutside(of lifetimeFrontier: InstructionSet, beginInstruction: Instruction) -> Bool {\n while let inst = users.pop() {\n if lifetimeFrontier.contains(inst) {\n return true\n }\n users.pushPredecessors(of: inst, ignoring: beginInstruction)\n }\n return false\n }\n}\n\nprivate extension Value {\n var lookThroughIntCasts: Value {\n guard let builtin = self as? BuiltinInst else {\n return self\n }\n switch builtin.id {\n case .ZExtOrBitCast, .SExtOrBitCast, .TruncOrBitCast:\n return builtin.arguments[0].lookThroughIntCasts\n default:\n return self\n }\n }\n\n var lookThroughTruncOrBitCast: Value {\n if let truncOrBitCast = self as? BuiltinInst, truncOrBitCast.id == .TruncOrBitCast {\n return truncOrBitCast.arguments[0]\n }\n return self\n }\n}\n\nprivate extension BuiltinInst {\n var indexAndStrideOfMultiplication : (index: Value, strideType: Type)? {\n assert(id == .SMulOver)\n if let strideOf = arguments[0].lookThroughIntCasts as? BuiltinInst, strideOf.id == .Strideof {\n return (index: arguments[1], strideType: strideOf.alignOrStrideType)\n }\n if let strideOf = arguments[1].lookThroughIntCasts as? BuiltinInst, strideOf.id == .Strideof {\n return (index: arguments[0], strideType: strideOf.alignOrStrideType)\n }\n return nil\n }\n\n var alignOrStrideType: Type {\n substitutionMap.replacementTypes[0].loweredType(in: parentFunction)\n }\n}\n\nprivate extension Builder {\n func createCastIfNeeded(of index: Value, toIndexTypeOf indexRawPtr: IndexRawPointerInst) -> Value {\n if let truncOrBitCast = indexRawPtr.index as? BuiltinInst {\n assert(truncOrBitCast.id == .TruncOrBitCast)\n return createBuiltin(name: truncOrBitCast.name, type: truncOrBitCast.type, arguments: [index])\n }\n return index\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyPointerToAddress.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyPointerToAddress.swift
Swift
10,791
0.95
0.066667
0.305648
python-kit
204
2024-07-11T12:43:41.344907
BSD-3-Clause
false
5ce88670e00cc36e4acf8d2b8bbd62ba
//===--- SimplifyRefCasts.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n// Note: this simplifications are not SILCombineSimplifiable, because SILCombine has\n// its own simplifications for those cast instructions which are not ported to Swift, yet.\n\nextension CheckedCastBranchInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n // Has only an effect if the source is an (existential) reference.\n simplifySourceOperandOfRefCast(context)\n }\n}\n\nextension UncheckedRefCastInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n simplifySourceOperandOfRefCast(context)\n }\n}\n\nprivate extension UnaryInstruction {\n\n /// Look through `upcast` and `init_existential_ref` instructions and replace the\n /// operand of this cast instruction with the original value.\n /// For example:\n /// ```\n /// %2 = upcast %1 : $Derived to $Base\n /// %3 = init_existential_ref %2 : $Base : $Base, $AnyObject\n /// checked_cast_br AnyObject in %3 : $AnyObject to Derived, bb1, bb2\n /// ```\n ///\n /// This makes it more likely that the cast can be constant folded because the source\n /// operand's type is more accurate. In the example above, the cast reduces to\n /// ```\n /// checked_cast_br Derived in %1 : $Derived to Derived, bb1, bb2\n /// ```\n /// which can be trivially folded to always-succeeds.\n ///\n func simplifySourceOperandOfRefCast(_ context: SimplifyContext) {\n while true {\n switch operand.value {\n case let ier as InitExistentialRefInst:\n if !tryReplaceSource(withOperandOf: ier, context) {\n return\n }\n case let uc as UpcastInst:\n if !tryReplaceSource(withOperandOf: uc, context) {\n return\n }\n default:\n return\n }\n }\n\n }\n\n func tryReplaceSource(withOperandOf inst: SingleValueInstruction, _ context: SimplifyContext) -> Bool {\n let singleUse = context.preserveDebugInfo ? inst.uses.singleUse : inst.uses.ignoreDebugUses.singleUse\n let canEraseInst = singleUse?.instruction == self\n let replacement = inst.operands[0].value\n\n if parentFunction.hasOwnership {\n if !canEraseInst && replacement.ownership == .owned {\n // We cannot add more uses to `replacement` without inserting a copy.\n return false\n }\n\n operand.set(to: replacement, context)\n\n if let ccb = self as? CheckedCastBranchInst {\n // In OSSA, the source value is passed as block argument to the failure block.\n // We have to re-create the skipped source instruction in the failure block.\n insertCompensatingInstructions(for: inst, in: ccb.failureBlock, context)\n }\n } else {\n operand.set(to: replacement, context)\n }\n\n if let ccb = self as? CheckedCastBranchInst {\n // Make sure that updating the formal type with the operand type is\n // legal.\n if operand.value.type.isLegalFormalType {\n ccb.updateSourceFormalTypeFromOperandLoweredType()\n }\n }\n if canEraseInst {\n context.erase(instructionIncludingDebugUses: inst)\n }\n return true\n }\n}\n\n/// Compensate a removed source value instruction in the failure block.\n/// For example:\n/// ```\n/// %inst = upcast %sourceValue : $Derived to $Base\n/// checked_cast_br Base in %inst : $Base to Derived, success_block, failure_block\n/// ...\n/// failure_block(%oldArg : $Base):\n/// ```\n/// is converted to:\n/// ```\n/// checked_cast_br Derived in %sourceValue : $Derived to Derived, success_block, failure_block\n/// ...\n/// failure_block(%newArg : $Derived):\n/// %3 = upcast %newArg : $Derived to $Base\n/// ```\nprivate func insertCompensatingInstructions(for inst: Instruction, in failureBlock: BasicBlock, _ context: SimplifyContext) {\n assert(failureBlock.arguments.count == 1)\n let sourceValue = inst.operands[0].value\n let newArg = failureBlock.addArgument(type: sourceValue.type, ownership: sourceValue.ownership, context)\n let builder = Builder(atBeginOf: failureBlock, context)\n let newInst: SingleValueInstruction\n switch inst {\n case let ier as InitExistentialRefInst:\n newInst = builder.createInitExistentialRef(instance: newArg,\n existentialType: ier.type,\n formalConcreteType: ier.formalConcreteType,\n conformances: ier.conformances)\n case let uc as UpcastInst:\n newInst = builder.createUpcast(from: newArg, to: uc.type)\n default:\n fatalError("unhandled instruction")\n }\n let oldArg = failureBlock.arguments[0]\n oldArg.uses.replaceAll(with: newInst, context)\n failureBlock.eraseArgument(at: 0, context)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyRefCasts.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyRefCasts.swift
Swift
5,137
0.95
0.123188
0.4
react-lib
536
2024-02-03T02:42:37.324418
BSD-3-Clause
false
a128c1c476fdb642dbf118385bf128d6
//===--- SimplifyRetainReleaseValue.swift ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension RetainValueInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Remove pairs of\n // ```\n // release_value %0 // the release is before the retain!\n // retain_value %0\n // ```\n // which sometimes the ARC optimizations cannot do.\n //\n if optimizeReleaseRetainPair(context) {\n return\n }\n\n // Replace\n // ```\n // %1 = enum #E.A, %0\n // retain_value %1\n // ```\n // with\n // ```\n // %1 = enum #E.A, %0 // maybe dead\n // retain_value %0\n // ```\n replaceOperandWithPayloadOfEnum(context)\n\n // Remove if the operand is trivial (but not necessarily its type), e.g.\n // ```\n // %1 = value_to_bridge_object %0 : $UInt64\n // retain_value %1 : $Builtin.BridgeObject\n // ```\n if removeIfOperandIsTrivial(context) {\n return\n }\n\n // Replace e.g.\n // ```\n // retain_value %1 : $SomeClass\n // ```\n // with\n // ```\n // strong_retain %1 : $SomeClass\n // ```\n replaceWithStrongOrUnownedRetain(context)\n }\n}\n\nextension ReleaseValueInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Replace\n // ```\n // %1 = enum #E.A, %0\n // release_value %1\n // ```\n // with\n // ```\n // %1 = enum #E.A, %0 // maybe dead\n // release_value %0\n // ```\n replaceOperandWithPayloadOfEnum(context)\n\n // Remove if the operand is trivial (but not necessarily its type), e.g.\n // ```\n // %1 = value_to_bridge_object %0 : $UInt64\n // release_value %1 : $Builtin.BridgeObject\n // ```\n if removeIfOperandIsTrivial(context) {\n return\n }\n\n // Replace e.g.\n // ```\n // release_value %1 : $SomeClass\n // ```\n // with\n // ```\n // release_value %1 : $SomeClass\n // ```\n replaceWithStrongOrUnownedRelease(context)\n }\n}\n\nprivate extension RetainValueInst {\n func optimizeReleaseRetainPair(_ context: SimplifyContext) -> Bool {\n if let prevInst = self.previous,\n let release = prevInst as? ReleaseValueInst,\n release.value == self.value {\n context.erase(instruction: release)\n context.erase(instruction: self)\n return true\n }\n return false\n }\n\n func replaceWithStrongOrUnownedRetain(_ context: SimplifyContext) {\n if value.type.isReferenceCounted(in: parentFunction) {\n let builder = Builder(before: self, context)\n if value.type.isUnownedStorageType {\n builder.createUnownedRetain(operand: value)\n } else {\n builder.createStrongRetain(operand: value)\n }\n context.erase(instruction: self)\n }\n }\n}\n\nprivate extension ReleaseValueInst {\n func replaceWithStrongOrUnownedRelease(_ context: SimplifyContext) {\n if value.type.isReferenceCounted(in: parentFunction) {\n let builder = Builder(before: self, context)\n if value.type.isUnownedStorageType {\n builder.createUnownedRelease(operand: value)\n } else {\n builder.createStrongRelease(operand: value)\n }\n context.erase(instruction: self)\n }\n }\n}\n\nprivate extension UnaryInstruction {\n func replaceOperandWithPayloadOfEnum(_ context: SimplifyContext) {\n if let e = operand.value as? EnumInst,\n !e.type.isValueTypeWithDeinit,\n let payload = e.payload {\n operand.set(to: payload, context)\n }\n }\n\n func removeIfOperandIsTrivial(_ context: SimplifyContext) -> Bool {\n if operand.value.isTrivial(context) {\n context.erase(instruction: self)\n return true\n }\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyRetainReleaseValue.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyRetainReleaseValue.swift
Swift
4,111
0.95
0.091503
0.463768
python-kit
484
2025-04-10T09:01:36.749310
Apache-2.0
false
e781c45b6d5b9379c01ce9eed4ed9f85
//===--- SimplifyStrongRetainRelease.swift - strong_retain/release opt ----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension StrongRetainInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n if isNotReferenceCounted(value: instance) {\n context.erase(instruction: self)\n return\n }\n\n // Sometimes in the stdlib due to hand offs, we will see code like:\n //\n // strong_release %0\n // strong_retain %0\n //\n // with the matching strong_retain to the strong_release in a predecessor\n // basic block and the matching strong_release for the strong_retain in a\n // successor basic block.\n //\n // Due to the matching pairs being in different basic blocks, the ARC\n // Optimizer (which is currently local to one basic block does not handle\n // it). But that does not mean that we cannot eliminate this pair with a\n // peephole.\n if let prev = previous {\n if let release = prev as? StrongReleaseInst {\n if release.instance == self.instance {\n context.erase(instruction: self)\n context.erase(instruction: release)\n return\n }\n }\n }\n }\n}\n\nextension StrongReleaseInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n let op = instance\n if isNotReferenceCounted(value: op) {\n context.erase(instruction: self)\n return\n }\n\n // Release of a classbound existential converted from a class is just a\n // release of the class, squish the conversion.\n if let ier = op as? InitExistentialRefInst {\n if ier.uses.isSingleUse {\n setOperand(at: 0, to: ier.instance, context)\n context.erase(instruction: ier)\n return\n }\n }\n }\n}\n\n/// Returns true if \p value is something where reference counting instructions\n/// don't have any effect.\nprivate func isNotReferenceCounted(value: Value) -> Bool {\n if value.type.isMarkedAsImmortal {\n return true\n }\n switch value {\n case let cfi as ConvertFunctionInst:\n return isNotReferenceCounted(value: cfi.fromFunction)\n case let uci as UpcastInst:\n return isNotReferenceCounted(value: uci.fromInstance)\n case let urc as UncheckedRefCastInst:\n return isNotReferenceCounted(value: urc.fromInstance)\n case let gvi as GlobalValueInst:\n // Since Swift 5.1, statically allocated objects have "immortal" reference\n // counts. Therefore we can safely eliminate unbalanced retains and\n // releases, because they are no-ops on immortal objects.\n // Note that the `simplifyGlobalValuePass` pass is deleting balanced\n // retains/releases, which doesn't require a Swift 5.1 minimum deployment\n // target.\n return gvi.parentFunction.isSwift51RuntimeAvailable\n case let rptr as RawPointerToRefInst:\n // Like `global_value` but for the empty collection singletons from the\n // stdlib, e.g. the empty Array singleton.\n if rptr.parentFunction.isSwift51RuntimeAvailable {\n // The pattern generated for empty collection singletons is:\n // %0 = global_addr @_swiftEmptyArrayStorage\n // %1 = address_to_pointer %0\n // %2 = raw_pointer_to_ref %1\n if let atp = rptr.pointer as? AddressToPointerInst {\n return atp.address is GlobalAddrInst\n }\n }\n return false\n case // Thin functions are not reference counted.\n is ThinToThickFunctionInst,\n // The same for meta types.\n is ObjCExistentialMetatypeToObjectInst,\n is ObjCMetatypeToObjectInst,\n // Retain and Release of tagged strings is a no-op.\n // The builtin code pattern to find tagged strings is:\n // builtin "stringObjectOr_Int64" (or to tag the string)\n // value_to_bridge_object (cast the UInt to bridge object)\n is ValueToBridgeObjectInst:\n return true\n default:\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyStrongRetainRelease.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyStrongRetainRelease.swift
Swift
4,337
0.95
0.173913
0.412844
react-lib
627
2024-09-05T04:38:41.008079
Apache-2.0
false
50bd068bf12726394e4aa9253aa794f0
//===--- SimplifyStructExtract.swift --------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension StructExtractInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n guard let structInst = self.struct as? StructInst else {\n return\n }\n context.tryReplaceRedundantInstructionPair(first: structInst, second: self,\n with: structInst.operands[fieldIndex].value)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyStructExtract.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyStructExtract.swift
Swift
886
0.95
0.086957
0.52381
vue-tools
611
2025-02-02T09:20:42.338310
BSD-3-Clause
false
9000420d3227587438b6481395caab73
//===--- SimplifySwitchEnum.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n// Removes an `enum` - `switch_enum` pair:\n// ```\n// %1 = enum $E, #someCase, %payload\n// switch_enum %1, case #someCase: bb1, ...\n// bb1(%payloadArgument):\n// ```\n// ->\n// ```\n// br bb1(%payload)\n// bb1(%payloadArgument):\n// ```\n//\n// Other case blocks of the switch_enum become dead.\n//\nextension SwitchEnumInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n guard let enumInst = enumOp as? EnumInst,\n let caseBlock = getUniqueSuccessor(forCaseIndex: enumInst.caseIndex) else\n {\n return\n }\n\n let singleUse = context.preserveDebugInfo ? enumInst.uses.singleUse : enumInst.uses.ignoreDebugUses.singleUse\n let canEraseEnumInst = singleUse?.instruction == self\n\n if !canEraseEnumInst && parentFunction.hasOwnership && enumInst.ownership == .owned {\n // We cannot add more uses to the `enum` instruction without inserting a copy.\n return\n }\n\n let builder = Builder(before: self, context)\n switch caseBlock.arguments.count {\n case 0:\n precondition(enumInst.payload == nil || !parentFunction.hasOwnership,\n "missing payload argument in switch_enum case block")\n builder.createBranch(to: caseBlock)\n context.erase(instruction: self)\n case 1:\n builder.createBranch(to: caseBlock, arguments: [enumInst.payload!])\n context.erase(instruction: self)\n updateBorrowedFrom(for: [Phi(caseBlock.arguments[0])!], context)\n default:\n fatalError("case block of switch_enum cannot have more than 1 argument")\n }\n\n if canEraseEnumInst {\n context.erase(instructionIncludingDebugUses: enumInst)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifySwitchEnum.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifySwitchEnum.swift
Swift
2,176
0.95
0.09375
0.448276
awesome-app
364
2024-11-18T22:48:28.284637
GPL-3.0
false
b9dea396c4b08454e852b4f5c275a758
//===--- SimplifyTuple.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension TupleInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Eliminate the redundant instruction pair\n // ```\n // (%3, %4, %5) = destructure_tuple %input\n // %output = tuple (%3, %4, %5)\n // ```\n // and replace the result %output with %input\n //\n var destructure: DestructureTupleInst?\n for operand in operands {\n guard let def = operand.value.definingInstruction as? DestructureTupleInst else {\n return\n }\n guard let destructure else {\n destructure = def\n continue\n }\n if destructure != def {\n return\n }\n }\n guard let destructure else {\n return\n }\n guard destructure.operand.value.type == type else {\n return\n }\n // The destructure's operand having the same type as the tuple ensures that\n // the count of results of the destructure is equal to the count of operands\n // of the tuple.\n assert(destructure.results.count == operands.count)\n for (result, operand) in zip(destructure.results, operands) {\n if result != operand.value {\n return\n }\n }\n tryReplaceDestructConstructPair(destruct: destructure, construct: self, context)\n }\n}\n\nprivate func tryReplaceDestructConstructPair(destruct: MultipleValueInstruction & UnaryInstruction,\n construct: SingleValueInstruction,\n _ context: SimplifyContext) {\n let everyResultUsedOnce = context.preserveDebugInfo\n ? destruct.results.allSatisfy { $0.uses.singleUse != nil }\n : destruct.results.allSatisfy { $0.uses.ignoreDebugUses.singleUse != nil }\n let anyOwned = destruct.results.contains { $0.ownership == .owned }\n\n if !everyResultUsedOnce && construct.parentFunction.hasOwnership && anyOwned {\n // We cannot add more uses to this destructure without inserting a copy.\n return\n }\n\n construct.uses.replaceAll(with: destruct.operand.value, context)\n\n if everyResultUsedOnce {\n context.erase(instructionIncludingDebugUses: construct)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyTuple.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyTuple.swift
Swift
2,633
0.95
0.146667
0.323529
node-utils
510
2024-01-13T09:51:34.028085
BSD-3-Clause
false
086d338325e56f4ff3056149d9208244
//===--- SimplifyTupleExtract.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension TupleExtractInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Replace tuple_extract(tuple(x)) -> x\n\n guard let tupleInst = tuple as? TupleInst else {\n return\n }\n context.tryReplaceRedundantInstructionPair(first: tupleInst, second: self,\n with: tupleInst.operands[fieldIndex].value)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyTupleExtract.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyTupleExtract.swift
Swift
921
0.95
0.076923
0.545455
python-kit
695
2024-05-06T11:49:09.570580
BSD-3-Clause
false
7588fd23439df5e684593a3bb39038ef
//===--- SimplifyUncheckedEnumData.swift ----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension UncheckedEnumDataInst : OnoneSimplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n guard let enumInst = self.enum as? EnumInst else {\n return\n }\n if caseIndex != enumInst.caseIndex {\n return\n }\n context.tryReplaceRedundantInstructionPair(first: enumInst, second: self, with: enumInst.payload!)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyUncheckedEnumData.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyUncheckedEnumData.swift
Swift
899
0.95
0.12
0.478261
vue-tools
218
2024-03-13T04:59:21.180935
Apache-2.0
false
5bf3a2131a590b21b7af8f5b1e79db40
//===--- SimplifyValueToBridgeObject.swift --------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension ValueToBridgeObjectInst : OnoneSimplifiable {\n func simplify(_ context: SimplifyContext) {\n\n // Optimize the sequence\n // ```\n // %1 = value_to_bridge_object %0\n // %2 = struct $SomeInt (%1)\n // %3 = unchecked_trivial_bit_cast %2\n // %4 = struct_extract %3, #valueFieldInInt\n // %5 = value_to_bridge_object %4\n // ```\n // to\n // ```\n // %5 = value_to_bridge_object %0\n // ```\n // This sequence comes up in the code for constructing an empty string literal.\n //\n if let se = self.value as? StructExtractInst,\n let utbc = se.struct as? UncheckedTrivialBitCastInst,\n let vtbo = utbc.fromValue as? ValueToBridgeObjectInst {\n self.operand.set(to: vtbo.value, context)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyValueToBridgeObject.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyValueToBridgeObject.swift
Swift
1,292
0.95
0.105263
0.714286
react-lib
699
2024-01-18T11:59:47.364902
BSD-3-Clause
false
ef698b2370d621259ba4e97ae76b97b5
//===--- SimplifyWitnessMethod.swift --------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\nextension WitnessMethodInst : Simplifiable, SILCombineSimplifiable {\n func simplify(_ context: SimplifyContext) {\n _ = tryReplaceExistentialArchetype(of: self, context)\n }\n}\n\n/// If the witness_method operates on an existential archetype (`@opened("...")`) and the concrete\n/// type is known, replace the existential archetype with the concrete type.\n/// For example:\n/// ```\n/// %3 = witness_method $@opened("...", P) Self, #P.foo, %2\n/// ```\n/// ->\n/// ```\n/// %3 = witness_method $ConcreteType, #P.foo, %2\n/// ```\nprivate func tryReplaceExistentialArchetype(of witnessMethod: WitnessMethodInst, _ context: SimplifyContext) -> Bool {\n guard let concreteType = witnessMethod.concreteTypeOfDependentExistentialArchetype else {\n return false\n }\n let conf = concreteType.checkConformance(to: witnessMethod.lookupProtocol)\n guard conf.isValid else {\n return false\n }\n\n let builder = Builder(before: witnessMethod, context)\n let newWmi = builder.createWitnessMethod(lookupType: concreteType,\n conformance: conf,\n member: witnessMethod.member,\n methodType: witnessMethod.type)\n witnessMethod.replace(with: newWmi, context)\n return true\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyWitnessMethod.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_InstructionSimplification_SimplifyWitnessMethod.swift
Swift
1,826
0.95
0.041667
0.477273
node-utils
814
2025-02-26T13:28:05.463722
MIT
false
5f9521b1202a5cadcde35c0d4d5aeb97
//===--------- DiagnoseUnknownConstValues.swift --------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport AST\n\n/// Performs mandatory diagnostic pass for emitting errors for '@const' values which the compiler was not able to\n/// simplify/interpret/reduce to a symbolic value.\n///\nlet diagnoseUnknownConstValues = ModulePass(name: "diagnose-unknown-const-values") {\n (moduleContext: ModulePassContext) in\n var constExprEvaluator: ConstExpressionEvaluator = .init()\n defer { constExprEvaluator.deinitialize() }\n \n // Verify all const globals to be initialized with compile-time known values\n verifyGlobals(moduleContext)\n \n // Verify @const lets appearing as local variables\n verifyLocals(constExprEvaluator: &constExprEvaluator,\n moduleContext)\n \n // For each function call, ensure arguments to @const parameters are all compile-time known values\n verifyCallArguments(constExprEvaluator: &constExprEvaluator,\n moduleContext)\n \n // For each `@const` function, ensure it is fully evaluable/interpretable at compile time\n verifyFunctions(moduleContext)\n}\n\nprivate func verifyGlobals(_ context: ModulePassContext) {\n for gv in context.globalVariables where gv.isConst {\n if gv.staticInitValue == nil {\n context.diagnosticEngine.diagnose(.require_const_initializer_for_const,\n at: gv.varDecl?.location.sourceLoc)\n }\n }\n}\n\nprivate func verifyLocals(constExprEvaluator: inout ConstExpressionEvaluator,\n _ context: ModulePassContext) {\n for f in context.functions {\n for i in f.instructions {\n if let dbi = i as? DebugValueInst {\n verifyLocal(debugValueInst: dbi, constExprState: &constExprEvaluator, in: context)\n }\n }\n }\n}\n\nprivate func verifyLocal(debugValueInst: DebugValueInst,\n constExprState: inout ConstExpressionEvaluator,\n in context: ModulePassContext) {\n guard let localVarDecl = debugValueInst.varDecl,\n !(localVarDecl is ParamDecl),\n localVarDecl.isConst else {\n return\n }\n \n if !constExprState.isConstantValue(debugValueInst.operand.value) {\n context.diagnosticEngine.diagnose(.require_const_initializer_for_const,\n at: debugValueInst.location)\n }\n}\n\nprivate func verifyCallArguments(constExprEvaluator: inout ConstExpressionEvaluator,\n _ context: ModulePassContext) {\n for f in context.functions {\n for i in f.instructions {\n // TODO: Consider closures (partial_apply)\n if let apply = i as? FullApplySite {\n verifyCallArguments(apply: apply, constExprState: &constExprEvaluator, in: context)\n }\n }\n }\n}\n\nprivate func verifyCallArguments(apply: FullApplySite,\n constExprState: inout ConstExpressionEvaluator,\n in context: ModulePassContext) {\n guard let calleeFn = apply.referencedFunction else {\n return\n }\n for (paramIdx, param) in calleeFn.convention.parameters.enumerated() where param.hasOption(.const) {\n let matchingOperand = apply.parameterOperands[paramIdx]\n if !constExprState.isConstantValue(matchingOperand.value) {\n context.diagnosticEngine.diagnose(.require_const_arg_for_parameter,\n at: apply.location)\n }\n }\n}\n\nprivate func verifyFunctions(_ context: ModulePassContext) {\n // TODO: Implement\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_DiagnoseUnknownConstValues.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_DiagnoseUnknownConstValues.swift
Swift
3,896
0.95
0.165049
0.222222
awesome-app
489
2025-03-06T22:53:16.599684
GPL-3.0
false
9118ba3664eea982c9d79826bd7b0467
//===--- EmbeddedSwiftDiagnostics.swift -----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\n/// Diagnoses violations of Embedded Swift language restrictions.\n///\nlet embeddedSwiftDiagnostics = ModulePass(name: "embedded-swift-diagnostics") {\n (moduleContext: ModulePassContext) in\n\n guard moduleContext.options.enableEmbeddedSwift,\n // Skip all embedded diagnostics if asked. This is used from SourceKit to avoid reporting\n // false positives when WMO is turned off for indexing purposes.\n moduleContext.enableWMORequiredDiagnostics\n else {\n return\n }\n\n // Try to start with public and exported functions to get better caller information in the diagnostics.\n let allFunctions = Array(moduleContext.functions.lazy.filter { !$0.isGeneric })\n .sorted(by: { $0.priority < $1.priority })\n\n var checker = FunctionChecker(moduleContext)\n defer { checker.deinitialize() }\n\n for function in allFunctions {\n do {\n assert(checker.callStack.isEmpty)\n try checker.checkFunction(function)\n } catch let error as Diagnostic {\n checker.diagnose(error)\n } catch {\n fatalError("unknown error thrown")\n }\n }\n\n checkVTables(moduleContext)\n}\n\nprivate struct FunctionChecker {\n let context: ModulePassContext\n var visitedFunctions = Set<Function>()\n var visitedConformances = Set<Conformance>()\n var callStack: Stack<CallSite>\n\n init(_ context: ModulePassContext) {\n self.context = context\n self.callStack = Stack(context)\n }\n\n mutating func deinitialize() {\n callStack.deinitialize()\n }\n\n mutating func checkFunction(_ function: Function) throws {\n guard function.isDefinition,\n // Avoid infinite recursion\n visitedFunctions.insert(function).inserted\n else {\n return\n }\n\n for inst in function.instructions {\n try checkInstruction(inst)\n }\n }\n\n mutating func checkInstruction(_ instruction: Instruction) throws {\n switch instruction {\n case is OpenExistentialMetatypeInst,\n is InitExistentialMetatypeInst:\n throw Diagnostic(.embedded_swift_metatype_type, instruction.operands[0].value.type, at: instruction.location)\n\n case is OpenExistentialBoxInst,\n is OpenExistentialBoxValueInst,\n is OpenExistentialValueInst,\n is OpenExistentialAddrInst,\n is InitExistentialAddrInst,\n is InitExistentialValueInst,\n is ExistentialMetatypeInst:\n throw Diagnostic(.embedded_swift_existential_type, instruction.operands[0].value.type, at: instruction.location)\n\n case let aeb as AllocExistentialBoxInst:\n throw Diagnostic(.embedded_swift_existential_type, aeb.type, at: instruction.location)\n\n case let ier as InitExistentialRefInst:\n for conf in ier.conformances {\n try checkConformance(conf, location: ier.location)\n }\n\n case is ValueMetatypeInst,\n is MetatypeInst:\n let metaType = (instruction as! SingleValueInstruction).type\n if metaType.representationOfMetatype != .thin {\n let rawType = metaType.canonicalType.rawType.instanceTypeOfMetatype\n let type = rawType.isDynamicSelf ? rawType.staticTypeOfDynamicSelf : rawType\n if !type.isClass {\n throw Diagnostic(.embedded_swift_metatype_type, type, at: instruction.location)\n }\n }\n\n case is KeyPathInst:\n throw Diagnostic(.embedded_swift_keypath, at: instruction.location)\n\n case is CheckedCastAddrBranchInst,\n is UnconditionalCheckedCastAddrInst:\n throw Diagnostic(.embedded_swift_dynamic_cast, at: instruction.location)\n\n case let abi as AllocBoxInst:\n // It needs a bit of work to support alloc_box of generic non-copyable structs/enums with deinit,\n // because we need to specialize the deinit functions, though they are not explicitly referenced in SIL.\n // Until this is supported, give an error in such cases. Otherwise IRGen would crash.\n if abi.allocsGenericValueTypeWithDeinit {\n throw Diagnostic(.embedded_capture_of_generic_value_with_deinit, at: abi.location)\n }\n fallthrough\n case is AllocRefInst,\n is AllocRefDynamicInst:\n if context.options.noAllocations {\n throw Diagnostic(.embedded_swift_allocating_type, (instruction as! SingleValueInstruction).type,\n at: instruction.location)\n }\n case is BeginApplyInst:\n throw Diagnostic(.embedded_swift_allocating_coroutine, at: instruction.location)\n case is ThunkInst:\n throw Diagnostic(.embedded_swift_allocating, at: instruction.location)\n\n case let pai as PartialApplyInst:\n if context.options.noAllocations && !pai.isOnStack {\n throw Diagnostic(.embedded_swift_allocating_closure, at: instruction.location)\n }\n\n case let bi as BuiltinInst:\n switch bi.id {\n case .AllocRaw:\n if context.options.noAllocations {\n throw Diagnostic(.embedded_swift_allocating, at: instruction.location)\n }\n case .BuildOrdinaryTaskExecutorRef,\n .BuildOrdinarySerialExecutorRef,\n .BuildComplexEqualitySerialExecutorRef:\n // Those builtins implicitly create an existential.\n try checkConformance(bi.substitutionMap.conformances[0], location: bi.location)\n\n default:\n break\n }\n\n case let apply as ApplySite:\n if context.options.noAllocations && apply.isAsync {\n throw Diagnostic(.embedded_swift_allocating_type, at: instruction.location)\n }\n\n if !apply.callee.type.hasValidSignatureForEmbedded,\n // Some runtime functions have generic parameters in SIL, which are not used in IRGen.\n // Therefore exclude runtime functions at all.\n !apply.callsEmbeddedRuntimeFunction\n {\n switch apply.callee {\n case let cmi as ClassMethodInst:\n throw Diagnostic(.embedded_cannot_specialize_class_method, cmi.member, at: instruction.location)\n case let wmi as WitnessMethodInst:\n throw Diagnostic(.embedded_cannot_specialize_witness_method, wmi.member, at: instruction.location)\n default:\n throw Diagnostic(.embedded_call_generic_function, at: instruction.location)\n }\n }\n\n // Although all (non-generic) functions are initially put into the worklist there are two reasons\n // to call `checkFunction` recursively:\n // * To get a better caller info in the diagnostics.\n // * When passing an opened existential to a generic function, it's valid in Embedded swift even if the\n // generic is not specialized. We need to check such generic functions, too.\n if let callee = apply.referencedFunction {\n callStack.push(CallSite(apply: apply, callee: callee))\n try checkFunction(callee)\n _ = callStack.pop()\n }\n\n default:\n break\n }\n }\n\n // Check for any violations in witness tables for existentials.\n mutating func checkConformance(_ conformance: Conformance, location: Location) throws {\n guard conformance.isConcrete,\n // Avoid infinite recursion\n visitedConformances.insert(conformance).inserted,\n let witnessTable = context.lookupWitnessTable(for: conformance)\n else {\n return\n }\n if !conformance.protocol.requiresClass {\n throw Diagnostic(.embedded_swift_existential_protocol, conformance.protocol.name, at: location)\n }\n\n for entry in witnessTable.entries {\n switch entry {\n case .invalid, .associatedType:\n break\n case .method(let requirement, let witness):\n if let witness = witness {\n callStack.push(CallSite(location: location, kind: .conformance))\n if witness.isGeneric {\n throw Diagnostic(.embedded_cannot_specialize_witness_method, requirement, at: witness.location)\n }\n try checkFunction(witness)\n _ = callStack.pop()\n }\n case .baseProtocol(_, let witness):\n try checkConformance(witness, location: location)\n case .associatedConformance(_, let assocConf):\n // If it's not a class protocol, the associated type can never be used to create\n // an existential. Therefore this witness entry is never used at runtime in embedded swift.\n if assocConf.protocol.requiresClass {\n try checkConformance(assocConf, location: location)\n }\n }\n }\n }\n\n mutating func diagnose(_ error: Diagnostic) {\n var diagPrinted = false\n if error.position != nil {\n context.diagnosticEngine.diagnose(error)\n diagPrinted = true\n }\n\n // If the original instruction doesn't have a location (e.g. because it's in a stdlib function),\n // search the callstack and use the location from a call site.\n while let callSite = callStack.pop() {\n if !diagPrinted {\n if callSite.location.hasValidLineNumber {\n context.diagnosticEngine.diagnose(error.id, error.arguments, at: callSite.location)\n diagPrinted = true\n }\n } else {\n // Print useful callsite information as a note (see `CallSite`)\n switch callSite.kind {\n case .constructorCall:\n context.diagnosticEngine.diagnose(.embedded_constructor_called, at: callSite.location)\n case .specializedCall:\n context.diagnosticEngine.diagnose(.embedded_specialization_called_from, at: callSite.location)\n case .conformance:\n context.diagnosticEngine.diagnose(.embedded_existential_created, at: callSite.location)\n case .call:\n break\n }\n }\n }\n if !diagPrinted {\n context.diagnosticEngine.diagnose(error)\n }\n }\n}\n\n// Print errors for generic functions in vtables, which is not allowed in embedded Swift.\nprivate func checkVTables(_ context: ModulePassContext) {\n for vTable in context.vTables {\n if !vTable.class.isGenericAtAnyLevel || vTable.isSpecialized {\n for entry in vTable.entries where entry.implementation.isGeneric {\n context.diagnosticEngine.diagnose(.embedded_cannot_specialize_class_method, entry.methodDecl,\n at: entry.methodDecl.location)\n }\n }\n }\n}\n\n/// Relevant call site information for diagnostics.\n/// This information is printed as additional note(s) after the original diagnostic.\nprivate struct CallSite {\n enum Kind {\n // A regular function call. Not every function call in the call stack is printed in diagnostics.\n // This is only used if the original instruction doesn't have a location.\n case call\n\n // If the error is in a constructor, this is the place where the object/value is created.\n case constructorCall\n\n // If the error is in a specialized function, this is the place where the generic function is originally\n // specialized with concrete types. This is useful if a specialized type is relevant for the error.\n case specializedCall\n\n // If the error is in a protocol witness method, this is the place where the existential is created.\n case conformance\n }\n\n let location: Location\n let kind: Kind\n\n init(apply: ApplySite, callee: Function) {\n self.location = apply.location\n if let d = callee.location.decl, d is ConstructorDecl {\n self.kind = .constructorCall\n } else if callee.isSpecialization && !apply.parentFunction.isSpecialization {\n self.kind = .specializedCall\n } else {\n self.kind = .call\n }\n }\n\n init(location: Location, kind: Kind) {\n self.location = location\n self.kind = kind\n }\n}\n\nprivate extension Function {\n // The priority (1 = highest) which defines the order in which functions are checked.\n // This is important to get good caller information in diagnostics.\n var priority: Int {\n // There might be functions without a location, e.g. `swift_readAtKeyPath` generated by SILGen for keypaths.\n // It's okay to skip the ctor/dtor/method detection logic for those.\n if location.hasValidLineNumber {\n if let decl = location.decl {\n if decl is DestructorDecl || decl is ConstructorDecl {\n return 4\n }\n if let parent = decl.parent, parent is ClassDecl {\n return 2\n }\n }\n }\n if isPossiblyUsedExternally {\n return 1\n }\n return 3\n }\n}\n\nprivate extension AllocBoxInst {\n var allocsGenericValueTypeWithDeinit: Bool {\n type.getBoxFields(in: parentFunction).contains { $0.hasGenericValueDeinit(in: parentFunction) }\n }\n}\n\nprivate extension ApplySite {\n var callsEmbeddedRuntimeFunction: Bool {\n if let callee = referencedFunction,\n !callee.isDefinition,\n !callee.name.startsWith("$e")\n {\n return true\n }\n return false\n }\n}\n\nprivate extension Type {\n func hasGenericValueDeinit(in function: Function) -> Bool {\n guard isMoveOnly, let nominal = nominal else {\n return false\n }\n\n if nominal.isGenericAtAnyLevel && nominal.valueTypeDestructor != nil {\n return true\n }\n\n if isStruct {\n if let fields = getNominalFields(in: function) {\n return fields.contains { $0.hasGenericValueDeinit(in: function) }\n }\n } else if isEnum {\n if let enumCases = getEnumCases(in: function) {\n return enumCases.contains { $0.payload?.hasGenericValueDeinit(in: function) ?? false }\n }\n }\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_EmbeddedSwiftDiagnostics.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_EmbeddedSwiftDiagnostics.swift
Swift
13,694
0.95
0.228346
0.142857
vue-tools
507
2025-06-21T14:36:11.470292
Apache-2.0
false
3cf14e54c7df3487862e491151efbeb4
//===--- MandatoryPerformanceOptimizations.swift --------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\n/// Performs mandatory optimizations for performance-annotated functions, and global\n/// variable initializers that are required to be statically initialized.\n///\n/// Optimizations include:\n/// * de-virtualization\n/// * mandatory inlining\n/// * generic specialization\n/// * mandatory memory optimizations\n/// * dead alloc elimination\n/// * instruction simplification\n///\n/// The pass starts with performance-annotated functions / globals and transitively handles\n/// called functions.\n///\nlet mandatoryPerformanceOptimizations = ModulePass(name: "mandatory-performance-optimizations") {\n (moduleContext: ModulePassContext) in\n\n var worklist = FunctionWorklist()\n // For embedded Swift, optimize all the functions (there cannot be any\n // generics, type metadata, etc.)\n if moduleContext.options.enableEmbeddedSwift {\n worklist.addAllNonGenericFunctions(of: moduleContext)\n } else {\n worklist.addAllMandatoryRequiredFunctions(of: moduleContext)\n }\n\n optimizeFunctionsTopDown(using: &worklist, moduleContext)\n}\n\nprivate func optimizeFunctionsTopDown(using worklist: inout FunctionWorklist,\n _ moduleContext: ModulePassContext) {\n while let f = worklist.pop() {\n moduleContext.transform(function: f) { context in\n if !context.loadFunction(function: f, loadCalleesRecursively: true) {\n return\n }\n\n // It's not required to set the perf_constraint flag on all functions in embedded mode.\n // Embedded mode already implies that flag.\n if !moduleContext.options.enableEmbeddedSwift {\n f.set(isPerformanceConstraint: true, context)\n }\n\n optimize(function: f, context, moduleContext, &worklist)\n }\n\n // Generic specialization takes care of removing metatype arguments of generic functions.\n // But sometimes non-generic functions have metatype arguments which must be removed.\n // We need handle this case with a function signature optimization.\n removeMetatypeArgumentsInCallees(of: f, moduleContext)\n\n worklist.addCallees(of: f)\n }\n}\n\nfileprivate struct PathFunctionTuple: Hashable {\n var path: SmallProjectionPath\n var function: Function\n}\n\nprivate func optimize(function: Function, _ context: FunctionPassContext, _ moduleContext: ModulePassContext, _ worklist: inout FunctionWorklist) {\n var alreadyInlinedFunctions: Set<PathFunctionTuple> = Set()\n\n // ObjectOutliner replaces calls to findStringSwitchCase with _findStringSwitchCaseWithCache, but this happens as a late SIL optimization,\n // which is a problem for Embedded Swift, because _findStringSwitchCaseWithCache will then reference non-specialized code. Solve this by\n // eagerly linking and specializing _findStringSwitchCaseWithCache whenever findStringSwitchCase is found in the module.\n if context.options.enableEmbeddedSwift {\n if function.hasSemanticsAttribute("findStringSwitchCase"),\n let f = context.lookupStdlibFunction(name: "_findStringSwitchCaseWithCache"),\n context.loadFunction(function: f, loadCalleesRecursively: true) {\n worklist.pushIfNotVisited(f)\n }\n }\n \n var changed = true\n while changed {\n changed = runSimplification(on: function, context, preserveDebugInfo: true) { instruction, simplifyCtxt in\n if let i = instruction as? OnoneSimplifiable {\n i.simplify(simplifyCtxt)\n if instruction.isDeleted {\n return\n }\n }\n switch instruction {\n case let apply as FullApplySite:\n inlineAndDevirtualize(apply: apply, alreadyInlinedFunctions: &alreadyInlinedFunctions, context, simplifyCtxt)\n\n // Embedded Swift specific transformations\n case let alloc as AllocRefInst:\n if context.options.enableEmbeddedSwift {\n specializeVTable(forClassType: alloc.type, errorLocation: alloc.location, moduleContext) {\n worklist.pushIfNotVisited($0)\n }\n }\n case let metatype as MetatypeInst:\n if context.options.enableEmbeddedSwift {\n let instanceType = metatype.type.loweredInstanceTypeOfMetatype(in: function)\n if instanceType.isClass {\n specializeVTable(forClassType: instanceType, errorLocation: metatype.location, moduleContext) {\n worklist.pushIfNotVisited($0)\n }\n }\n }\n case let classMethod as ClassMethodInst:\n if context.options.enableEmbeddedSwift {\n _ = context.specializeClassMethodInst(classMethod)\n }\n case let witnessMethod as WitnessMethodInst:\n if context.options.enableEmbeddedSwift {\n _ = context.specializeWitnessMethodInst(witnessMethod)\n }\n\n case let initExRef as InitExistentialRefInst:\n if context.options.enableEmbeddedSwift {\n for c in initExRef.conformances where c.isConcrete {\n specializeWitnessTable(for: c, moduleContext) {\n worklist.addWitnessMethods(of: $0)\n }\n }\n }\n\n case let bi as BuiltinInst:\n switch bi.id {\n case .BuildOrdinaryTaskExecutorRef,\n .BuildOrdinarySerialExecutorRef,\n .BuildComplexEqualitySerialExecutorRef:\n specializeWitnessTable(for: bi.substitutionMap.conformances[0], moduleContext) {\n worklist.addWitnessMethods(of: $0)\n }\n\n default:\n break\n }\n\n\n // We need to de-virtualize deinits of non-copyable types to be able to specialize the deinitializers.\n case let destroyValue as DestroyValueInst:\n if !devirtualizeDeinits(of: destroyValue, simplifyCtxt) {\n context.diagnosticEngine.diagnose(.deinit_not_visible, at: destroyValue.location)\n }\n case let destroyAddr as DestroyAddrInst:\n if !devirtualizeDeinits(of: destroyAddr, simplifyCtxt) {\n context.diagnosticEngine.diagnose(.deinit_not_visible, at: destroyAddr.location)\n }\n\n case let iem as InitExistentialMetatypeInst:\n if iem.uses.ignoreDebugUses.isEmpty {\n context.erase(instructionIncludingDebugUses: iem)\n }\n\n case let fri as FunctionRefInst:\n // Mandatory de-virtualization and mandatory inlining might leave referenced functions in "serialized"\n // functions with wrong linkage. Fix this by making the referenced function public.\n // It's not great, because it can prevent dead code elimination. But it's only a rare case.\n if function.serializedKind != .notSerialized,\n !fri.referencedFunction.hasValidLinkageForFragileRef(function.serializedKind)\n {\n fri.referencedFunction.set(linkage: .public, moduleContext)\n }\n \n case let copy as CopyAddrInst:\n if function.isGlobalInitOnceFunction, copy.source.type.isLoadable(in: function) {\n // In global init functions we have to make sure that redundant load elimination can remove all\n // loads (from temporary stack locations) so that globals can be statically initialized.\n // For this it's necessary to load copy_addr instructions to loads and stores.\n copy.replaceWithLoadAndStore(simplifyCtxt)\n }\n\n default:\n break\n }\n }\n\n _ = context.specializeApplies(in: function, isMandatory: true)\n\n removeUnusedMetatypeInstructions(in: function, context)\n\n // If this is a just specialized function, try to optimize copy_addr, etc.\n if eliminateRedundantLoads(in: function,\n variant: function.isGlobalInitOnceFunction ? .mandatoryInGlobalInit : .mandatory,\n context)\n {\n changed = true\n }\n\n changed = context.eliminateDeadAllocations(in: function) || changed\n }\n}\n\nprivate func inlineAndDevirtualize(apply: FullApplySite, alreadyInlinedFunctions: inout Set<PathFunctionTuple>,\n _ context: FunctionPassContext, _ simplifyCtxt: SimplifyContext) {\n // De-virtualization and inlining in/into a "serialized" function might create function references to functions\n // with wrong linkage. We need to fix this later (see handling of FunctionRefInst in `optimize`).\n if simplifyCtxt.tryDevirtualize(apply: apply, isMandatory: true) != nil {\n return\n }\n\n guard let callee = apply.referencedFunction else {\n return\n }\n\n if !context.loadFunction(function: callee, loadCalleesRecursively: true) {\n // We don't have the function body of the callee.\n return\n }\n\n if shouldInline(apply: apply, callee: callee, alreadyInlinedFunctions: &alreadyInlinedFunctions) {\n if apply.inliningCanInvalidateStackNesting {\n simplifyCtxt.notifyInvalidatedStackNesting()\n }\n\n simplifyCtxt.inlineFunction(apply: apply, mandatoryInline: true)\n }\n}\n\nprivate func removeMetatypeArgumentsInCallees(of function: Function, _ context: ModulePassContext) {\n for inst in function.instructions {\n if let apply = inst as? FullApplySite {\n specializeByRemovingMetatypeArguments(apply: apply, context)\n }\n }\n}\n\nprivate func removeUnusedMetatypeInstructions(in function: Function, _ context: FunctionPassContext) {\n for inst in function.instructions {\n if let mt = inst as? MetatypeInst,\n mt.isTriviallyDeadIgnoringDebugUses {\n context.erase(instructionIncludingDebugUses: mt)\n }\n }\n}\n\nprivate func shouldInline(apply: FullApplySite, callee: Function, alreadyInlinedFunctions: inout Set<PathFunctionTuple>) -> Bool {\n if let beginApply = apply as? BeginApplyInst,\n !beginApply.canInline\n {\n return false\n }\n\n if !callee.canBeInlinedIntoCaller(withSerializedKind: apply.parentFunction.serializedKind) &&\n // Even if the serialization kind doesn't match, we need to make sure to inline witness method thunks\n // in embedded swift.\n callee.thunkKind != .thunk\n {\n return false\n }\n\n // Cannot inline a non-ossa function into an ossa function\n if apply.parentFunction.hasOwnership && !callee.hasOwnership {\n return false\n }\n\n if callee.isTransparent {\n precondition(callee.hasOwnership, "transparent functions should have ownership at this stage of the pipeline")\n return true\n }\n\n if apply is BeginApplyInst {\n // Avoid co-routines because they might allocate (their context).\n return true\n }\n\n if callee.mayBindDynamicSelf {\n // We don't support inlining a function that binds dynamic self into a global-init function\n // because the global-init function cannot provide the self metadata.\n return false\n }\n\n if apply.parentFunction.isGlobalInitOnceFunction && callee.inlineStrategy == .always {\n // Some arithmetic operations, like integer conversions, are not transparent but `inline(__always)`.\n // Force inlining them in global initializers so that it's possible to statically initialize the global.\n return true\n }\n\n if apply.substitutionMap.isEmpty,\n let pathIntoGlobal = apply.resultIsUsedInGlobalInitialization(),\n alreadyInlinedFunctions.insert(PathFunctionTuple(path: pathIntoGlobal, function: callee)).inserted {\n return true\n }\n\n return false\n}\n\nprivate extension FullApplySite {\n func resultIsUsedInGlobalInitialization() -> SmallProjectionPath? {\n guard parentFunction.isGlobalInitOnceFunction,\n let global = parentFunction.getInitializedGlobal() else {\n return nil\n }\n\n switch numIndirectResultArguments {\n case 0:\n return singleDirectResult?.isStored(to: global)\n case 1:\n let resultAccessPath = arguments[0].accessPath\n switch resultAccessPath.base {\n case .global(let resultGlobal) where resultGlobal == global:\n return resultAccessPath.materializableProjectionPath\n case .stack(let allocStack) where resultAccessPath.projectionPath.isEmpty:\n return allocStack.getStoredValue(by: self)?.isStored(to: global)\n default:\n return nil\n }\n default:\n return nil\n }\n }\n}\n\nprivate extension AllocStackInst {\n func getStoredValue(by storingInstruction: Instruction) -> Value? {\n // If the only use (beside `storingInstruction`) is a load, it's the value which is\n // stored by `storingInstruction`.\n var loadedValue: Value? = nil\n for use in self.uses {\n switch use.instruction {\n case is DeallocStackInst:\n break\n case let load as LoadInst:\n if loadedValue != nil {\n return nil\n }\n loadedValue = load\n default:\n if use.instruction != storingInstruction {\n return nil\n }\n }\n }\n return loadedValue\n }\n}\n\nprivate extension Value {\n /// Analyzes the def-use chain of an apply instruction, and looks for a single chain that leads to a store instruction\n /// that initializes a part of a global variable or the entire variable:\n ///\n /// Example:\n /// %g = global_addr @global\n /// ...\n /// %f = function_ref @func\n /// %apply = apply %f(...)\n /// store %apply to %g <--- is a store to the global trivially (the apply result is immediately going into a store)\n ///\n /// Example:\n /// %apply = apply %f(...)\n /// %apply2 = apply %f2(%apply)\n /// store %apply2 to %g <--- is a store to the global (the apply result has a single chain into the store)\n ///\n /// Example:\n /// %a = apply %f(...)\n /// %s = struct $MyStruct (%a, %b)\n /// store %s to %g <--- is a partial store to the global (returned SmallProjectionPath is MyStruct.s0)\n ///\n /// Example:\n /// %a = apply %f(...)\n /// %as = struct $AStruct (%other, %a)\n /// %bs = struct $BStruct (%as, %bother)\n /// store %bs to %g <--- is a partial store to the global (returned SmallProjectionPath is MyStruct.s0.s1)\n ///\n /// Returns nil if we cannot find a singular def-use use chain (e.g. because a value has more than one user)\n /// leading to a store to the specified global variable.\n func isStored(to global: GlobalVariable) -> SmallProjectionPath? {\n var singleUseValue: any Value = self\n var path = SmallProjectionPath()\n while true {\n // The initializer value of a global can contain access instructions if it references another\n // global variable by address, e.g.\n // var p = Point(x: 10, y: 20)\n // let o = UnsafePointer(&p)\n // Therefore ignore the `end_access` use of a `begin_access`.\n let relevantUses = singleUseValue.uses.ignoreDebugUses.ignoreUsers(ofType: EndAccessInst.self)\n\n guard let use = relevantUses.singleUse else {\n return nil\n }\n \n switch use.instruction {\n case is StructInst:\n path = path.push(.structField, index: use.index)\n break\n case is TupleInst:\n path = path.push(.tupleField, index: use.index)\n break\n case let ei as EnumInst:\n path = path.push(.enumCase, index: ei.caseIndex)\n break\n case let si as StoreInst:\n let accessPath = si.destination.getAccessPath(fromInitialPath: path)\n switch accessPath.base {\n case .global(let storedGlobal) where storedGlobal == global:\n return accessPath.materializableProjectionPath\n default:\n return nil\n }\n case is PointerToAddressInst, is AddressToPointerInst, is BeginAccessInst:\n break\n default:\n return nil\n }\n\n guard let nextInstruction = use.instruction as? SingleValueInstruction else {\n return nil\n }\n\n singleUseValue = nextInstruction\n }\n }\n}\n\nprivate extension Function {\n /// Analyzes the global initializer function and returns global it initializes (from `alloc_global` instruction).\n func getInitializedGlobal() -> GlobalVariable? {\n if !isDefinition {\n return nil\n }\n for inst in self.entryBlock.instructions {\n switch inst {\n case let agi as AllocGlobalInst:\n return agi.global\n default:\n break\n }\n }\n\n return nil\n }\n}\n\nfileprivate struct FunctionWorklist {\n private(set) var functions = Array<Function>()\n private var pushedFunctions = Set<Function>()\n private var currentIndex = 0\n\n mutating func pop() -> Function? {\n if currentIndex < functions.count {\n let f = functions[currentIndex]\n currentIndex += 1\n return f\n }\n return nil\n }\n \n mutating func addAllMandatoryRequiredFunctions(of moduleContext: ModulePassContext) {\n for f in moduleContext.functions {\n // Performance annotated functions\n if f.performanceConstraints != .none {\n pushIfNotVisited(f)\n }\n \n // Annotated global init-once functions\n if f.isGlobalInitOnceFunction {\n if let global = f.getInitializedGlobal(),\n global.mustBeInitializedStatically {\n pushIfNotVisited(f)\n }\n }\n \n // @const global init-once functions\n if f.isGlobalInitOnceFunction {\n if let global = f.getInitializedGlobal(),\n global.mustBeInitializedStatically {\n pushIfNotVisited(f)\n }\n }\n }\n }\n\n mutating func addAllNonGenericFunctions(of moduleContext: ModulePassContext) {\n for f in moduleContext.functions where !f.isGeneric {\n pushIfNotVisited(f)\n }\n return\n }\n\n mutating func addCallees(of function: Function) {\n for inst in function.instructions {\n switch inst {\n case let apply as ApplySite:\n if let callee = apply.referencedFunction {\n pushIfNotVisited(callee)\n }\n case let bi as BuiltinInst:\n switch bi.id {\n case .Once, .OnceWithContext:\n if let fri = bi.operands[1].value as? FunctionRefInst {\n pushIfNotVisited(fri.referencedFunction)\n }\n break;\n default:\n break\n }\n default:\n break\n }\n }\n }\n\n mutating func addWitnessMethods(of witnessTable: WitnessTable) {\n for entry in witnessTable.entries {\n if case .method(_, let witness) = entry,\n let method = witness,\n // A new witness table can still contain a generic function if the method couldn't be specialized for\n // some reason and an error has been printed. Exclude generic functions to not run into an assert later.\n !method.isGeneric\n {\n pushIfNotVisited(method)\n }\n }\n }\n\n mutating func pushIfNotVisited(_ element: Function) {\n if pushedFunctions.insert(element).inserted {\n functions.append(element)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_MandatoryPerformanceOptimizations.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_MandatoryPerformanceOptimizations.swift
Swift
18,806
0.95
0.229323
0.204255
awesome-app
152
2024-10-23T21:02:28.715219
GPL-3.0
false
468a3415f6885f44ad9ff66d495b2478
//===--- ReadOnlyGlobalVariables.swift ------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n/// Marks global `var` variables as `let` if they are never written.\n///\n/// Note that this pass relies on the initialize-static-globals pass which converts lazily\n/// initialized globals to statically initialized globals.\n/// This pass does not mark lazily initialized globals as `let`, because such globals _are_\n/// written: in their initializers.\n///\nlet readOnlyGlobalVariablesPass = ModulePass(name: "read-only-global-variables") {\n (moduleContext: ModulePassContext) in\n\n var writtenGlobals = Set<GlobalVariable>()\n\n for f in moduleContext.functions {\n for inst in f.instructions {\n if let gAddr = inst as? GlobalAddrInst {\n if findWrites(toAddress: gAddr) {\n writtenGlobals.insert(gAddr.global)\n }\n }\n }\n }\n\n for g in moduleContext.globalVariables {\n if !g.isDefinedExternally,\n !g.isPossiblyUsedExternally,\n !g.isLet,\n !writtenGlobals.contains(g) {\n g.setIsLet(to: true, moduleContext)\n }\n }\n}\n\nprivate func findWrites(toAddress: Value) -> Bool {\n var walker = FindWrites()\n return walker.walkDownUses(ofAddress: toAddress, path: UnusedWalkingPath()) == .abortWalk\n}\n\nprivate struct FindWrites : AddressDefUseWalker {\n mutating func leafUse(address: Operand, path: UnusedWalkingPath) -> WalkResult {\n switch address.instruction {\n case is LoadInst, is LoadBorrowInst:\n return .continueWalk\n\n case let ca as CopyAddrInst:\n return address == ca.sourceOperand ? .continueWalk : .abortWalk\n\n case let apply as FullApplySite:\n if let calleeArgIdx = apply.calleeArgumentIndex(of: address) {\n let convention = apply.calleeArgumentConventions[calleeArgIdx]\n if convention.isIndirectIn {\n return .continueWalk\n }\n }\n return .abortWalk\n default:\n return .abortWalk\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_ReadOnlyGlobalVariables.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_ReadOnlyGlobalVariables.swift
Swift
2,360
0.95
0.164384
0.28125
python-kit
101
2025-06-30T23:01:12.318761
MIT
false
ddb0eda2b83ab45e7ecd92d8b93fda19
//===--- StackProtection.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(_ message: @autoclosure () -> String) {\n if verbose {\n print("### \(message())")\n }\n}\n\n/// Decides which functions need stack protection.\n///\n/// Sets the `needStackProtection` flags on all function which contain stack-allocated\n/// values for which an buffer overflow could occur.\n///\n/// Within safe swift code there shouldn't be any buffer overflows. But if the address\n/// of a stack variable is converted to an unsafe pointer, it's not in the control of\n/// the compiler anymore.\n/// This means, if an `alloc_stack` ends up at an `address_to_pointer [stack_protection]`,\n/// the `alloc_stack`'s function is marked for stack protection.\n/// Another case is `index_addr [stack_protection]` for non-tail allocated memory. This\n/// pattern appears if pointer arithmetic is done with unsafe pointers in swift code.\n///\n/// If the origin of an unsafe pointer can only be tracked to a function argument, the\n/// pass tries to find the root stack allocation for such an argument by doing an\n/// inter-procedural analysis. If this is not possible and the `enableMoveInoutStackProtection`\n/// option is set, the fallback is to move the argument into a temporary `alloc_stack`\n/// and do the unsafe pointer operations on the temporary.\nlet stackProtection = ModulePass(name: "stack-protection") {\n (context: ModulePassContext) in\n\n if !context.options.enableStackProtection {\n return\n }\n\n var optimization = StackProtectionOptimization(enableMoveInout: context.options.enableMoveInoutStackProtection)\n optimization.processModule(context)\n}\n\n/// The stack-protection optimization on function-level.\n///\n/// In contrast to the `stack-protection` pass, this pass doesn't do any inter-procedural\n/// analysis. It runs at Onone.\nlet functionStackProtection = FunctionPass(name: "function-stack-protection") {\n (function: Function, context: FunctionPassContext) in\n\n if !context.options.enableStackProtection {\n return\n }\n\n var optimization = StackProtectionOptimization(enableMoveInout: context.options.enableMoveInoutStackProtection)\n optimization.process(function: function, context)\n}\n\n/// The optimization algorithm.\nprivate struct StackProtectionOptimization {\n\n private let enableMoveInout: Bool\n\n // The following members are nil/not used if this utility is used on function-level.\n\n private var moduleContext: ModulePassContext?\n private var functionUses = FunctionUses()\n private var functionUsesComputed = false\n\n // Functions (other than the currently processed one) which need stack protection,\n // are added to this array in `findOriginsInCallers`.\n private var needStackProtection: [Function] = []\n\n init(enableMoveInout: Bool) {\n self.enableMoveInout = enableMoveInout\n }\n\n /// The main entry point if running on module-level.\n mutating func processModule(_ moduleContext: ModulePassContext) {\n self.moduleContext = moduleContext\n\n // Collect all functions which need stack protection and insert required moves.\n for function in moduleContext.functions {\n\n moduleContext.transform(function: function) { context in\n process(function: function, context)\n }\n\n // We cannot modify other functions than the currently processed function in `process(function:)`.\n // Therefore, if `findOriginsInCallers` finds any callers, which need stack protection,\n // add the `needStackProtection` flags here.\n for function in needStackProtection {\n moduleContext.transform(function: function) { context in\n function.setNeedsStackProtection(context)\n }\n }\n needStackProtection.removeAll(keepingCapacity: true)\n }\n }\n \n /// The main entry point if running on function-level.\n mutating func process(function: Function, _ context: FunctionPassContext) {\n var mustFixStackNesting = false\n for inst in function.instructions {\n process(instruction: inst, in: function, mustFixStackNesting: &mustFixStackNesting, context)\n }\n if mustFixStackNesting {\n function.fixStackNesting(context)\n }\n }\n\n /// Checks if `instruction` may be an unsafe instruction which may cause a buffer overflow.\n ///\n /// If this is the case, either\n /// - set the function's `needStackProtection` flag if the relevant allocation is in the\n /// same function, or\n /// - if the address is passed as an argument: try to find the origin in its callers and\n /// add the relevant callers to `self.needStackProtection`, or\n /// - if the origin is unknown, move the value into a temporary and set the function's\n /// `needStackProtection` flag.\n private mutating func process(instruction: Instruction, in function: Function,\n mustFixStackNesting: inout Bool, _ context: FunctionPassContext) {\n\n // `withUnsafeTemporaryAllocation(of:capacity:_:)` is compiled to a `builtin "stackAlloc"`.\n if let bi = instruction as? BuiltinInst, bi.id == .StackAlloc {\n function.setNeedsStackProtection(context)\n return\n }\n\n // For example:\n // %accessBase = alloc_stack $S\n // %scope = begin_access [modify] %accessBase\n // %instruction = address_to_pointer [stack_protection] %scope\n //\n guard let (accessBase, scope) = instruction.accessBaseToProtect else {\n return\n }\n\n switch accessBase.isStackAllocated {\n case .no:\n // For example:\n // %baseAddr = global_addr @global\n break\n\n case .yes:\n // For example:\n // %baseAddr = alloc_stack $T\n log("local: \(function.name) -- \(instruction)")\n\n function.setNeedsStackProtection(context)\n\n case .decidedInCaller(let arg):\n // For example:\n // bb0(%baseAddr: $*T):\n\n var worklist = ArgumentWorklist(context)\n defer { worklist.deinitialize() }\n worklist.push(arg)\n\n if findOriginsInCallers(&worklist) == NeedInsertMoves.yes {\n // We don't know the origin of the function argument. Therefore we need to do the\n // conservative default which is to move the value to a temporary stack location.\n if let beginAccess = scope {\n // If there is an access, we need to move the destination of the `begin_access`.\n // We should never change the source address of a `begin_access` to a temporary.\n moveToTemporary(scope: beginAccess, mustFixStackNesting: &mustFixStackNesting, context)\n } else {\n moveToTemporary(argument: arg, context)\n }\n }\n\n case .objectIfStackPromoted(let obj):\n // For example:\n // %0 = alloc_ref [stack] $Class\n // %baseAddr = ref_element_addr %0 : $Class, #Class.field\n\n var worklist = ArgumentWorklist(context)\n defer { worklist.deinitialize() }\n\n // If the object is passed as an argument to its function, add those arguments\n // to the worklist.\n let (_, foundStackAlloc) = worklist.push(rootsOf: obj)\n if foundStackAlloc {\n // The object is created by an `alloc_ref [stack]`.\n log("objectIfStackPromoted: \(function.name) -- \(instruction)")\n\n function.setNeedsStackProtection(context)\n }\n // In case the (potentially) stack allocated object is passed via an argument,\n // process the worklist as we do for indirect arguments (see above).\n // For example:\n // bb0(%0: $Class):\n // %baseAddr = ref_element_addr %0 : $Class, #Class.field\n if findOriginsInCallers(&worklist) == NeedInsertMoves.yes,\n let beginAccess = scope {\n // We don't know the origin of the object. Therefore we need to do the\n // conservative default which is to move the value to a temporary stack location.\n moveToTemporary(scope: beginAccess, mustFixStackNesting: &mustFixStackNesting, context)\n }\n\n case .unknown:\n // TODO: better handling of unknown access bases\n break\n }\n }\n\n /// Return value of `findOriginsInCallers()`.\n enum NeedInsertMoves {\n // Not all call sites could be identified, and if moves are enabled (`enableMoveInout`)\n // the original argument should be moved to a temporary.\n case yes\n\n // Either all call sites could be identified, which means that stack protection is done\n // in the callers, or moves are not enabled (`enableMoveInout` is false).\n case no\n }\n\n /// Find all origins of function arguments in `worklist`.\n /// All functions, which allocate such an origin are added to `self.needStackProtection`.\n /// Returns true if all origins could be found and false, if there are unknown origins.\n private mutating func findOriginsInCallers(_ worklist: inout ArgumentWorklist) -> NeedInsertMoves {\n \n guard let moduleContext = moduleContext else {\n // Don't do any inter-procedural analysis when used on function-level.\n return enableMoveInout ? .yes : .no\n }\n \n // Put the resulting functions into a temporary array, because we only add them to\n // `self.needStackProtection` if we don't return false.\n var newFunctions = Stack<Function>(moduleContext)\n defer { newFunctions.deinitialize() }\n\n if !functionUsesComputed {\n functionUses.collect(context: moduleContext)\n functionUsesComputed = true\n }\n\n while let arg = worklist.pop() {\n let f = arg.parentFunction\n let uses = functionUses.getUses(of: f)\n if uses.hasUnknownUses && enableMoveInout {\n return NeedInsertMoves.yes\n }\n \n for useInst in uses {\n guard let fri = useInst as? FunctionRefInst else {\n if enableMoveInout {\n return NeedInsertMoves.yes\n }\n continue\n }\n \n for functionRefUse in fri.uses {\n guard let apply = functionRefUse.instruction as? ApplySite,\n let callerArgOp = apply.operand(forCalleeArgumentIndex: arg.index) else {\n if enableMoveInout {\n return NeedInsertMoves.yes\n }\n continue\n }\n let callerArg = callerArgOp.value\n if callerArg.type.isAddress {\n // It's an indirect argument.\n switch callerArg.accessBase.isStackAllocated {\n case .yes:\n if !callerArg.parentFunction.needsStackProtection {\n log("alloc_stack in caller: \(callerArg.parentFunction.name) -- \(callerArg)")\n newFunctions.push(callerArg.parentFunction)\n }\n case .no:\n break\n case .decidedInCaller(let callerFuncArg):\n if !callerFuncArg.convention.isInout {\n break\n }\n // The argumente is itself passed as an argument to its function.\n // Continue with looking into the callers.\n worklist.push(callerFuncArg)\n case .objectIfStackPromoted(let obj):\n // If the object is passed as an argument to its function,\n // add those arguments to the worklist.\n let (foundUnknownRoots, foundStackAlloc) = worklist.push(rootsOf: obj)\n if foundUnknownRoots && enableMoveInout {\n return NeedInsertMoves.yes\n }\n if foundStackAlloc && !obj.parentFunction.needsStackProtection {\n // The object is created by an `alloc_ref [stack]`.\n log("object in caller: \(obj.parentFunction.name) -- \(obj)")\n newFunctions.push(obj.parentFunction)\n }\n case .unknown:\n if enableMoveInout {\n return NeedInsertMoves.yes\n }\n }\n } else {\n // The argument is an object. If the object is itself passed as an argument\n // to its function, add those arguments to the worklist.\n let (foundUnknownRoots, foundStackAlloc) = worklist.push(rootsOf: callerArg)\n if foundUnknownRoots && enableMoveInout {\n return NeedInsertMoves.yes\n }\n if foundStackAlloc && !callerArg.parentFunction.needsStackProtection {\n // The object is created by an `alloc_ref [stack]`.\n log("object arg in caller: \(callerArg.parentFunction.name) -- \(callerArg)")\n newFunctions.push(callerArg.parentFunction)\n }\n }\n }\n }\n }\n needStackProtection.append(contentsOf: newFunctions)\n return NeedInsertMoves.no\n }\n\n /// Moves the value of an indirect argument to a temporary stack location, if possible.\n private func moveToTemporary(argument: FunctionArgument, _ context: FunctionPassContext) {\n if !argument.convention.isInout {\n // We cannot move from a read-only argument.\n // Also, read-only arguments shouldn't be subject to buffer overflows (because\n // no one should ever write to such an argument).\n return\n }\n\n let function = argument.parentFunction\n let entryBlock = function.entryBlock\n let loc = entryBlock.instructions.first!.location.autoGenerated\n let builder = Builder(atBeginOf: entryBlock, location: loc, context)\n let temporary = builder.createAllocStack(argument.type)\n argument.uses.replaceAll(with: temporary, context)\n\n builder.createCopyAddr(from: argument, to: temporary, takeSource: true, initializeDest: true)\n\n for block in function.blocks {\n let terminator = block.terminator\n if terminator.isFunctionExiting {\n let exitBuilder = Builder(before: terminator, location: terminator.location.autoGenerated, context)\n exitBuilder.createCopyAddr(from: temporary, to: argument, takeSource: true, initializeDest: true)\n exitBuilder.createDeallocStack(temporary)\n }\n }\n log("move addr protection in \(function.name): \(argument)")\n \n function.setNeedsStackProtection(context)\n }\n\n /// Moves the value of a `beginAccess` to a temporary stack location, if possible.\n private func moveToTemporary(scope beginAccess: BeginAccessInst, mustFixStackNesting: inout Bool,\n _ context: FunctionPassContext) {\n if beginAccess.accessKind != .modify {\n // We can only move from a `modify` access.\n // Also, read-only accesses shouldn't be subject to buffer overflows (because\n // no one should ever write to such a storage).\n return\n }\n \n let builder = Builder(after: beginAccess, location: beginAccess.location.autoGenerated, context)\n let temporary = builder.createAllocStack(beginAccess.type)\n\n beginAccess.uses.ignoreUsers(ofType: EndAccessInst.self).replaceAll(with: temporary, context)\n\n for endAccess in beginAccess.endInstructions {\n let endBuilder = Builder(before: endAccess, location: endAccess.location.autoGenerated, context)\n endBuilder.createCopyAddr(from: temporary, to: beginAccess, takeSource: true, initializeDest: true)\n endBuilder.createDeallocStack(temporary)\n }\n\n builder.createCopyAddr(from: beginAccess, to: temporary, takeSource: true, initializeDest: true)\n log("move object protection in \(beginAccess.parentFunction.name): \(beginAccess)")\n\n beginAccess.parentFunction.setNeedsStackProtection(context)\n\n // Access scopes are not necessarily properly nested, which can result in\n // not properly nested stack allocations.\n mustFixStackNesting = true\n }\n}\n\n/// Worklist for inter-procedural analysis of function arguments.\nprivate struct ArgumentWorklist : ValueUseDefWalker {\n var walkUpCache = WalkerCache<SmallProjectionPath>()\n\n // Used in `push(rootsOf:)`\n private var foundStackAlloc = false\n private var foundUnknownRoots = false\n\n // Contains arguments which are already handled and don't need to be put into the worklist again.\n // Note that this cannot be a `ValueSet`, because argument can be from different functions.\n private var handled = Set<FunctionArgument>()\n\n // The actual worklist.\n private var list: Stack<FunctionArgument>\n\n init(_ context: FunctionPassContext) {\n self.list = Stack(context)\n }\n\n mutating func deinitialize() {\n list.deinitialize()\n }\n\n mutating func push(_ arg: FunctionArgument) {\n if handled.insert(arg).0 {\n list.push(arg)\n }\n }\n\n /// Pushes all roots of `object`, which are function arguments, to the worklist.\n /// If the returned `foundUnknownRoots` is true, it means that not all roots of `object` could\n /// be tracked to a function argument.\n /// If the returned `foundStackAlloc` than at least one found root is an `alloc_ref [stack]`.\n mutating func push(rootsOf object: Value) -> (foundUnknownRoots: Bool, foundStackAlloc: Bool) {\n foundStackAlloc = false\n foundUnknownRoots = false\n _ = walkUp(value: object, path: SmallProjectionPath(.anything))\n return (foundUnknownRoots, foundStackAlloc)\n }\n\n mutating func pop() -> FunctionArgument? {\n return list.pop()\n }\n\n // Internal walker function.\n mutating func rootDef(value: Value, path: Path) -> WalkResult {\n switch value {\n case let ar as AllocRefInstBase:\n if ar.canAllocOnStack {\n foundStackAlloc = true\n }\n case let arg as FunctionArgument:\n push(arg)\n default:\n foundUnknownRoots = true\n }\n return .continueWalk\n }\n}\n\nprivate extension AccessBase {\n enum IsStackAllocatedResult {\n case yes\n case no\n case decidedInCaller(FunctionArgument)\n case objectIfStackPromoted(Value)\n case unknown\n }\n\n var isStackAllocated: IsStackAllocatedResult {\n switch self {\n case .stack, .storeBorrow:\n return .yes\n case .box, .global:\n return .no\n case .class(let rea):\n return .objectIfStackPromoted(rea.instance)\n case .tail(let rta):\n return .objectIfStackPromoted(rta.instance)\n case .argument(let arg):\n return .decidedInCaller(arg)\n case .yield, .pointer:\n return .unknown\n case .index, .unidentified:\n // In the rare case of an unidentified access, just ignore it.\n // This should not happen in regular SIL, anyway.\n return .no\n }\n }\n}\n\nprivate extension Instruction {\n /// If the instruction needs stack protection, return the relevant access base and scope.\n var accessBaseToProtect: (AccessBase, scope: BeginAccessInst?)? {\n let baseAddr: Value\n switch self {\n case let atp as AddressToPointerInst:\n if !atp.needsStackProtection {\n return nil\n }\n var hasNoStores = NoStores()\n if hasNoStores.walkDownUses(ofValue: atp, path: SmallProjectionPath()) == .continueWalk {\n return nil\n }\n\n // The result of an `address_to_pointer` may be used in any unsafe way, e.g.\n // passed to a C function.\n baseAddr = atp.address\n case let ia as IndexAddrInst:\n if !ia.needsStackProtection {\n return nil\n }\n var hasNoStores = NoStores()\n if hasNoStores.walkDownUses(ofAddress: ia, path: SmallProjectionPath()) == .continueWalk {\n return nil\n }\n\n // `index_addr` is unsafe if not used for tail-allocated elements (e.g. in Array).\n baseAddr = ia.base\n default:\n return nil\n }\n let (accessPath, scope) = baseAddr.accessPathWithScope\n\n if case .tail = accessPath.base, self is IndexAddrInst {\n // `index_addr` for tail-allocated elements is the usual case (most likely coming from\n // Array code).\n return nil\n }\n return (accessPath.base, scope)\n }\n}\n\n/// Checks if there are no stores to an address or raw pointer.\nprivate struct NoStores : ValueDefUseWalker, AddressDefUseWalker {\n var walkDownCache = WalkerCache<SmallProjectionPath>()\n\n mutating func leafUse(value: Operand, path: SmallProjectionPath) -> WalkResult {\n switch value.instruction {\n case let ptai as PointerToAddressInst:\n return walkDownUses(ofAddress: ptai, path: path)\n case let bi as BuiltinInst:\n switch bi.intrinsicID {\n case .memcpy, .memmove:\n return value.index != 0 ? .continueWalk : .abortWalk\n default:\n return .abortWalk\n }\n default:\n return .abortWalk\n }\n }\n\n mutating func leafUse(address: Operand, path: SmallProjectionPath) -> WalkResult {\n switch address.instruction {\n case is LoadInst:\n return .continueWalk\n case let cai as CopyAddrInst:\n return address == cai.sourceOperand ? .continueWalk : .abortWalk\n default:\n return .abortWalk\n }\n }\n}\n\nprivate extension Function {\n func setNeedsStackProtection(_ context: FunctionPassContext) {\n if !needsStackProtection {\n set(needStackProtection: true, context)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_StackProtection.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_ModulePasses_StackProtection.swift
Swift
21,057
0.95
0.232975
0.271222
awesome-app
473
2024-09-10T06:14:12.445359
MIT
false
9731fe4b73b4dacc6b0d650db7cefd92
//===--- Context.swift - defines the context types ------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\nimport OptimizerBridging\n\n/// The base type of all contexts.\nprotocol Context {\n var _bridged: BridgedPassContext { get }\n}\n\nextension Context {\n var options: Options { Options(_bridged: _bridged) }\n\n var diagnosticEngine: DiagnosticEngine {\n return DiagnosticEngine(bridged: _bridged.getDiagnosticEngine())\n }\n\n // The calleeAnalysis is not specific to a function and therefore can be provided in\n // all contexts.\n var calleeAnalysis: CalleeAnalysis {\n let bridgeCA = _bridged.getCalleeAnalysis()\n return CalleeAnalysis(bridged: bridgeCA)\n }\n\n var hadError: Bool { _bridged.hadError() }\n\n var silStage: SILStage {\n switch _bridged.getSILStage() {\n case .Raw: return .raw\n case .Canonical: return .canonical\n case .Lowered: return .lowered\n default: fatalError("unhandled SILStage case")\n }\n }\n\n var currentModuleContext: ModuleDecl {\n _bridged.getCurrentModuleContext().getAs(ModuleDecl.self)\n }\n\n var moduleIsSerialized: Bool { _bridged.moduleIsSerialized() }\n\n var moduleHasLoweredAddresses: Bool { _bridged.moduleHasLoweredAddresses() }\n\n /// Enable diagnostics requiring WMO (for @noLocks, @noAllocation\n /// annotations, Embedded Swift, and class specialization). SourceKit is the\n /// only consumer that has this disabled today (as it disables WMO\n /// explicitly).\n var enableWMORequiredDiagnostics: Bool {\n _bridged.enableWMORequiredDiagnostics()\n }\n\n func canMakeStaticObjectReadOnly(objectType: Type) -> Bool {\n _bridged.canMakeStaticObjectReadOnly(objectType.bridged)\n }\n\n func lookupDeinit(ofNominal: NominalTypeDecl) -> Function? {\n _bridged.lookUpNominalDeinitFunction(ofNominal.bridged).function\n }\n\n func getBuiltinIntegerType(bitWidth: Int) -> Type { _bridged.getBuiltinIntegerType(bitWidth).type }\n\n func lookupFunction(name: String) -> Function? {\n name._withBridgedStringRef {\n _bridged.lookupFunction($0).function\n }\n }\n\n func lookupWitnessTable(for conformance: Conformance) -> WitnessTable? {\n return _bridged.lookupWitnessTable(conformance.bridged).witnessTable\n }\n\n func lookupVTable(for classDecl: NominalTypeDecl) -> VTable? {\n return _bridged.lookupVTable(classDecl.bridged).vTable\n }\n\n func lookupSpecializedVTable(for classType: Type) -> VTable? {\n return _bridged.lookupSpecializedVTable(classType.bridged).vTable\n }\n\n func getSpecializedConformance(of genericConformance: Conformance,\n for type: AST.`Type`,\n substitutions: SubstitutionMap) -> Conformance\n {\n let c = _bridged.getSpecializedConformance(genericConformance.bridged, type.bridged, substitutions.bridged)\n return Conformance(bridged: c)\n }\n\n func notifyNewFunction(function: Function, derivedFrom: Function) {\n _bridged.addFunctionToPassManagerWorklist(function.bridged, derivedFrom.bridged)\n }\n}\n\n/// A context which allows mutation of a function's SIL.\nprotocol MutatingContext : Context {\n // Called by all instruction mutations, including inserted new instructions.\n var notifyInstructionChanged: (Instruction) -> () { get }\n}\n\nextension MutatingContext {\n func notifyInvalidatedStackNesting() { _bridged.notifyInvalidatedStackNesting() }\n var needFixStackNesting: Bool { _bridged.getNeedFixStackNesting() }\n\n func verifyIsTransforming(function: Function) {\n precondition(_bridged.isTransforming(function.bridged), "pass modifies wrong function")\n }\n\n /// Splits the basic block, which contains `inst`, before `inst` and returns the\n /// new block.\n ///\n /// `inst` and all subsequent instructions are moved to the new block, while all\n /// instructions _before_ `inst` remain in the original block.\n func splitBlock(before inst: Instruction) -> BasicBlock {\n notifyBranchesChanged()\n return _bridged.splitBlockBefore(inst.bridged).block\n }\n\n /// Splits the basic block, which contains `inst`, after `inst` and returns the\n /// new block.\n ///\n /// All subsequent instructions after `inst` are moved to the new block, while `inst` and all\n /// instructions _before_ `inst` remain in the original block.\n func splitBlock(after inst: Instruction) -> BasicBlock {\n notifyBranchesChanged()\n return _bridged.splitBlockAfter(inst.bridged).block\n }\n\n func createBlock(after block: BasicBlock) -> BasicBlock {\n notifyBranchesChanged()\n return _bridged.createBlockAfter(block.bridged).block\n }\n\n func erase(instruction: Instruction) {\n if !instruction.isInStaticInitializer {\n verifyIsTransforming(function: instruction.parentFunction)\n }\n if instruction is FullApplySite {\n notifyCallsChanged()\n }\n if instruction is TermInst {\n notifyBranchesChanged()\n }\n notifyInstructionsChanged()\n\n _bridged.eraseInstruction(instruction.bridged)\n }\n\n func erase(instructionIncludingAllUsers inst: Instruction) {\n if inst.isDeleted {\n return\n }\n for result in inst.results {\n for use in result.uses {\n erase(instructionIncludingAllUsers: use.instruction)\n }\n }\n erase(instruction: inst)\n }\n\n func erase<S: Sequence>(instructions: S) where S.Element: Instruction {\n for inst in instructions {\n erase(instruction: inst)\n }\n }\n\n func erase(instructionIncludingDebugUses inst: Instruction) {\n precondition(inst.results.allSatisfy { $0.uses.ignoreDebugUses.isEmpty })\n erase(instructionIncludingAllUsers: inst)\n }\n\n func erase(block: BasicBlock) {\n _bridged.eraseBlock(block.bridged)\n }\n\n func tryOptimizeApplyOfPartialApply(closure: PartialApplyInst) -> Bool {\n if _bridged.tryOptimizeApplyOfPartialApply(closure.bridged) {\n notifyInstructionsChanged()\n notifyCallsChanged()\n\n for use in closure.callee.uses {\n if use.instruction is FullApplySite {\n notifyInstructionChanged(use.instruction)\n }\n }\n return true\n }\n return false\n }\n\n func tryDeleteDeadClosure(closure: SingleValueInstruction, needKeepArgsAlive: Bool = true) -> Bool {\n if _bridged.tryDeleteDeadClosure(closure.bridged, needKeepArgsAlive) {\n notifyInstructionsChanged()\n return true\n }\n return false\n }\n\n func tryDevirtualize(apply: FullApplySite, isMandatory: Bool) -> ApplySite? {\n let result = _bridged.tryDevirtualizeApply(apply.bridged, isMandatory)\n if let newApply = result.newApply.instruction {\n erase(instruction: apply)\n notifyInstructionsChanged()\n notifyCallsChanged()\n if result.cfgChanged {\n notifyBranchesChanged()\n }\n notifyInstructionChanged(newApply)\n return newApply as! FullApplySite\n }\n return nil\n }\n \n func tryOptimizeKeypath(apply: FullApplySite) -> Bool {\n return _bridged.tryOptimizeKeypath(apply.bridged)\n }\n\n func inlineFunction(apply: FullApplySite, mandatoryInline: Bool) {\n // This is only a best-effort attempt to notify the new cloned instructions as changed.\n // TODO: get a list of cloned instructions from the `inlineFunction`\n let instAfterInling: Instruction?\n switch apply {\n case is ApplyInst:\n instAfterInling = apply.next\n case let beginApply as BeginApplyInst:\n let next = beginApply.next!\n instAfterInling = (next is EndApplyInst ? nil : next)\n case is TryApplyInst:\n instAfterInling = apply.parentBlock.next?.instructions.first\n default:\n instAfterInling = nil\n }\n\n _bridged.inlineFunction(apply.bridged, mandatoryInline)\n\n if let instAfterInling = instAfterInling {\n notifyNewInstructions(from: apply, to: instAfterInling)\n }\n }\n\n func loadFunction(function: Function, loadCalleesRecursively: Bool) -> Bool {\n if function.isDefinition {\n return true\n }\n _bridged.loadFunction(function.bridged, loadCalleesRecursively)\n return function.isDefinition\n }\n\n private func notifyNewInstructions(from: Instruction, to: Instruction) {\n var inst = from\n while inst != to {\n if !inst.isDeleted {\n notifyInstructionChanged(inst)\n }\n if let next = inst.next {\n inst = next\n } else {\n inst = inst.parentBlock.next!.instructions.first!\n }\n }\n }\n\n func getContextSubstitutionMap(for type: Type) -> SubstitutionMap {\n SubstitutionMap(bridged: _bridged.getContextSubstitutionMap(type.bridged))\n }\n\n func notifyInstructionsChanged() {\n _bridged.asNotificationHandler().notifyChanges(.instructionsChanged)\n }\n\n func notifyCallsChanged() {\n _bridged.asNotificationHandler().notifyChanges(.callsChanged)\n }\n\n func notifyBranchesChanged() {\n _bridged.asNotificationHandler().notifyChanges(.branchesChanged)\n }\n\n /// Notifies the pass manager that the optimization result of the current pass depends\n /// on the body (i.e. SIL instructions) of another function than the currently optimized one.\n func notifyDependency(onBodyOf otherFunction: Function) {\n _bridged.notifyDependencyOnBodyOf(otherFunction.bridged)\n }\n}\n\n/// The context which is passed to the run-function of a FunctionPass.\nstruct FunctionPassContext : MutatingContext {\n let _bridged: BridgedPassContext\n\n // A no-op.\n var notifyInstructionChanged: (Instruction) -> () { return { inst in } }\n\n func continueWithNextSubpassRun(for inst: Instruction? = nil) -> Bool {\n return _bridged.continueWithNextSubpassRun(inst.bridged)\n }\n\n func createSimplifyContext(preserveDebugInfo: Bool, notifyInstructionChanged: @escaping (Instruction) -> ()) -> SimplifyContext {\n SimplifyContext(_bridged: _bridged, notifyInstructionChanged: notifyInstructionChanged, preserveDebugInfo: preserveDebugInfo)\n }\n\n var deadEndBlocks: DeadEndBlocksAnalysis {\n let bridgeDEA = _bridged.getDeadEndBlocksAnalysis()\n return DeadEndBlocksAnalysis(bridged: bridgeDEA)\n }\n\n var dominatorTree: DominatorTree {\n let bridgedDT = _bridged.getDomTree()\n return DominatorTree(bridged: bridgedDT)\n }\n\n var postDominatorTree: PostDominatorTree {\n let bridgedPDT = _bridged.getPostDomTree()\n return PostDominatorTree(bridged: bridgedPDT)\n }\n\n var swiftArrayDecl: NominalTypeDecl {\n _bridged.getSwiftArrayDecl().getAs(NominalTypeDecl.self)\n }\n\n func loadFunction(name: StaticString, loadCalleesRecursively: Bool) -> Function? {\n return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in\n let nameStr = BridgedStringRef(data: nameBuffer.baseAddress, count: nameBuffer.count)\n return _bridged.loadFunction(nameStr, loadCalleesRecursively).function\n }\n }\n\n /// Looks up a function in the `Swift` module.\n /// The `name` is the source name of the function and not the mangled name.\n /// Returns nil if no such function or multiple matching functions are found.\n func lookupStdlibFunction(name: StaticString) -> Function? {\n return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in\n let nameStr = BridgedStringRef(data: nameBuffer.baseAddress, count: nameBuffer.count)\n return _bridged.lookupStdlibFunction(nameStr).function\n }\n }\n\n func modifyEffects(in function: Function, _ body: (inout FunctionEffects) -> ()) {\n notifyEffectsChanged()\n function._modifyEffects(body)\n }\n\n fileprivate func notifyEffectsChanged() {\n _bridged.asNotificationHandler().notifyChanges(.effectsChanged)\n }\n\n func eliminateDeadAllocations(in function: Function) -> Bool {\n if _bridged.eliminateDeadAllocations(function.bridged) {\n notifyInstructionsChanged()\n return true\n }\n return false\n }\n\n func specializeClassMethodInst(_ cm: ClassMethodInst) -> Bool {\n if _bridged.specializeClassMethodInst(cm.bridged) {\n notifyInstructionsChanged()\n notifyCallsChanged()\n return true\n }\n return false\n }\n\n func specializeWitnessMethodInst(_ wm: WitnessMethodInst) -> Bool {\n if _bridged.specializeWitnessMethodInst(wm.bridged) {\n notifyInstructionsChanged()\n notifyCallsChanged()\n return true\n }\n return false\n }\n\n func specializeApplies(in function: Function, isMandatory: Bool) -> Bool {\n if _bridged.specializeAppliesInFunction(function.bridged, isMandatory) {\n notifyInstructionsChanged()\n notifyCallsChanged()\n return true\n }\n return false\n }\n\n func mangleOutlinedVariable(from function: Function) -> String {\n return String(taking: _bridged.mangleOutlinedVariable(function.bridged))\n }\n\n func mangle(withClosureArguments closureArgs: [Value], closureArgIndices: [Int], from applySiteCallee: Function) -> String {\n closureArgs.withBridgedValues { bridgedClosureArgsRef in\n closureArgIndices.withBridgedArrayRef{bridgedClosureArgIndicesRef in \n String(taking: _bridged.mangleWithClosureArgs(\n bridgedClosureArgsRef, \n bridgedClosureArgIndicesRef, \n applySiteCallee.bridged\n ))\n }\n }\n }\n\n func createGlobalVariable(name: String, type: Type, linkage: Linkage, isLet: Bool) -> GlobalVariable {\n let gv = name._withBridgedStringRef {\n _bridged.createGlobalVariable($0, type.bridged, linkage.bridged, isLet)\n }\n return gv.globalVar\n }\n\n func createFunctionForClosureSpecialization(from applySiteCallee: Function, withName specializedFunctionName: String, \n withParams specializedParameters: [ParameterInfo], \n withSerialization isSerialized: Bool) -> Function \n {\n return specializedFunctionName._withBridgedStringRef { nameRef in\n let bridgedParamInfos = specializedParameters.map { $0._bridged }\n\n return bridgedParamInfos.withUnsafeBufferPointer { paramBuf in\n _bridged.ClosureSpecializer_createEmptyFunctionWithSpecializedSignature(nameRef, paramBuf.baseAddress, \n paramBuf.count, \n applySiteCallee.bridged, \n isSerialized).function\n }\n }\n }\n\n func buildSpecializedFunction<T>(specializedFunction: Function, buildFn: (Function, FunctionPassContext) -> T) -> T {\n let nestedFunctionPassContext = \n FunctionPassContext(_bridged: _bridged.initializeNestedPassContext(specializedFunction.bridged))\n\n defer { _bridged.deinitializedNestedPassContext() }\n\n return buildFn(specializedFunction, nestedFunctionPassContext)\n }\n\n /// Makes sure that the lifetime of `value` ends at all control flow paths, even in dead-end blocks.\n /// Inserts destroys in dead-end blocks if those are missing.\n func completeLifetime(of value: Value) {\n if _bridged.completeLifetime(value.bridged) {\n notifyInstructionsChanged()\n }\n }\n}\n\nstruct SimplifyContext : MutatingContext {\n let _bridged: BridgedPassContext\n let notifyInstructionChanged: (Instruction) -> ()\n let preserveDebugInfo: Bool\n}\n\nextension Type {\n func getStaticSize(context: SimplifyContext) -> Int? {\n let v = context._bridged.getStaticSize(self.bridged)\n return v == -1 ? nil : v\n }\n \n func getStaticAlignment(context: SimplifyContext) -> Int? {\n let v = context._bridged.getStaticAlignment(self.bridged)\n return v == -1 ? nil : v\n }\n \n func getStaticStride(context: SimplifyContext) -> Int? {\n let v = context._bridged.getStaticStride(self.bridged)\n return v == -1 ? nil : v\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Builder initialization\n//===----------------------------------------------------------------------===//\n\nprivate extension Instruction {\n /// Returns self, unless self is a meta instruction, in which case the next\n /// non-meta instruction is returned. Returns nil if there are no non-meta\n /// instructions in the basic block.\n var nextNonMetaInstruction: Instruction? {\n for inst in InstructionList(first: self) where !(inst is MetaInstruction) {\n return inst\n }\n return nil\n }\n\n /// Returns the next interesting location. As it is impossible to set a\n /// breakpoint on a meta instruction, those are skipped.\n /// However, we don't want to take a location with different inlining\n /// information than this instruction, so in that case, we will return the\n /// location of the meta instruction. If the meta instruction is the only\n /// instruction in the basic block, we also take its location.\n var locationOfNextNonMetaInstruction: Location {\n let location = self.location\n guard !location.isInlined,\n let nextLocation = nextNonMetaInstruction?.location,\n !nextLocation.isInlined else {\n return location\n }\n return nextLocation\n }\n}\n\nextension Builder {\n /// Creates a builder which inserts _before_ `insPnt`, using a custom `location`.\n init(before insPnt: Instruction, location: Location, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: insPnt.parentFunction)\n self.init(insertAt: .before(insPnt), location: location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts before `insPnt`, using `insPnt`'s next\n /// non-meta instruction's location.\n /// This function should be used when moving code to an unknown insert point,\n /// when we want to inherit the location of the closest non-meta instruction.\n /// For replacing an existing meta instruction with another, use\n /// ``Builder.init(replacing:_:)``.\n init(before insPnt: Instruction, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: insPnt.parentFunction)\n self.init(insertAt: .before(insPnt),\n location: insPnt.locationOfNextNonMetaInstruction,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts _before_ `insPnt`, using the exact location of `insPnt`,\n /// for the purpose of replacing that meta instruction with an equivalent instruction.\n /// This function does not delete `insPnt`.\n init(replacing insPnt: MetaInstruction, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: insPnt.parentFunction)\n self.init(insertAt: .before(insPnt), location: insPnt.location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts _after_ `insPnt`, using a custom `location`.\n ///\n /// TODO: this is usually incorrect for terminator instructions. Instead use\n /// `Builder.insert(after:location:_:insertFunc)` from OptUtils.swift. Rename this to afterNonTerminator.\n init(after insPnt: Instruction, location: Location, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: insPnt.parentFunction)\n guard let nextInst = insPnt.next else {\n fatalError("cannot insert an instruction after a block terminator.")\n }\n self.init(insertAt: .before(nextInst), location: location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts _after_ `insPnt`, using `insPnt`'s next\n /// non-meta instruction's location.\n ///\n /// TODO: this is incorrect for terminator instructions. Instead use `Builder.insert(after:location:_:insertFunc)`\n /// from OptUtils.swift. Rename this to afterNonTerminator.\n init(after insPnt: Instruction, _ context: some MutatingContext) {\n self.init(after: insPnt, location: insPnt.locationOfNextNonMetaInstruction, context)\n }\n\n /// Creates a builder which inserts at the end of `block`, using a custom `location`.\n init(atEndOf block: BasicBlock, location: Location, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: block.parentFunction)\n self.init(insertAt: .atEndOf(block), location: location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts at the begin of `block`, using a custom `location`.\n init(atBeginOf block: BasicBlock, location: Location, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: block.parentFunction)\n let firstInst = block.instructions.first!\n self.init(insertAt: .before(firstInst), location: location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts at the begin of `block`, using the location of the first\n /// non-meta instruction of `block`.\n init(atBeginOf block: BasicBlock, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: block.parentFunction)\n let firstInst = block.instructions.first!\n self.init(insertAt: .before(firstInst),\n location: firstInst.locationOfNextNonMetaInstruction,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n /// Creates a builder which inserts instructions into an empty function, using the location of the function itself.\n init(atStartOf function: Function, _ context: some MutatingContext) {\n context.verifyIsTransforming(function: function)\n self.init(insertAt: .atStartOf(function), location: function.location,\n context.notifyInstructionChanged, context._bridged.asNotificationHandler())\n }\n\n init(staticInitializerOf global: GlobalVariable, _ context: some MutatingContext) {\n self.init(insertAt: .staticInitializer(global),\n location: Location.artificialUnreachableLocation,\n { _ in }, context._bridged.asNotificationHandler())\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Modifying the SIL\n//===----------------------------------------------------------------------===//\n\nextension Undef {\n static func get(type: Type, _ context: some MutatingContext) -> Undef {\n context._bridged.getSILUndef(type.bridged).value as! Undef\n }\n}\n\nextension BasicBlock {\n func addArgument(type: Type, ownership: Ownership, _ context: some MutatingContext) -> Argument {\n context.notifyInstructionsChanged()\n return bridged.addBlockArgument(type.bridged, ownership._bridged).argument\n }\n \n func addFunctionArgument(type: Type, _ context: some MutatingContext) -> FunctionArgument {\n context.notifyInstructionsChanged()\n return bridged.addFunctionArgument(type.bridged).argument as! FunctionArgument\n }\n\n func eraseArgument(at index: Int, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.eraseArgument(index)\n }\n\n func moveAllInstructions(toBeginOf otherBlock: BasicBlock, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n context.notifyBranchesChanged()\n bridged.moveAllInstructionsToBegin(otherBlock.bridged)\n }\n\n func moveAllInstructions(toEndOf otherBlock: BasicBlock, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n context.notifyBranchesChanged()\n bridged.moveAllInstructionsToEnd(otherBlock.bridged)\n }\n\n func eraseAllArguments(_ context: some MutatingContext) {\n // Arguments are stored in an array. We need to erase in reverse order to avoid quadratic complexity.\n for argIdx in (0 ..< arguments.count).reversed() {\n eraseArgument(at: argIdx, context)\n }\n }\n\n func moveAllArguments(to otherBlock: BasicBlock, _ context: some MutatingContext) {\n bridged.moveArgumentsTo(otherBlock.bridged)\n }\n}\n\nextension Argument {\n func set(reborrow: Bool, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.setReborrow(reborrow)\n }\n}\n\nextension AllocRefInstBase {\n func setIsStackAllocatable(_ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.AllocRefInstBase_setIsStackAllocatable()\n context.notifyInstructionChanged(self)\n }\n}\n\nextension Sequence where Element == Operand {\n func replaceAll(with replacement: Value, _ context: some MutatingContext) {\n for use in self {\n use.set(to: replacement, context)\n }\n }\n}\n\nextension Operand {\n func set(to value: Value, _ context: some MutatingContext) {\n instruction.setOperand(at: index, to: value, context)\n }\n\n func changeOwnership(from: Ownership, to: Ownership, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.changeOwnership(from._bridged, to._bridged)\n context.notifyInstructionChanged(instruction)\n }\n}\n\nextension Instruction {\n func setOperand(at index : Int, to value: Value, _ context: some MutatingContext) {\n if let apply = self as? FullApplySite, apply.isCallee(operand: operands[index]) {\n context.notifyCallsChanged()\n }\n context.notifyInstructionsChanged()\n bridged.setOperand(index, value.bridged)\n context.notifyInstructionChanged(self)\n }\n\n func move(before otherInstruction: Instruction, _ context: some MutatingContext) {\n BridgedPassContext.moveInstructionBefore(bridged, otherInstruction.bridged)\n context.notifyInstructionsChanged()\n }\n}\n\nextension BuiltinInst {\n func constantFold(_ context: some MutatingContext) -> Value? {\n context._bridged.constantFoldBuiltin(bridged).value\n }\n}\n\nextension RefCountingInst {\n func setAtomicity(isAtomic: Bool, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.RefCountingInst_setIsAtomic(isAtomic)\n context.notifyInstructionChanged(self)\n }\n}\n\nextension AllocRefInst {\n func setIsBare(_ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.AllocRefInst_setIsBare()\n context.notifyInstructionChanged(self)\n }\n}\n\nextension RefElementAddrInst {\n func set(isImmutable: Bool, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.RefElementAddrInst_setImmutable(isImmutable)\n context.notifyInstructionChanged(self)\n }\n}\n\nextension GlobalAddrInst {\n func clearToken(_ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.GlobalAddrInst_clearToken()\n context.notifyInstructionChanged(self)\n }\n}\n\nextension GlobalValueInst {\n func setIsBare(_ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.GlobalValueInst_setIsBare()\n context.notifyInstructionChanged(self)\n }\n}\n\nextension LoadInst {\n func set(ownership: LoadInst.LoadOwnership, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.LoadInst_setOwnership(ownership.rawValue)\n context.notifyInstructionChanged(self)\n }\n}\n\nextension PointerToAddressInst {\n func set(alignment: Int?, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.PointerToAddressInst_setAlignment(UInt64(alignment ?? 0))\n context.notifyInstructionChanged(self)\n }\n}\n\nextension TermInst {\n func replaceBranchTarget(from fromBlock: BasicBlock, to toBlock: BasicBlock, _ context: some MutatingContext) {\n context.notifyBranchesChanged()\n bridged.TermInst_replaceBranchTarget(fromBlock.bridged, toBlock.bridged)\n }\n}\n\nextension ForwardingInstruction {\n func setForwardingOwnership(to ownership: Ownership, _ context: some MutatingContext) {\n context.notifyInstructionsChanged()\n bridged.ForwardingInst_setForwardingOwnership(ownership._bridged)\n }\n}\n\nextension Function {\n func set(needStackProtection: Bool, _ context: FunctionPassContext) {\n context.notifyEffectsChanged()\n bridged.setNeedStackProtection(needStackProtection)\n }\n\n func set(thunkKind: ThunkKind, _ context: FunctionPassContext) {\n context.notifyEffectsChanged()\n switch thunkKind {\n case .noThunk: bridged.setThunk(.IsNotThunk)\n case .thunk: bridged.setThunk(.IsThunk)\n case .reabstractionThunk: bridged.setThunk(.IsReabstractionThunk)\n case .signatureOptimizedThunk: bridged.setThunk(.IsSignatureOptimizedThunk)\n }\n }\n\n func set(isPerformanceConstraint: Bool, _ context: FunctionPassContext) {\n context.notifyEffectsChanged()\n bridged.setIsPerformanceConstraint(isPerformanceConstraint)\n }\n\n func fixStackNesting(_ context: FunctionPassContext) {\n context._bridged.fixStackNesting(bridged)\n }\n\n func appendNewBlock(_ context: FunctionPassContext) -> BasicBlock {\n context.notifyBranchesChanged()\n return context._bridged.appendBlock(bridged).block\n }\n}\n\nextension DeclRef {\n func calleesAreStaticallyKnowable(_ context: some Context) -> Bool {\n context._bridged.calleesAreStaticallyKnowable(bridged)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Context.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Context.swift
Swift
29,044
0.95
0.11677
0.118421
python-kit
480
2024-05-25T21:28:31.714877
MIT
false
2063834525092a0dc66551d3bc7b404c
//===--- ModulePassContext.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\nimport OptimizerBridging\n\n/// The context which is passed to a `ModulePass`'s run-function.\n///\n/// It provides access to all functions, v-tables and witness tables of a module,\n/// but it doesn't provide any APIs to modify functions.\n/// In order to modify a function, a module pass must use `transform(function:)`.\nstruct ModulePassContext : Context, CustomStringConvertible {\n let _bridged: BridgedPassContext\n\n var description: String {\n return String(taking: _bridged.getModuleDescription())\n }\n\n struct FunctionList : CollectionLikeSequence, IteratorProtocol {\n private var currentFunction: Function?\n \n fileprivate init(first: Function?) { currentFunction = first }\n\n mutating func next() -> Function? {\n if let f = currentFunction {\n currentFunction = BridgedPassContext.getNextFunctionInModule(f.bridged).function\n return f\n }\n return nil\n }\n }\n\n struct GlobalVariableList : CollectionLikeSequence, IteratorProtocol {\n private var currentGlobal: GlobalVariable?\n\n fileprivate init(first: GlobalVariable?) { currentGlobal = first }\n\n mutating func next() -> GlobalVariable? {\n if let g = currentGlobal {\n currentGlobal = BridgedPassContext.getNextGlobalInModule(g.bridged).globalVar\n return g\n }\n return nil\n }\n }\n\n struct VTableArray : BridgedRandomAccessCollection {\n fileprivate let bridgedCtxt: BridgedPassContext\n\n var startIndex: Int { return 0 }\n var endIndex: Int { return bridgedCtxt.getNumVTables() }\n\n subscript(_ index: Int) -> VTable {\n assert(index >= startIndex && index < endIndex)\n return VTable(bridged: bridgedCtxt.getVTable(index))\n }\n }\n\n struct WitnessTableList : CollectionLikeSequence, IteratorProtocol {\n private var currentTable: WitnessTable?\n \n fileprivate init(first: WitnessTable?) { currentTable = first }\n\n mutating func next() -> WitnessTable? {\n if let t = currentTable {\n currentTable = BridgedPassContext.getNextWitnessTableInModule(t.bridged).witnessTable\n return t\n }\n return nil\n }\n }\n\n struct DefaultWitnessTableList : CollectionLikeSequence, IteratorProtocol {\n private var currentTable: DefaultWitnessTable?\n \n fileprivate init(first: DefaultWitnessTable?) { currentTable = first }\n\n mutating func next() -> DefaultWitnessTable? {\n if let t = currentTable {\n currentTable = BridgedPassContext.getNextDefaultWitnessTableInModule(t.bridged).defaultWitnessTable\n return t\n }\n return nil\n }\n }\n\n var functions: FunctionList {\n FunctionList(first: _bridged.getFirstFunctionInModule().function)\n }\n \n var globalVariables: GlobalVariableList {\n GlobalVariableList(first: _bridged.getFirstGlobalInModule().globalVar)\n }\n\n var vTables: VTableArray { VTableArray(bridgedCtxt: _bridged) }\n \n var witnessTables: WitnessTableList {\n WitnessTableList(first: _bridged.getFirstWitnessTableInModule().witnessTable)\n }\n\n var defaultWitnessTables: DefaultWitnessTableList {\n DefaultWitnessTableList(first: _bridged.getFirstDefaultWitnessTableInModule().defaultWitnessTable)\n }\n\n /// Run a closure with a `PassContext` for a function, which allows to modify that function.\n ///\n /// Only a single `transform` can be alive at the same time, i.e. it's not allowed to nest\n /// calls to `transform`.\n func transform(function: Function, _ runOnFunction: (FunctionPassContext) -> ()) {\n _bridged.beginTransformFunction(function.bridged)\n runOnFunction(FunctionPassContext(_bridged: _bridged))\n _bridged.endTransformFunction();\n }\n\n func loadFunction(function: Function, loadCalleesRecursively: Bool) -> Bool {\n if function.isDefinition {\n return true\n }\n _bridged.loadFunction(function.bridged, loadCalleesRecursively)\n return function.isDefinition\n }\n\n func specialize(function: Function, for substitutions: SubstitutionMap) -> Function? {\n return _bridged.specializeFunction(function.bridged, substitutions.bridged).function\n }\n\n enum DeserializationMode {\n case allFunctions\n case onlySharedFunctions\n }\n\n func deserializeAllCallees(of function: Function, mode: DeserializationMode) {\n _bridged.deserializeAllCallees(function.bridged, mode == .allFunctions ? true : false)\n }\n\n @discardableResult\n func createSpecializedWitnessTable(entries: [WitnessTable.Entry],\n conformance: Conformance,\n linkage: Linkage,\n serialized: Bool) -> WitnessTable\n {\n let bridgedEntries = entries.map { $0.bridged }\n let bridgedWitnessTable = bridgedEntries.withBridgedArrayRef {\n _bridged.createSpecializedWitnessTable(linkage.bridged, serialized, conformance.bridged, $0)\n }\n return WitnessTable(bridged: bridgedWitnessTable)\n }\n\n @discardableResult\n func createSpecializedVTable(entries: [VTable.Entry],\n for classType: Type,\n isSerialized: Bool) -> VTable\n {\n let bridgedEntries = entries.map { $0.bridged }\n let bridgedVTable = bridgedEntries.withBridgedArrayRef {\n _bridged.createSpecializedVTable(classType.bridged, isSerialized, $0)\n }\n return VTable(bridged: bridgedVTable)\n }\n\n func replaceVTableEntries(of vTable: VTable, with entries: [VTable.Entry]) {\n let bridgedEntries = entries.map { $0.bridged }\n bridgedEntries.withBridgedArrayRef {\n vTable.bridged.replaceEntries($0)\n }\n notifyFunctionTablesChanged()\n }\n\n func createEmptyFunction(\n name: String,\n parameters: [ParameterInfo],\n hasSelfParameter: Bool,\n fromOriginal originalFunction: Function\n ) -> Function {\n return name._withBridgedStringRef { nameRef in\n let bridgedParamInfos = parameters.map { $0._bridged }\n return bridgedParamInfos.withUnsafeBufferPointer { paramBuf in\n _bridged.createEmptyFunction(nameRef, paramBuf.baseAddress, paramBuf.count,\n hasSelfParameter, originalFunction.bridged).function\n }\n }\n }\n\n func moveFunctionBody(from sourceFunc: Function, to destFunc: Function) {\n precondition(!destFunc.isDefinition, "cannot move body to non-empty function")\n _bridged.moveFunctionBody(sourceFunc.bridged, destFunc.bridged)\n }\n\n func mangleAsyncRemoved(from function: Function) -> String {\n return String(taking: _bridged.mangleAsyncRemoved(function.bridged))\n }\n\n func mangle(withDeadArguments: [Int], from function: Function) -> String {\n withDeadArguments.withUnsafeBufferPointer { bufPtr in\n bufPtr.withMemoryRebound(to: Int.self) { valPtr in\n String(taking: _bridged.mangleWithDeadArgs(valPtr.baseAddress,\n withDeadArguments.count,\n function.bridged))\n }\n }\n }\n\n func notifyFunctionTablesChanged() {\n _bridged.asNotificationHandler().notifyChanges(.functionTablesChanged)\n }\n}\n\nextension GlobalVariable {\n func setIsLet(to value: Bool, _ context: ModulePassContext) {\n bridged.setLet(value)\n }\n}\n\nextension Function {\n func set(linkage: Linkage, _ context: ModulePassContext) {\n bridged.setLinkage(linkage.bridged)\n }\n\n func set(isSerialized: Bool, _ context: ModulePassContext) {\n bridged.setIsSerialized(isSerialized)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_ModulePassContext.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_ModulePassContext.swift
Swift
7,888
0.95
0.146552
0.103627
awesome-app
406
2024-10-24T16:16:55.804825
Apache-2.0
false
e274cd107ec3c4a60c877866152c8fe2
//===--- Options.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport OptimizerBridging\n\nstruct Options {\n let _bridged: BridgedPassContext\n\n var enableStackProtection: Bool {\n _bridged.enableStackProtection()\n }\n\n var useAggressiveReg2MemForCodeSize : Bool {\n _bridged.useAggressiveReg2MemForCodeSize()\n }\n\n var enableMoveInoutStackProtection: Bool {\n _bridged.enableMoveInoutStackProtection()\n }\n\n func enableSimplification(for inst: Instruction) -> Bool {\n _bridged.enableSimplificationFor(inst.bridged)\n }\n\n func enableAddressDependencies() -> Bool {\n _bridged.enableAddressDependencies()\n }\n\n var noAllocations: Bool {\n _bridged.noAllocations()\n }\n\n var enableEmbeddedSwift: Bool {\n hasFeature(.Embedded)\n }\n\n var enableMergeableTraps: Bool {\n _bridged.enableMergeableTraps()\n }\n\n func hasFeature(_ feature: BridgedFeature) -> Bool {\n _bridged.hasFeature(feature)\n }\n\n // The values for the assert_configuration call are:\n // 0: Debug\n // 1: Release\n // 2: Fast / Unchecked\n enum AssertConfiguration {\n case debug\n case release\n case unchecked\n case unknown\n\n var integerValue: Int {\n switch self {\n case .debug: return 0\n case .release: return 1\n case .unchecked: return 2\n case .unknown: fatalError()\n }\n }\n }\n\n var assertConfiguration: AssertConfiguration {\n switch _bridged.getAssertConfiguration() {\n case .Debug: return .debug\n case .Release: return .release\n case .Unchecked: return .unchecked\n default: return .unknown\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Options.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Options.swift
Swift
2,102
0.95
0.072289
0.217391
vue-tools
463
2024-05-03T21:02:30.131884
BSD-3-Clause
false
14edb7aefe5928d5aae377b6db2029aa
//===--- Passes.swift ---- instruction and function passes ----------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport SIL\nimport OptimizerBridging\n\nstruct FunctionPass {\n\n let name: String\n let runFunction: (Function, FunctionPassContext) -> ()\n\n init(name: String, _ runFunction: @escaping (Function, FunctionPassContext) -> ()) {\n self.name = name\n self.runFunction = runFunction\n }\n\n func run(_ bridgedCtxt: BridgedFunctionPassCtxt) {\n let function = bridgedCtxt.function.function\n let context = FunctionPassContext(_bridged: bridgedCtxt.passContext)\n runFunction(function, context)\n }\n}\n\nstruct ModulePass {\n\n let name: String\n let runFunction: (ModulePassContext) -> ()\n\n init(name: String, _ runFunction: @escaping (ModulePassContext) -> ()) {\n self.name = name\n self.runFunction = runFunction\n }\n\n func run(_ bridgedCtxt: BridgedPassContext) {\n let context = ModulePassContext(_bridged: bridgedCtxt)\n runFunction(context)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Passes.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_Passes.swift
Swift
1,381
0.95
0.152174
0.289474
awesome-app
608
2024-01-08T19:11:28.411148
Apache-2.0
false
5f105e0c0fee229ef306c96377a629af
//===--- PassRegistration.swift - Register optimization passes -------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\nimport OptimizerBridging\n\n@_cdecl("initializeSwiftModules")\npublic func initializeSwiftModules() {\n registerAST()\n registerSILClasses()\n registerSwiftAnalyses()\n registerUtilities()\n registerSwiftPasses()\n registerOptimizerTests()\n}\n\nprivate func registerPass(\n _ pass: ModulePass,\n _ runFn: @escaping (@convention(c) (BridgedPassContext) -> ())) {\n pass.name._withBridgedStringRef { nameStr in\n SILPassManager_registerModulePass(nameStr, runFn)\n }\n}\n\nprivate func registerPass(\n _ pass: FunctionPass,\n _ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) {\n pass.name._withBridgedStringRef { nameStr in\n SILPassManager_registerFunctionPass(nameStr, runFn)\n }\n}\n\nprotocol SILCombineSimplifiable : Instruction {\n func simplify(_ context: SimplifyContext)\n}\n\nprivate func run<InstType: SILCombineSimplifiable>(_ instType: InstType.Type,\n _ bridgedCtxt: BridgedInstructionPassCtxt) {\n let inst = bridgedCtxt.instruction.getAs(instType)\n let context = SimplifyContext(_bridged: bridgedCtxt.passContext,\n notifyInstructionChanged: {inst in},\n preserveDebugInfo: false)\n inst.simplify(context)\n}\n\nprivate func registerForSILCombine<InstType: SILCombineSimplifiable>(\n _ instType: InstType.Type,\n _ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) {\n "\(instType)"._withBridgedStringRef { instClassStr in\n SILCombine_registerInstructionPass(instClassStr, runFn)\n }\n}\n\nprivate func registerSwiftPasses() {\n // Module passes\n registerPass(mandatoryPerformanceOptimizations, { mandatoryPerformanceOptimizations.run($0) })\n registerPass(diagnoseUnknownConstValues, { diagnoseUnknownConstValues.run($0)})\n registerPass(readOnlyGlobalVariablesPass, { readOnlyGlobalVariablesPass.run($0) })\n registerPass(stackProtection, { stackProtection.run($0) })\n registerPass(embeddedSwiftDiagnostics, { embeddedSwiftDiagnostics.run($0) })\n\n // Function passes\n registerPass(asyncDemotion, { asyncDemotion.run($0) })\n registerPass(booleanLiteralFolding, { booleanLiteralFolding.run($0) })\n registerPass(letPropertyLowering, { letPropertyLowering.run($0) })\n registerPass(mergeCondFailsPass, { mergeCondFailsPass.run($0) })\n registerPass(computeEscapeEffects, { computeEscapeEffects.run($0) })\n registerPass(computeSideEffects, { computeSideEffects.run($0) })\n registerPass(diagnoseInfiniteRecursion, { diagnoseInfiniteRecursion.run($0) })\n registerPass(destroyHoisting, { destroyHoisting.run($0) })\n registerPass(initializeStaticGlobalsPass, { initializeStaticGlobalsPass.run($0) })\n registerPass(objCBridgingOptimization, { objCBridgingOptimization.run($0) })\n registerPass(objectOutliner, { objectOutliner.run($0) })\n registerPass(stackPromotion, { stackPromotion.run($0) })\n registerPass(functionStackProtection, { functionStackProtection.run($0) })\n registerPass(assumeSingleThreadedPass, { assumeSingleThreadedPass.run($0) })\n registerPass(releaseDevirtualizerPass, { releaseDevirtualizerPass.run($0) })\n registerPass(simplificationPass, { simplificationPass.run($0) })\n registerPass(ononeSimplificationPass, { ononeSimplificationPass.run($0) })\n registerPass(lateOnoneSimplificationPass, { lateOnoneSimplificationPass.run($0) })\n registerPass(cleanupDebugStepsPass, { cleanupDebugStepsPass.run($0) })\n registerPass(namedReturnValueOptimization, { namedReturnValueOptimization.run($0) })\n registerPass(stripObjectHeadersPass, { stripObjectHeadersPass.run($0) })\n registerPass(deadStoreElimination, { deadStoreElimination.run($0) })\n registerPass(redundantLoadElimination, { redundantLoadElimination.run($0) })\n registerPass(mandatoryRedundantLoadElimination, { mandatoryRedundantLoadElimination.run($0) })\n registerPass(earlyRedundantLoadElimination, { earlyRedundantLoadElimination.run($0) })\n registerPass(deinitDevirtualizer, { deinitDevirtualizer.run($0) })\n registerPass(lifetimeDependenceDiagnosticsPass, { lifetimeDependenceDiagnosticsPass.run($0) })\n registerPass(lifetimeDependenceInsertionPass, { lifetimeDependenceInsertionPass.run($0) })\n registerPass(lifetimeDependenceScopeFixupPass, { lifetimeDependenceScopeFixupPass.run($0) })\n registerPass(copyToBorrowOptimization, { copyToBorrowOptimization.run($0) })\n registerPass(generalClosureSpecialization, { generalClosureSpecialization.run($0) })\n registerPass(autodiffClosureSpecialization, { autodiffClosureSpecialization.run($0) })\n\n // Instruction passes\n registerForSILCombine(BeginBorrowInst.self, { run(BeginBorrowInst.self, $0) })\n registerForSILCombine(BeginCOWMutationInst.self, { run(BeginCOWMutationInst.self, $0) })\n registerForSILCombine(FixLifetimeInst.self, { run(FixLifetimeInst.self, $0) })\n registerForSILCombine(GlobalValueInst.self, { run(GlobalValueInst.self, $0) })\n registerForSILCombine(StrongRetainInst.self, { run(StrongRetainInst.self, $0) })\n registerForSILCombine(StrongReleaseInst.self, { run(StrongReleaseInst.self, $0) })\n registerForSILCombine(RetainValueInst.self, { run(RetainValueInst.self, $0) })\n registerForSILCombine(ReleaseValueInst.self, { run(ReleaseValueInst.self, $0) })\n registerForSILCombine(LoadInst.self, { run(LoadInst.self, $0) })\n registerForSILCombine(LoadBorrowInst.self, { run(LoadBorrowInst.self, $0) })\n registerForSILCombine(CopyValueInst.self, { run(CopyValueInst.self, $0) })\n registerForSILCombine(CopyBlockInst.self, { run(CopyBlockInst.self, $0) })\n registerForSILCombine(DestroyValueInst.self, { run(DestroyValueInst.self, $0) })\n registerForSILCombine(DestructureStructInst.self, { run(DestructureStructInst.self, $0) })\n registerForSILCombine(DestructureTupleInst.self, { run(DestructureTupleInst.self, $0) })\n registerForSILCombine(TypeValueInst.self, { run(TypeValueInst.self, $0) })\n registerForSILCombine(ClassifyBridgeObjectInst.self, { run(ClassifyBridgeObjectInst.self, $0) })\n registerForSILCombine(PointerToAddressInst.self, { run(PointerToAddressInst.self, $0) })\n registerForSILCombine(UncheckedEnumDataInst.self, { run(UncheckedEnumDataInst.self, $0) })\n registerForSILCombine(WitnessMethodInst.self, { run(WitnessMethodInst.self, $0) })\n registerForSILCombine(UnconditionalCheckedCastInst.self, { run(UnconditionalCheckedCastInst.self, $0) })\n registerForSILCombine(AllocStackInst.self, { run(AllocStackInst.self, $0) })\n registerForSILCombine(ApplyInst.self, { run(ApplyInst.self, $0) })\n registerForSILCombine(TryApplyInst.self, { run(TryApplyInst.self, $0) })\n\n // Test passes\n registerPass(aliasInfoDumper, { aliasInfoDumper.run($0) })\n registerPass(functionUsesDumper, { functionUsesDumper.run($0) })\n registerPass(silPrinterPass, { silPrinterPass.run($0) })\n registerPass(escapeInfoDumper, { escapeInfoDumper.run($0) })\n registerPass(addressEscapeInfoDumper, { addressEscapeInfoDumper.run($0) })\n registerPass(accessDumper, { accessDumper.run($0) })\n registerPass(deadEndBlockDumper, { deadEndBlockDumper.run($0) })\n registerPass(memBehaviorDumper, { memBehaviorDumper.run($0) })\n registerPass(rangeDumper, { rangeDumper.run($0) })\n registerPass(runUnitTests, { runUnitTests.run($0) })\n registerPass(testInstructionIteration, { testInstructionIteration.run($0) })\n registerPass(updateBorrowedFromPass, { updateBorrowedFromPass.run($0) })\n}\n\nprivate func registerSwiftAnalyses() {\n AliasAnalysis.register()\n CalleeAnalysis.register()\n}\n\nprivate func registerUtilities() {\n registerVerifier()\n registerPhiUpdater()\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_PassRegistration.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_PassManager_PassRegistration.swift
Swift
8,170
0.95
0.012903
0.105634
vue-tools
533
2024-04-04T18:40:14.862382
Apache-2.0
false
371d5c283d4af7ef80fd34f04afe3096
//===--- AddressUtils.swift - Utilities for handling SIL addresses -------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(_ message: @autoclosure () -> String) {\n if verbose {\n print("### \(message())")\n }\n}\n\n/// Classify address uses. This can be used by def-use walkers to\n/// ensure complete handling of all legal SIL patterns.\n///\n/// TODO: Integrate this with SIL verification to ensure completeness.\n///\n/// TODO: Convert AddressDefUseWalker to use AddressUseVisitor after\n/// checking that the additional instructions are handled correctly by\n/// escape analysis.\n///\n/// TODO: Verify that pointerEscape is only called for live ranges in which\n/// `findPointerEscape()` returns true.\nprotocol AddressUseVisitor {\n var context: Context { get }\n\n /// An address projection produces a single address result and does not\n /// escape its address operand in any other way.\n mutating func projectedAddressUse(of operand: Operand, into value: Value)\n -> WalkResult\n\n /// An access scope: begin_access, begin_apply, load_borrow.\n mutating func scopedAddressUse(of operand: Operand) -> WalkResult\n\n /// end_access, end_apply, abort_apply, end_borrow.\n mutating func scopeEndingAddressUse(of operand: Operand) -> WalkResult\n\n /// An address leaf use propagates neither the address bits, nor the\n /// in-memory value beyond the instruction.\n ///\n /// StoringInstructions are leaf uses.\n mutating func leafAddressUse(of operand: Operand) -> WalkResult\n\n /// An address used by an apply.\n mutating func appliedAddressUse(of operand: Operand, by apply: FullApplySite)\n -> WalkResult\n\n /// A loaded address use propagates the value at the address.\n mutating func loadedAddressUse(of operand: Operand, intoValue value: Value)\n -> WalkResult\n\n /// A loaded address use propagates the value at the address to the\n /// destination address operand.\n mutating func loadedAddressUse(of operand: Operand, intoAddress address: Operand)\n -> WalkResult\n\n /// Yielding an address may modify the value at the yield, but not past the yield. The yielded value may escape, but\n /// only if its type is escapable.\n mutating func yieldedAddressUse(of operand: Operand) -> WalkResult\n\n /// A forwarded `value` whose ownership depends on the in-memory value at the address `operand`.\n /// `%value` may be an address type, but only uses of this address value are dependent.\n /// e.g. `%value = mark_dependence %_ on %operand`\n mutating func dependentAddressUse(of operand: Operand, dependentValue value: Value) -> WalkResult\n\n /// A dependent `address` whose lifetime depends on the in-memory value at `address`.\n /// e.g. `mark_dependence_addr %address on %operand`\n mutating func dependentAddressUse(of operand: Operand, dependentAddress address: Value) -> WalkResult\n\n /// A pointer escape may propagate the address beyond the current instruction.\n mutating func escapingAddressUse(of operand: Operand) -> WalkResult\n\n /// A unknown address use. This should never be called in valid SIL.\n mutating func unknownAddressUse(of operand: Operand) -> WalkResult\n}\n\nextension AddressUseVisitor {\n /// Classify an address-type operand, dispatching to one of the\n /// protocol methods above.\n mutating func classifyAddress(operand: Operand) -> WalkResult {\n switch operand.instruction {\n case is BeginAccessInst, is LoadBorrowInst, is StoreBorrowInst:\n return scopedAddressUse(of: operand)\n\n case is EndAccessInst, is EndApplyInst, is AbortApplyInst, is EndBorrowInst:\n return scopeEndingAddressUse(of: operand)\n\n case is MarkDependenceInstruction:\n return classifyMarkDependence(operand: operand)\n\n case let pai as PartialApplyInst where !pai.mayEscape:\n return dependentAddressUse(of: operand, dependentValue: pai)\n\n case let pai as PartialApplyInst where pai.mayEscape:\n return escapingAddressUse(of: operand)\n\n case is ThrowInst, is AddressToPointerInst:\n return escapingAddressUse(of: operand)\n\n case is StructElementAddrInst, is TupleElementAddrInst,\n is IndexAddrInst, is TailAddrInst, is TuplePackElementAddrInst, \n is InitEnumDataAddrInst, is UncheckedTakeEnumDataAddrInst,\n is InitExistentialAddrInst, is OpenExistentialAddrInst,\n is ProjectBlockStorageInst, is UncheckedAddrCastInst,\n is MarkUninitializedInst, is DropDeinitInst,\n is CopyableToMoveOnlyWrapperAddrInst,\n is MoveOnlyWrapperToCopyableAddrInst,\n is MarkUnresolvedNonCopyableValueInst:\n let svi = operand.instruction as! SingleValueInstruction\n return projectedAddressUse(of: operand, into: svi)\n\n case let apply as FullApplySite:\n return appliedAddressUse(of: operand, by: apply)\n\n case is SwitchEnumAddrInst, is CheckedCastAddrBranchInst,\n is SelectEnumAddrInst, is InjectEnumAddrInst,\n is StoreInst, is StoreUnownedInst, is StoreWeakInst,\n is AssignInst, is AssignByWrapperInst, is AssignOrInitInst,\n is TupleAddrConstructorInst, is InitBlockStorageHeaderInst,\n is RetainValueAddrInst, is ReleaseValueAddrInst,\n is DestroyAddrInst, is DeallocStackInst, \n is DeinitExistentialAddrInst,\n is IsUniqueInst, is MarkFunctionEscapeInst,\n is PackElementSetInst:\n return leafAddressUse(of: operand)\n\n case is LoadInst, is LoadUnownedInst, is LoadWeakInst, is ValueMetatypeInst, is ExistentialMetatypeInst,\n is PackElementGetInst:\n let svi = operand.instruction as! SingleValueInstruction\n return loadedAddressUse(of: operand, intoValue: svi)\n\n case is YieldInst:\n return yieldedAddressUse(of: operand)\n\n case let sdai as SourceDestAddrInstruction\n where sdai.sourceOperand == operand:\n return loadedAddressUse(of: operand, intoAddress: sdai.destinationOperand)\n\n case let sdai as SourceDestAddrInstruction\n where sdai.destinationOperand == operand:\n return leafAddressUse(of: operand)\n\n case let builtin as BuiltinInst:\n switch builtin.id {\n // Builtins that cannot load a nontrivial value.\n case .TSanInoutAccess, .ResumeThrowingContinuationReturning,\n .ResumeNonThrowingContinuationReturning, .GenericAdd,\n .GenericFAdd, .GenericAnd, .GenericAShr, .GenericLShr, .GenericOr,\n .GenericFDiv, .GenericMul, .GenericFMul, .GenericSDiv,\n .GenericExactSDiv, .GenericShl, .GenericSRem, .GenericSub,\n .GenericFSub, .GenericUDiv, .GenericExactUDiv, .GenericURem,\n .GenericFRem, .GenericXor, .TaskRunInline, .ZeroInitializer,\n .GetEnumTag, .InjectEnumTag:\n return leafAddressUse(of: operand)\n default:\n // TODO: SIL verification should check that this exhaustively\n // recognizes all builtin address uses.\n return .abortWalk\n }\n\n case is BranchInst, is CondBranchInst:\n fatalError("address phi is not allowed")\n\n default:\n if operand.instruction.isIncidentalUse {\n return leafAddressUse(of: operand)\n }\n // Unknown instruction.\n return unknownAddressUse(of: operand)\n }\n }\n\n private mutating func classifyMarkDependence(operand: Operand) -> WalkResult {\n switch operand.instruction {\n case let markDep as MarkDependenceInst:\n if markDep.valueOperand == operand {\n return projectedAddressUse(of: operand, into: markDep)\n }\n assert(markDep.baseOperand == operand)\n // If another address depends on the current address,\n // handle it like a projection.\n if markDep.type.isAddress {\n return projectedAddressUse(of: operand, into: markDep)\n }\n switch markDep.dependenceKind {\n case .Unresolved:\n if LifetimeDependence(markDep, context) == nil {\n break\n }\n fallthrough\n case .NonEscaping:\n // Note: This is unreachable from InteriorUseVisitor because the base address of a `mark_dependence\n // [nonescaping]` must be a `begin_access`, and interior liveness does not check uses of the accessed address.\n return dependentAddressUse(of: operand, dependentValue: markDep)\n case .Escaping:\n break\n }\n // A potentially escaping value depends on this address.\n return escapingAddressUse(of: operand)\n \n case let markDep as MarkDependenceAddrInst:\n if markDep.addressOperand == operand {\n return leafAddressUse(of: operand)\n }\n switch markDep.dependenceKind {\n case .Unresolved:\n if LifetimeDependence(markDep, context) == nil {\n break\n }\n fallthrough\n case .NonEscaping:\n return dependentAddressUse(of: operand, dependentAddress: markDep.address)\n case .Escaping:\n break\n }\n // A potentially escaping value depends on this address.\n return escapingAddressUse(of: operand)\n\n default:\n fatalError("Unexpected MarkDependenceInstruction")\n }\n }\n}\n\nextension AccessBase {\n enum Initializer {\n // An @in or @inout argument that is never modified inside the function. Handling an unmodified @inout like an @in\n // allows clients to ignore access scopes for the purpose of reaching definitions and lifetimes.\n case argument(FunctionArgument)\n // A yielded @in argument.\n case yield(MultipleValueInstructionResult)\n // A local variable or @out argument that is assigned once.\n // 'initialAddress' is the first point at which address may be used. Typically the allocation.\n case store(initializingStore: Instruction, initialAddress: Value)\n\n var initialAddress: Value {\n let address: Value\n switch self {\n case let .argument(arg):\n address = arg\n case let .yield(result):\n address = result\n case let .store(_, initialAddress):\n address = initialAddress\n }\n assert(address.type.isAddress)\n return address\n }\n }\n\n /// If this access base has a single initializer, return it, along with the initialized address. This does not\n /// guarantee that all uses of that address are dominated by the store or even that the store is a direct use of\n /// `address`.\n func findSingleInitializer(_ context: some Context) -> Initializer? {\n let baseAddr: Value\n switch self {\n case let .stack(allocStack):\n baseAddr = allocStack\n case let .argument(arg):\n if arg.convention.isIndirectIn {\n return .argument(arg)\n }\n baseAddr = arg\n case let .storeBorrow(sbi):\n guard case let .stack(allocStack) = sbi.destinationOperand.value.accessBase else {\n return nil\n }\n return .store(initializingStore: sbi, initialAddress: allocStack)\n default:\n return nil\n }\n return AddressInitializationWalker.findSingleInitializer(ofAddress: baseAddr, context: context)\n }\n}\n\n// Walk the address def-use paths to find a single initialization.\n//\n// Implements AddressUseVisitor to guarantee that we can't miss any\n// stores. This separates escapingAddressUse from leafAddressUse.\n//\n// Main entry point:\n// static func findSingleInitializer(ofAddress: Value, context: some Context)\n//\n// TODO: Make AddressDefUseWalker always conform to AddressUseVisitor once we're\n// ready to debug changes to escape analysis etc...\n//\n// Future:\n// AddressUseVisitor\n// (how to transitively follow uses, complete classification)\n// -> AddressPathDefUseWalker\n// (follow projections and track Path,\n// client handles all other uses, such as access scopes)\n// -> AddressProjectionDefUseWalker\n// (follow projections, track Path, ignore access scopes,\n// merge all other callbacks into only two:\n// instantaneousAddressUse vs. escapingAddressUse)\n//\n// FIXME: This currently assumes that isAddressInitialization catches\n// writes to the memory address. We need a complete abstraction that\n// distinguishes between `mayWriteToMemory` for dependence vs. actual\n// modification of memory.\nstruct AddressInitializationWalker: AddressDefUseWalker, AddressUseVisitor {\n let baseAddress: Value\n let context: any Context\n\n var walkDownCache = WalkerCache<SmallProjectionPath>()\n\n var isProjected = false\n var initializer: AccessBase.Initializer?\n\n static func findSingleInitializer(ofAddress baseAddr: Value, context: some Context)\n -> AccessBase.Initializer? {\n\n var walker = AddressInitializationWalker(baseAddress: baseAddr, context)\n if walker.walkDownUses(ofAddress: baseAddr, path: SmallProjectionPath()) == .abortWalk {\n return nil\n }\n return walker.initializer\n }\n\n private init(baseAddress: Value, _ context: some Context) {\n self.baseAddress = baseAddress\n self.context = context\n if let arg = baseAddress as? FunctionArgument {\n assert(!arg.convention.isIndirectIn, "@in arguments cannot be initialized")\n if arg.convention.isInout {\n initializer = .argument(arg)\n }\n // @out arguments are initialized normally via stores.\n }\n }\n\n private mutating func setInitializer(instruction: Instruction) -> WalkResult {\n // An initializer must be unique and store the full value.\n if initializer != nil || isProjected {\n initializer = nil\n return .abortWalk\n }\n initializer = .store(initializingStore: instruction, initialAddress: baseAddress)\n return .continueWalk\n }\n}\n\n// Implement AddressDefUseWalker\nextension AddressInitializationWalker {\n mutating func leafUse(address: Operand, path: SmallProjectionPath)\n -> WalkResult {\n isProjected = !path.isEmpty\n return classifyAddress(operand: address)\n }\n}\n\n// Implement AddressUseVisitor\nextension AddressInitializationWalker {\n /// An address projection produces a single address result and does not\n /// escape its address operand in any other way.\n mutating func projectedAddressUse(of operand: Operand, into value: Value)\n -> WalkResult {\n // AddressDefUseWalker should catch most of these.\n return .abortWalk\n }\n\n mutating func scopedAddressUse(of operand: Operand) -> WalkResult {\n // AddressDefUseWalker currently skips most of these.\n return .abortWalk\n }\n\n mutating func scopeEndingAddressUse(of operand: Operand) -> WalkResult {\n // AddressDefUseWalker currently skips most of these.\n return .continueWalk\n }\n\n mutating func leafAddressUse(of operand: Operand) -> WalkResult {\n if operand.isAddressInitialization {\n return setInitializer(instruction: operand.instruction)\n }\n // FIXME: check mayWriteToMemory but ignore non-stores. Currently,\n // stores should all be checked my isAddressInitialization, but\n // this is not robust.\n return .continueWalk\n }\n\n mutating func appliedAddressUse(of operand: Operand, by apply: FullApplySite)\n -> WalkResult {\n if operand.isAddressInitialization {\n return setInitializer(instruction: operand.instruction)\n }\n guard let convention = apply.convention(of: operand) else {\n return .continueWalk\n }\n return convention.isIndirectIn ? .continueWalk : .abortWalk\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoValue value: Value)\n -> WalkResult {\n return .continueWalk\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoAddress address: Operand)\n -> WalkResult {\n return .continueWalk\n }\n\n mutating func yieldedAddressUse(of operand: Operand) -> WalkResult {\n // An inout yield is a partial write. Initialization via coroutine is not supported, so we assume a prior\n // initialization must dominate the yield.\n return .continueWalk\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentValue value: Value) -> WalkResult {\n return .continueWalk\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentAddress address: Value) -> WalkResult {\n return .continueWalk\n }\n\n mutating func escapingAddressUse(of operand: Operand) -> WalkResult {\n return .abortWalk\n }\n\n mutating func unknownAddressUse(of operand: Operand) -> WalkResult {\n return .abortWalk\n }\n}\n\n/// A live range representing the ownership of addressable memory.\n///\n/// This live range represents the minimal guaranteed lifetime of the object being addressed. Uses of derived addresses\n/// may be extended up to the ends of this scope without violating ownership.\n///\n/// .liveOut objects (@in_guaranteed, @out) and .global variables have no instruction range.\n///\n/// .local objects (alloc_stack, yield, @in, @inout) report the single live range of the full assignment that reaches\n/// this address.\n///\n/// .owned values (boxes and references) simply report OSSA liveness.\n///\n/// .borrow values report each borrow scope's range. The effective live range is their intersection. A valid use must\n/// lie within all ranges.\n///\n/// FIXME: .borrow values should be represented with a single multiply-defined instruction range. Otherwise we will run\n/// out of blockset bits as soon as we have multiple ranges (each range uses three sets). It is ok to take the\n/// union of the borrow ranges since all address uses that may be extended will be already be dominated by the current\n/// address. Alternatively, we can have a utility that folds two InstructionRanges together as an intersection, and\n/// repeatedly fold the range of each borrow introducer.\n///\n/// Example:\n///\n/// %x = alloc_box\n/// %b = begin_borrow %x -+ begin ownership range\n/// %p = project_box %b | <--- accessBase\n/// %a = begin_access %p |\n/// end_access %a | <--- address use\n/// end_borrow %b -+ end ownership range\n/// destroy_value %x\n///\n/// This may return multiple ranges if a borrowed reference has multiple introducers:\n///\n/// %b1 = begin_borrow -+ range1\n/// %b2 = begin_borrow | -+ -+ range2\n/// %s = struct (%b1, %2) | | |\n/// %e = struct_extract %s, #s.0 | | | intersection\n/// %d = ref_element_addr %e | | | where ownership\n/// %a = begin_access %d | | | is valid\n/// end_access %a | | |\n/// end_borrow %b1 -+ | -+\n/// ... |\n/// end_borrow %b2 -+\n///\n/// Note: The resulting live range must be deinitialized in stack order.\nenum AddressOwnershipLiveRange : CustomStringConvertible {\n case liveOut(FunctionArgument)\n case global(GlobalVariable)\n case local(Value, InstructionRange) // Value represents the local allocation\n case owned(Value, InstructionRange)\n case borrow(SingleInlineArray<(BeginBorrowValue, InstructionRange)>)\n\n mutating func deinitialize() {\n switch self {\n case .liveOut, .global:\n break\n case var .local(_, range):\n range.deinitialize()\n case var .owned(_, range):\n range.deinitialize()\n case var .borrow(ranges):\n for idx in ranges.indices {\n ranges[idx].1.deinitialize()\n }\n }\n }\n\n /// Return the live range of the addressable value that reaches 'begin', not including 'begin', which may itself be an\n /// access of the address.\n ///\n /// The range ends at the destroy or reassignment of the addressable value.\n ///\n /// Return nil if the live range is unknown.\n static func compute(for address: Value, at begin: Instruction,\n _ localReachabilityCache: LocalVariableReachabilityCache,\n _ context: FunctionPassContext) -> AddressOwnershipLiveRange? {\n let accessBase = address.accessBase\n switch accessBase {\n case .box, .class, .tail:\n return computeValueLiveRange(of: accessBase.reference!, context)\n case let .stack(allocStack):\n return computeLocalLiveRange(allocation: allocStack, begin: begin, localReachabilityCache, context)\n case let .global(global):\n return .global(global)\n case let .argument(arg):\n switch arg.convention {\n case .indirectInGuaranteed, .indirectOut:\n return .liveOut(arg)\n case .indirectIn, .indirectInout, .indirectInoutAliasable:\n return computeLocalLiveRange(allocation: arg, begin: begin, localReachabilityCache, context)\n default:\n return nil\n }\n case let .yield(result):\n let apply = result.parentInstruction as! BeginApplyInst\n switch apply.convention(of: result) {\n case .indirectInGuaranteed:\n var range = InstructionRange(for: address, context)\n _ = BorrowingInstruction(apply)!.visitScopeEndingOperands(context) {\n range.insert($0.instruction)\n return .continueWalk\n }\n return .local(result, range)\n case .indirectIn, .indirectInout, .indirectInoutAliasable:\n return computeLocalLiveRange(allocation: result, begin: begin, localReachabilityCache, context)\n default:\n return nil\n }\n case .storeBorrow(let sb):\n return computeValueLiveRange(of: sb.source, context)\n case .pointer, .index, .unidentified:\n return nil\n }\n }\n\n /// Does this inclusive range include `inst`, assuming that `inst` occurs after a definition of the live range.\n func coversUse(_ inst: Instruction) -> Bool {\n switch self {\n case .liveOut, .global:\n return true\n case let .local(_, range), let .owned(_, range):\n return range.inclusiveRangeContains(inst)\n case let .borrow(borrowRanges):\n for (_, range) in borrowRanges {\n if !range.inclusiveRangeContains(inst) {\n return false\n }\n }\n return true\n }\n }\n\n var description: String {\n switch self {\n case let .liveOut(arg):\n return "liveOut: \(arg)"\n case let .global(global):\n return "global: \(global)"\n case let .local(allocation, range):\n return "local: \(allocation)\n\(range)"\n case let .owned(value, range):\n return "owned: \(value)\n\(range)"\n case let .borrow(borrowRanges):\n var str = ""\n for (borrow, range) in borrowRanges {\n str += "borrow: \(borrow)\n\(range)"\n }\n return str\n }\n }\n}\n\nextension AddressOwnershipLiveRange {\n /// Compute the ownership live range of any non-address value.\n ///\n /// For an owned value, simply compute its liveness. For a guaranteed value, return a separate range for each borrow\n /// introducer.\n ///\n /// For address values, use AccessBase.computeOwnershipRange.\n ///\n /// FIXME: This should use computeLinearLiveness rather than computeKnownLiveness as soon as complete OSSA lifetimes\n /// are verified.\n private static func computeValueLiveRange(of value: Value, _ context: FunctionPassContext)\n -> AddressOwnershipLiveRange? {\n switch value.ownership {\n case .none, .unowned:\n // This is unexpected for a value with derived addresses.\n return nil\n case .owned:\n return .owned(value, computeKnownLiveness(for: value, context))\n case .guaranteed:\n return .borrow(computeBorrowLiveRange(for: value, context))\n }\n }\n\n private static func computeLocalLiveRange(allocation: Value, begin: Instruction,\n _ localReachabilityCache: LocalVariableReachabilityCache,\n _ context: some Context) -> AddressOwnershipLiveRange? {\n guard let localReachability = localReachabilityCache.reachability(for: allocation, context) else {\n return nil\n }\n var reachingAssignments = Stack<LocalVariableAccess>(context)\n defer { reachingAssignments.deinitialize() }\n\n if !localReachability.gatherReachingAssignments(for: begin, in: &reachingAssignments) {\n return nil\n }\n // Any one of the reaching assignment is sufficient to compute the minimal live range. The caller presumably only\n // cares about the live range that is dominated by 'begin'. Since all assignments gathered above reach\n // 'begin', their live ranges must all be identical on all paths through 'addressInst'.\n let assignment = reachingAssignments.first!\n\n var reachableUses = Stack<LocalVariableAccess>(context)\n defer { reachableUses.deinitialize() }\n\n localReachability.gatherKnownLifetimeUses(from: assignment, in: &reachableUses)\n\n let assignmentInst = assignment.instruction ?? allocation.parentFunction.entryBlock.instructions.first!\n var range = InstructionRange(begin: assignmentInst, context)\n for localAccess in reachableUses {\n if localAccess.kind == .escape {\n log("Local variable: \(allocation)\n escapes at \(localAccess.instruction!)")\n }\n for end in localAccess.instruction!.endInstructions {\n range.insert(end)\n }\n }\n return .local(allocation, range)\n }\n}\n\nlet addressOwnershipLiveRangeTest = FunctionTest("address_ownership_live_range") {\n function, arguments, context in\n let address = arguments.takeValue()\n print("Address: \(address)")\n print("Base: \(address.accessBase)")\n let begin = address.definingInstructionOrTerminator ?? {\n assert(address is FunctionArgument)\n return function.instructions.first!\n }()\n let localReachabilityCache = LocalVariableReachabilityCache()\n guard var ownershipRange = AddressOwnershipLiveRange.compute(for: address, at: begin,\n localReachabilityCache, context) else {\n print("Error: indeterminate live range")\n return\n }\n defer { ownershipRange.deinitialize() }\n print(ownershipRange)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_AddressUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_AddressUtils.swift
Swift
25,691
0.95
0.091729
0.282353
react-lib
781
2025-04-05T11:51:24.441449
MIT
false
2a72dfcfd3ba0f399b9a887e11152f5d
//===--- BorrowUtils.swift - Utilities for borrow scopes ------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Utilities that model Ownership SSA (OSSA) borrow scopes.\n//\n// A BorrowingInstruction borrows one or more operands over a new\n// borrow scope, up to its scope-ending uses. This is typically\n// checked during a def-use walk.\n//\n// %val = some owned value\n// %store = store_borrow %val to %addr // borrowing instruction\n// ... // borrow scope\n// end_borrow %store // scope-ending use\n//\n// A BeginBorrowValue introduces a guaranteed OSSA lifetime. It\n// begins a new borrow scope that ends at its scope-ending uses. A\n// begin-borrow value may be defined by a borrowing instruction:\n//\n// %begin = begin_borrow %val // %begin borrows %val\n// ... // borrow scope\n// end_borrow %begin // scope-ending use\n//\n// Other kinds of BeginBorrowValues, however, like block arguments and\n// `load_borrow`, are not borrowing instructions. BeginBorrowValues\n// are typically checked during a use-def walk. Here, walking up from\n// `%forward` finds `%begin` as the introducer of its guaranteed\n// lifetime:\n//\n// %begin = load_borrow %addr // BeginBorrowValue\n// %forward = struct (%begin) // forwards a guaranteed value\n// ...\n// end_borrow %begin // scope-ending use\n// \n// Every guaranteed OSSA value has a set of borrow introducers, each\n// of which dominates the value and introduces a borrow scope that\n// encloses all forwarded uses of the guaranteed value.\n//\n// %1 = begin_borrow %0 // borrow introducer for %2\n// %2 = begin_borrow %1 // borrow introducer for %3\n// %3 = struct (%1, %2) // forwards two guaranteed values\n// ... all forwarded uses of %3\n// end_borrow %1 // scope-ending use\n// end_borrow %2 // scope-ending use\n//\n// Inner borrow scopes may be nested in outer borrow scopes:\n//\n// %1 = begin_borrow %0 // borrow introducer for %2\n// %2 = begin_borrow %1 // borrow introducer for %3\n// %3 = struct (%2)\n// ... all forwarded uses of %3\n// end_borrow %2 // scope-ending use of %2\n// end_borrow %1 // scope-ending use of %1\n//\n// Walking up the nested OSSA lifetimes requires iteratively querying\n// "enclosing values" until either a guaranteed function argument or\n// owned value is reached. Like a borrow introducer, an enclosing\n// value dominates all values that it encloses.\n//\n// Borrow Introducer Enclosing Value\n// ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~\n// %0 = some owned value invalid none\n// %1 = begin_borrow %0 %1 %0\n// %2 = begin_borrow %1 %2 %1\n// %3 = struct (%2) %2 %2\n//\n// The borrow introducer of a guaranteed phi is not directly\n// determined by a use-def walk because an introducer must dominate\n// all uses in its scope:\n//\n// Borrow Introducer Enclosing Value\n// ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~\n// \n// cond_br ..., bb1, bb2 \n// bb1: \n// %2 = begin_borrow %0 %2 %0\n// %3 = struct (%2) %2 %2\n// br bb3(%2, %3) \n// bb2: \n// %6 = begin_borrow %0 %6 %0\n// %7 = struct (%6) %6 %6\n// br bb3(%6, %7) \n// bb3(%reborrow: @reborrow, %reborrow %0\n// %phi: @guaranteed): %phi %reborrow\n// \n// `%reborrow` is an outer-adjacent phi to `%phi` because it encloses\n// `%phi`. `%phi` is an inner-adjacent phi to `%reborrow` because its\n// uses keep `%reborrow` alive. An outer-adjacent phi is either an\n// owned value or a reborrow. An inner-adjacent phi is either a\n// reborrow or a guaranteed forwarding phi. Here is an example of an\n// owned outer-adjacent phi with an inner-adjacent reborrow:\n// \n// Borrow Introducer Enclosing Value\n// ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~\n// \n// cond_br ..., bb1, bb2 \n// bb1: \n// %1 = owned value \n// %2 = begin_borrow %1 %2 %1\n// br bb3(%1, %2) \n// bb2: \n// %5 = owned value \n// %6 = begin_borrow %5 %6 %5\n// br bb3(%5, %6) \n// bb3(%phi: @owned, invalid none\n// %reborrow: @reborrow): %reborrow %phi\n// \n// In OSSA, each owned value defines a separate lifetime. It is\n// consumed on all paths by a direct use. Owned lifetimes can,\n// however, be nested within a borrow scope. In this case, finding the\n// scope-ending uses requires traversing owned forwarding\n// instructions:\n//\n// %1 = partial_apply %f(%0) // borrowing instruction borrows %0 and produces\n// // an owned closure value.\n// %2 = struct (%1) // end owned lifetime %1, begin owned lifetime %2\n// destroy_value %2 // end owned lifetime %2, scope-ending use of %1\n//\n//\n// TODO: These utilities should be integrated with OSSA SIL verification and\n// guaranteed to be complete (produce known results for all legal SIL\n// patterns).\n// ===----------------------------------------------------------------------===//\n\nimport SIL\n\n/// A scoped instruction that borrows one or more operands.\n///\n/// If this instruction produces a borrowed value, then BeginBorrowValue(resultOf: self) != nil.\n///\n/// This does not include instructions like `apply` and `try_apply` that instantaneously borrow a value from the caller.\n///\n/// This does not include `load_borrow` because it borrows a memory location, not the value of its operand.\n///\n/// Note: This must handle all instructions with a .borrow operand ownership.\n///\n/// Note: borrowed_from is a BorrowingInstruction because it creates a borrow scope for its enclosing operands. Its\n/// result, however, is only a BeginBorrowValue (.reborrow) if it forwards a reborrow phi. Otherwise, it simply forwards\n/// a guaranteed value and does not introduce a separate borrow scope.\n///\n/// Note: mark_dependence [nonescaping] is a BorrowingInstruction because it creates a borrow scope for its base\n/// operand. Its result, however, is not a BeginBorrowValue. Instead it is a ForwardingInstruction relative to its value\n/// operand.\n///\n/// TODO: replace BorrowIntroducingInstruction with this.\nenum BorrowingInstruction : CustomStringConvertible, Hashable {\n case beginBorrow(BeginBorrowInst)\n case borrowedFrom(BorrowedFromInst)\n case storeBorrow(StoreBorrowInst)\n case beginApply(BeginApplyInst)\n case partialApply(PartialApplyInst)\n case markDependence(MarkDependenceInst)\n case startAsyncLet(BuiltinInst)\n\n init?(_ inst: Instruction) {\n switch inst {\n case let bbi as BeginBorrowInst:\n self = .beginBorrow(bbi)\n case let bfi as BorrowedFromInst:\n self = .borrowedFrom(bfi)\n case let sbi as StoreBorrowInst:\n self = .storeBorrow(sbi)\n case let bai as BeginApplyInst:\n self = .beginApply(bai)\n case let pai as PartialApplyInst where !pai.mayEscape:\n self = .partialApply(pai)\n case let mdi as MarkDependenceInst:\n guard mdi.isNonEscaping else {\n return nil\n }\n self = .markDependence(mdi)\n case let bi as BuiltinInst\n where bi.id == .StartAsyncLetWithLocalBuffer:\n self = .startAsyncLet(bi)\n default:\n return nil\n }\n }\n \n var instruction: Instruction {\n switch self {\n case .beginBorrow(let bbi):\n return bbi\n case .borrowedFrom(let bfi):\n return bfi\n case .storeBorrow(let sbi):\n return sbi\n case .beginApply(let bai):\n return bai\n case .partialApply(let pai):\n return pai\n case .markDependence(let mdi):\n return mdi\n case .startAsyncLet(let bi):\n return bi\n }\n }\n\n var innerValue: Value? {\n if let dependent = dependentValue {\n return dependent\n }\n return scopedValue\n }\n\n var dependentValue: Value? {\n switch self {\n case .borrowedFrom(let bfi):\n let phi = bfi.borrowedPhi\n if phi.isReborrow {\n return nil\n }\n return phi.value\n case .markDependence(let mdi):\n if mdi.hasScopedLifetime {\n return nil\n }\n return mdi\n case .beginBorrow, .storeBorrow, .beginApply, .partialApply, .startAsyncLet:\n return nil\n }\n }\n\n /// If this is valid, then visitScopeEndingOperands succeeds.\n var scopedValue: Value? {\n switch self {\n case .beginBorrow, .storeBorrow:\n return instruction as! SingleValueInstruction\n case let .borrowedFrom(bfi):\n let phi = bfi.borrowedPhi\n guard phi.isReborrow else {\n return nil\n }\n return phi.value\n case .beginApply(let bai):\n return bai.token\n case .partialApply(let pai):\n // We currently assume that closure lifetimes are always complete (destroyed on all paths).\n return pai\n case .markDependence(let mdi):\n guard mdi.hasScopedLifetime else {\n return nil\n }\n return mdi\n case .startAsyncLet(let builtin):\n return builtin\n }\n }\n\n /// Visit the operands that end the local borrow scope.\n ///\n /// Returns .abortWalk if the borrow scope cannot be determined from lifetime-ending uses. For example:\n /// - borrowed_from where 'borrowedPhi.isReborrow == false'\n /// - non-owned mark_dependence [nonescaping]\n /// - owned mark_dependence [nonescaping] with a ~Escapable result (LifetimeDependenceDefUseWalker is needed).\n ///\n /// Note: .partialApply and .markDependence cannot currently be forwarded to phis because partial_apply [on_stack] and\n /// mark_dependence [nonescaping] cannot be cloned. Walking through the phi therefore safely returns dominated\n /// scope-ending operands. Handling phis here requires the equivalent of borrowed_from for owned values.\n ///\n /// TODO: For instructions that are not a BeginBorrowValue, verify that scope ending instructions exist on all\n /// paths. These instructions should be complete after SILGen and never cloned to produce phis.\n func visitScopeEndingOperands(_ context: Context, visitor: @escaping (Operand) -> WalkResult) -> WalkResult {\n guard let val = scopedValue else {\n return .abortWalk\n }\n switch self {\n case .beginBorrow, .storeBorrow:\n return visitEndBorrows(value: val, context, visitor)\n case .borrowedFrom:\n return visitEndBorrows(value: val, context, visitor)\n case .beginApply:\n return val.uses.walk { return visitor($0) }\n case .partialApply:\n // We currently assume that closure lifetimes are always complete (destroyed on all paths).\n return visitOwnedDependent(value: val, context, visitor)\n case .markDependence:\n return visitOwnedDependent(value: val, context, visitor)\n case .startAsyncLet:\n return val.uses.walk {\n if let builtinUser = $0.instruction as? BuiltinInst,\n builtinUser.id == .EndAsyncLetLifetime {\n return visitor($0)\n }\n return .continueWalk\n }\n }\n }\n}\n\nextension BorrowingInstruction {\n private func visitEndBorrows(value: Value, _ context: Context, _ visitor: @escaping (Operand) -> WalkResult)\n -> WalkResult {\n return value.lookThroughBorrowedFromUser.uses.filterUsers(ofType: EndBorrowInst.self).walk {\n visitor($0)\n }\n }\n\n private func visitOwnedDependent(value: Value, _ context: Context, _ visitor: @escaping (Operand) -> WalkResult)\n -> WalkResult {\n return visitForwardedUses(introducer: value, context) {\n switch $0 {\n case let .operand(operand):\n if operand.endsLifetime {\n return visitor(operand)\n }\n return .continueWalk\n case let .deadValue(_, operand):\n if let operand = operand {\n assert(!operand.endsLifetime,\n "a dead forwarding instruction cannot end a lifetime")\n }\n return .continueWalk\n }\n }\n }\n\n var description: String { instruction.description }\n}\n\n/// A value that introduces a borrow scope:\n/// begin_borrow, load_borrow, reborrow, guaranteed function argument, begin_apply, unchecked_ownership_conversion.\n///\n/// If the value introduces a local scope, then that scope is\n/// terminated by scope ending operands. Function arguments do not\n/// introduce a local scope because the caller owns the scope.\n///\n/// If the value is a begin_apply result, then it may be the token or\n/// one of the yielded values. In any case, the scope ending operands\n/// are on the end_apply or abort_apply instructions that use the\n/// token.\nenum BeginBorrowValue {\n case beginBorrow(BeginBorrowInst)\n case loadBorrow(LoadBorrowInst)\n case beginApply(Value)\n case uncheckOwnershipConversion(UncheckedOwnershipConversionInst)\n case functionArgument(FunctionArgument)\n case reborrow(Phi)\n\n init?(_ value: Value) {\n switch value {\n case let bbi as BeginBorrowInst:\n self = .beginBorrow(bbi)\n case let lbi as LoadBorrowInst:\n self = .loadBorrow(lbi)\n case let uoci as UncheckedOwnershipConversionInst where uoci.ownership == .guaranteed:\n self = .uncheckOwnershipConversion(uoci)\n case let arg as FunctionArgument where arg.ownership == .guaranteed:\n self = .functionArgument(arg)\n case let arg as Argument where arg.isReborrow:\n self = .reborrow(Phi(arg)!)\n default:\n if value.definingInstruction is BeginApplyInst {\n self = .beginApply(value)\n break\n }\n return nil\n }\n }\n \n var value: Value {\n switch self {\n case .beginBorrow(let bbi): return bbi\n case .loadBorrow(let lbi): return lbi\n case .beginApply(let v): return v\n case .uncheckOwnershipConversion(let uoci): return uoci\n case .functionArgument(let arg): return arg\n case .reborrow(let phi): return phi.value\n }\n }\n\n init?(using operand: Operand) {\n switch operand.instruction {\n case is BeginBorrowInst, is LoadBorrowInst:\n let inst = operand.instruction as! SingleValueInstruction\n self = BeginBorrowValue(inst)!\n case is BranchInst:\n guard let phi = Phi(using: operand) else {\n return nil\n }\n guard phi.isReborrow else {\n return nil\n }\n self = .reborrow(phi)\n default:\n return nil\n }\n }\n\n init?(resultOf borrowInstruction: BorrowingInstruction) {\n switch borrowInstruction {\n case let .beginBorrow(beginBorrow):\n self.init(beginBorrow)\n case let .borrowedFrom(borrowedFrom):\n // only returns non-nil if borrowedPhi is a reborrow\n self.init(borrowedFrom.borrowedPhi.value)\n case let .beginApply(beginApply):\n self.init(beginApply.token)\n case .storeBorrow, .partialApply, .markDependence, .startAsyncLet:\n return nil\n }\n }\n\n var hasLocalScope: Bool {\n switch self {\n case .beginBorrow, .loadBorrow, .beginApply, .reborrow, .uncheckOwnershipConversion:\n return true\n case .functionArgument:\n return false\n }\n }\n\n // Return the value borrowed by begin_borrow or address borrowed by\n // load_borrow.\n //\n // Return nil for begin_apply and reborrow, which need special handling.\n var baseOperand: Operand? {\n switch self {\n case let .beginBorrow(beginBorrow):\n return beginBorrow.operand\n case let .loadBorrow(loadBorrow):\n return loadBorrow.operand\n case .beginApply, .functionArgument, .reborrow, .uncheckOwnershipConversion:\n return nil\n }\n }\n\n /// The EndBorrows, reborrows (phis), and consumes (of closures)\n /// that end the local borrow scope. Empty if hasLocalScope is false.\n var scopeEndingOperands: LazyFilterSequence<UseList> {\n switch self {\n case let .beginApply(value):\n return (value.definingInstruction\n as! BeginApplyInst).token.uses.endingLifetime\n case let .reborrow(phi):\n return phi.value.lookThroughBorrowedFromUser.uses.endingLifetime\n default:\n return value.uses.endingLifetime\n }\n }\n}\n\n/// Compute the live range for the borrow scopes of a guaranteed value. This returns a separate instruction range for\n/// each of the value's borrow introducers.\n///\n/// TODO: This should return a single multiply-defined instruction range.\nfunc computeBorrowLiveRange(for value: Value, _ context: FunctionPassContext)\n -> SingleInlineArray<(BeginBorrowValue, InstructionRange)> {\n assert(value.ownership == .guaranteed)\n\n var ranges = SingleInlineArray<(BeginBorrowValue, InstructionRange)>()\n // If introducers is empty, then the dependence is on a trivial value, so\n // there is no ownership range.\n for beginBorrow in value.getBorrowIntroducers(context) {\n /// FIXME: Remove calls to computeKnownLiveness() as soon as lifetime completion runs immediately after\n /// SILGen. Instead, this should compute linear liveness for borrowed value by switching over BeginBorrowValue, just\n /// like LifetimeDependenc.Scope.computeRange().\n ranges.push((beginBorrow, computeKnownLiveness(for: beginBorrow.value, context)))\n }\n return ranges\n}\n\nextension Value {\n var lookThroughBorrowedFrom: Value {\n if let bfi = self as? BorrowedFromInst {\n return bfi.borrowedValue.lookThroughBorrowedFrom\n }\n return self\n }\n}\n\nstruct BorrowIntroducers<Ctxt: Context> : CollectionLikeSequence {\n let initialValue: Value\n let context: Ctxt\n\n func makeIterator() -> EnclosingValueIterator {\n EnclosingValueIterator(forBorrowIntroducers: initialValue, context)\n }\n}\n\nstruct EnclosingValues<Ctxt: Context> : CollectionLikeSequence {\n let initialValue: Value\n let context: Ctxt\n\n func makeIterator() -> EnclosingValueIterator {\n EnclosingValueIterator(forEnclosingValues: initialValue, context)\n }\n}\n\n// This iterator must be a class because we need a deinit.\n// It shouldn't be a performance problem because the optimizer should always be able to stack promote the iterator.\n// TODO: Make it a struct once this is possible with non-copyable types.\nfinal class EnclosingValueIterator : IteratorProtocol {\n var worklist: ValueWorklist\n\n init(forBorrowIntroducers value: Value, _ context: some Context) {\n self.worklist = ValueWorklist(context)\n self.worklist.pushIfNotVisited(value)\n }\n\n init(forEnclosingValues value: Value, _ context: some Context) {\n self.worklist = ValueWorklist(context)\n if value is Undef || value.ownership != .guaranteed {\n return\n }\n if let beginBorrow = BeginBorrowValue(value.lookThroughBorrowedFrom) {\n switch beginBorrow {\n case let .beginBorrow(bbi):\n // Gather the outer enclosing borrow scope.\n worklist.pushIfNotVisited(bbi.borrowedValue)\n case .loadBorrow, .beginApply, .functionArgument, .uncheckOwnershipConversion:\n // There is no enclosing value on this path.\n break\n case .reborrow(let phi):\n worklist.pushIfNotVisited(contentsOf: phi.borrowedFrom!.enclosingValues)\n }\n } else {\n // Handle forwarded guaranteed values.\n worklist.pushIfNotVisited(value)\n }\n }\n\n deinit {\n worklist.deinitialize()\n }\n\n func next() -> Value? {\n while let value = worklist.pop() {\n switch value.ownership {\n case .none, .unowned:\n break\n\n case .owned:\n return value\n\n case .guaranteed:\n if BeginBorrowValue(value) != nil {\n return value\n } else if let bfi = value as? BorrowedFromInst {\n if bfi.borrowedPhi.isReborrow {\n worklist.pushIfNotVisited(bfi.borrowedValue)\n } else {\n worklist.pushIfNotVisited(contentsOf: bfi.enclosingValues)\n }\n } else if let forwardingInst = value.forwardingInstruction {\n // Recurse through guaranteed forwarding non-phi instructions.\n let ops = forwardingInst.forwardedOperands\n worklist.pushIfNotVisited(contentsOf: ops.lazy.map { $0.value })\n } else {\n fatalError("cannot get borrow introducers for unknown guaranteed value")\n }\n }\n }\n return nil\n }\n}\n\n\nextension Value {\n /// Get the borrow introducers for this value. This gives you a set of\n /// OSSA lifetimes that directly include this value. If this value is owned,\n /// or introduces a borrow scope, then this value is the single introducer for itself.\n ///\n /// If this value is an address or any trivial type, then it has no introducers.\n ///\n /// Example: // introducers:\n /// // ~~~~~~~~~~~~\n /// bb0(%0 : @owned $Class, // %0\n /// %1 : @guaranteed $Class): // %1\n /// %borrow0 = begin_borrow %0 // %borrow0\n /// %pair = struct $Pair(%borrow0, %1) // %borrow0, %1\n /// %first = struct_extract %pair // %borrow0, %1\n /// %field = ref_element_addr %first // (none)\n /// %load = load_borrow %field : $*C // %load\n ///\n func getBorrowIntroducers<Ctxt: Context>(_ context: Ctxt) -> LazyMapSequence<BorrowIntroducers<Ctxt>, BeginBorrowValue> {\n BorrowIntroducers(initialValue: self, context: context).lazy.map { BeginBorrowValue($0)! }\n }\n\n /// Get "enclosing values" whose OSSA lifetime immediately encloses a guaranteed value.\n ///\n /// The guaranteed value being enclosed effectively keeps these enclosing values alive.\n /// This lets you walk up the levels of nested OSSA lifetimes to determine all the\n /// lifetimes that are kept alive by a given SILValue. In particular, it discovers "outer-adjacent phis":\n /// phis that are kept alive by uses of another phi in the same block.\n ///\n /// If this value is a forwarded guaranteed value, then this finds the\n /// introducers of the current borrow scope, which is never an empty set.\n ///\n /// If this value introduces a borrow scope, then this finds the introducers of the outer\n /// enclosing borrow scope that contains this inner scope.\n ///\n /// If this value is a `begin_borrow`, then this function returns its operand.\n ///\n /// If this value is an owned value, a function argument, or a load_borrow, then this is an empty set.\n ///\n /// If this value is a reborrow, then this either returns a dominating enclosing value or an outer adjacent phi.\n ///\n /// Example: // enclosing value:\n /// // ~~~~~~~~~~~~\n /// bb0(%0 : @owned $Class, // (none)\n /// %1 : @guaranteed $Class): // (none)\n /// %borrow0 = begin_borrow %0 // %0\n /// %pair = struct $Pair(%borrow0, %1) // %borrow0, %1\n /// %first = struct_extract %pair // %borrow0, %1\n /// %field = ref_element_addr %first // (none)\n /// %load = load_borrow %field : $*C // %load\n ///\n /// Example: // enclosing value:\n /// // ~~~~~~~~~~~~\n /// %outerBorrow = begin_borrow %0 // %0\n /// %innerBorrow = begin_borrow %outerBorrow // %outerBorrow\n /// br bb1(%outerBorrow, %innerBorrow)\n /// bb1(%outerReborrow : @reborrow, // %0\n /// %innerReborrow : @reborrow) // %outerReborrow\n ///\n func getEnclosingValues<Ctxt: Context>(_ context: Ctxt) -> EnclosingValues<Ctxt> {\n EnclosingValues(initialValue: self, context: context)\n }\n}\n\nextension Phi {\n /// The inner adjacent phis of this outer "enclosing" phi.\n /// These keep the enclosing (outer adjacent) phi alive.\n var innerAdjacentPhis: LazyMapSequence<LazyFilterSequence<LazyMapSequence<UseList, Phi?>>, Phi> {\n value.uses.lazy.compactMap { use in\n if let bfi = use.instruction as? BorrowedFromInst,\n use.index != 0\n {\n return Phi(bfi.borrowedValue)\n }\n return nil\n }\n }\n}\n\n/// Gathers enclosing values by visiting predecessor blocks.\n/// Only used for updating borrowed-from instructions and for verification.\nfunc gatherEnclosingValuesFromPredecessors(\n for phi: Phi,\n in enclosingValues: inout Stack<Value>,\n _ context: some Context\n) {\n var alreadyAdded = ValueSet(context)\n defer { alreadyAdded.deinitialize() }\n\n for predecessor in phi.predecessors {\n let incomingOperand = phi.incomingOperand(inPredecessor: predecessor)\n\n for predEV in incomingOperand.value.getEnclosingValues(context) {\n let ev = predecessor.getEnclosingValueInSuccessor(ofIncoming: predEV)\n if alreadyAdded.insert(ev) {\n enclosingValues.push(ev)\n }\n }\n }\n}\n\nextension BasicBlock {\n // Returns either the `incomingEnclosingValue` or an adjacent phi in the successor block.\n func getEnclosingValueInSuccessor(ofIncoming incomingEnclosingValue: Value) -> Value {\n let branch = terminator as! BranchInst\n if let incomingEV = branch.operands.first(where: { branchOp in\n // Only if the lifetime of `branchOp` ends at the branch (either because it's a reborrow or an owned value),\n // the corresponding phi argument can be the adjacent phi for the incoming value.\n // bb1:\n // %incomingEnclosingValue = some_owned_value\n // %2 = begin_borrow %incomingEnclosingValue // %incomingEnclosingValue = the enclosing value of %2 in bb1\n // br bb2(%incomingEnclosingValue, %2) // lifetime of incomingEnclosingValue ends here\n // bb2(%4 : @owned, %5 : @guaranteed): // -> %4 = the enclosing value of %5 in bb2\n //\n branchOp.endsLifetime &&\n branchOp.value.lookThroughBorrowedFrom == incomingEnclosingValue\n }) {\n return branch.getArgument(for: incomingEV)\n }\n // No candidates phi are outer-adjacent phis. The incomingEnclosingValue must dominate the successor block.\n // bb1: // dominates bb3\n // %incomingEnclosingValue = some_owned_value\n // bb2:\n // %2 = begin_borrow %incomingEnclosingValue\n // br bb3(%2)\n // bb3(%5 : @guaranteed): // -> %incomingEnclosingValue = the enclosing value of %5 in bb3\n //\n return incomingEnclosingValue\n }\n}\n\nlet borrowIntroducersTest = FunctionTest("borrow_introducers") {\n function, arguments, context in\n let value = arguments.takeValue()\n print(function)\n print("Borrow introducers for: \(value)")\n for bi in value.lookThroughBorrowedFromUser.getBorrowIntroducers(context) {\n print(bi)\n }\n}\n\nlet enclosingValuesTest = FunctionTest("enclosing_values") {\n function, arguments, context in\n let value = arguments.takeValue()\n print(function)\n print("Enclosing values for: \(value)")\n var enclosing = Stack<Value>(context)\n defer {\n enclosing.deinitialize()\n }\n for ev in value.lookThroughBorrowedFromUser.getEnclosingValues(context) {\n print(ev)\n }\n}\n\nextension Value {\n var lookThroughBorrowedFromUser: Value {\n for use in uses {\n if let bfi = use.forwardingBorrowedFromUser {\n return bfi\n }\n }\n return self\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_BorrowUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_BorrowUtils.swift
Swift
27,864
0.95
0.116279
0.399417
react-lib
712
2025-02-21T10:55:42.387053
MIT
false
a3e34234e7cde0c76a37979155710922
//===--- Devirtualization.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n/// Devirtualizes all value-type deinitializers of a `destroy_value`.\n///\n/// This may be a no-op if the destroy doesn't call any deinitializers.\n/// Returns true if all deinitializers could be devirtualized.\nfunc devirtualizeDeinits(of destroy: DestroyValueInst, _ context: some MutatingContext) -> Bool {\n return devirtualize(destroy: destroy, context)\n}\n\n/// Devirtualizes all value-type deinitializers of a `destroy_addr`.\n///\n/// This may be a no-op if the destroy doesn't call any deinitializers.\n/// Returns true if all deinitializers could be devirtualized.\nfunc devirtualizeDeinits(of destroy: DestroyAddrInst, _ context: some MutatingContext) -> Bool {\n return devirtualize(destroy: destroy, context)\n}\n\nprivate func devirtualize(destroy: some DevirtualizableDestroy, _ context: some MutatingContext) -> Bool {\n let type = destroy.type\n if !type.isMoveOnly {\n return true\n }\n\n guard let nominal = type.nominal else {\n // E.g. a non-copyable generic function parameter\n return true\n }\n\n // We cannot de-virtualize C++ destructor calls of C++ move-only types because we cannot get\n // its destructor (`nominal.valueTypeDestructor` is nil).\n if nominal.hasClangNode {\n return false\n }\n\n if nominal.valueTypeDestructor != nil && !destroy.shouldDropDeinit {\n guard let deinitFunc = context.lookupDeinit(ofNominal: nominal) else {\n return false\n }\n if deinitFunc.linkage == .shared && !deinitFunc.isDefinition {\n // Make sure to not have an external shared function, which is illegal in SIL.\n _ = context.loadFunction(function: deinitFunc, loadCalleesRecursively: false)\n }\n destroy.createDeinitCall(to: deinitFunc, context)\n context.erase(instruction: destroy)\n return true\n }\n // If there is no deinit to be called for the original type we have to recursively visit\n // the struct fields or enum cases.\n if type.isStruct {\n return destroy.devirtualizeStructFields(context)\n }\n if type.isEnum {\n return destroy.devirtualizeEnumPayloads(context)\n }\n precondition(type.isClass, "unknown non-copyable type")\n // A class reference cannot be further de-composed.\n return true\n}\n\n// Used to dispatch devirtualization tasks to `destroy_value` and `destroy_addr`.\nprivate protocol DevirtualizableDestroy : UnaryInstruction {\n var shouldDropDeinit: Bool { get }\n func createDeinitCall(to deinitializer: Function, _ context: some MutatingContext)\n func devirtualizeStructFields(_ context: some MutatingContext) -> Bool\n func devirtualizeEnumPayload(enumCase: EnumCase, in block: BasicBlock, _ context: some MutatingContext) -> Bool\n func createSwitchEnum(atEndOf block: BasicBlock, cases: [(Int, BasicBlock)], _ context: some MutatingContext)\n}\n\nprivate extension DevirtualizableDestroy {\n var type: Type { operand.value.type }\n\n func devirtualizeEnumPayloads(_ context: some MutatingContext) -> Bool {\n guard let cases = type.getEnumCases(in: parentFunction) else {\n return false\n }\n defer {\n context.erase(instruction: self)\n }\n\n if cases.allPayloadsAreTrivial(in: parentFunction) {\n let builder = Builder(before: self, context)\n builder.createEndLifetime(of: operand.value)\n return true\n }\n\n var caseBlocks: [(caseIndex: Int, targetBlock: BasicBlock)] = []\n let switchBlock = parentBlock\n let endBlock = context.splitBlock(before: self)\n var result = true\n\n for enumCase in cases {\n let caseBlock = context.createBlock(after: switchBlock)\n caseBlocks.append((enumCase.index, caseBlock))\n let builder = Builder(atEndOf: caseBlock, location: location, context)\n builder.createBranch(to: endBlock)\n if !devirtualizeEnumPayload(enumCase: enumCase, in: caseBlock, context) {\n result = false\n }\n }\n createSwitchEnum(atEndOf: switchBlock, cases: caseBlocks, context)\n return result\n }\n}\n\nextension DestroyValueInst : DevirtualizableDestroy {\n fileprivate var shouldDropDeinit: Bool { operand.value.lookThoughOwnershipInstructions is DropDeinitInst }\n\n fileprivate func createDeinitCall(to deinitializer: Function, _ context: some MutatingContext) {\n let builder = Builder(before: self, context)\n let subs = context.getContextSubstitutionMap(for: type)\n let deinitRef = builder.createFunctionRef(deinitializer)\n if deinitializer.argumentConventions[deinitializer.selfArgumentIndex!].isIndirect {\n let allocStack = builder.createAllocStack(type)\n builder.createStore(source: destroyedValue, destination: allocStack, ownership: .initialize)\n builder.createApply(function: deinitRef, subs, arguments: [allocStack])\n builder.createDeallocStack(allocStack)\n } else {\n builder.createApply(function: deinitRef, subs, arguments: [destroyedValue])\n }\n }\n\n fileprivate func devirtualizeStructFields(_ context: some MutatingContext) -> Bool {\n guard let fields = type.getNominalFields(in: parentFunction) else {\n return false\n }\n\n defer {\n context.erase(instruction: self)\n }\n\n let builder = Builder(before: self, context)\n if fields.allFieldsAreTrivial(in: parentFunction) {\n builder.createEndLifetime(of: operand.value)\n return true\n }\n let destructure = builder.createDestructureStruct(struct: destroyedValue)\n var result = true\n\n for fieldValue in destructure.results where !fieldValue.type.isTrivial(in: parentFunction) {\n let destroyField = builder.createDestroyValue(operand: fieldValue)\n if !devirtualizeDeinits(of: destroyField, context) {\n result = false\n }\n }\n return result\n }\n\n fileprivate func devirtualizeEnumPayload(\n enumCase: EnumCase,\n in block: BasicBlock,\n _ context: some MutatingContext\n ) -> Bool {\n let builder = Builder(atBeginOf: block, location: location, context)\n if let payloadTy = enumCase.payload {\n let payload = block.addArgument(type: payloadTy, ownership: .owned, context)\n if !payloadTy.isTrivial(in: parentFunction) {\n let destroyPayload = builder.createDestroyValue(operand: payload)\n return devirtualizeDeinits(of: destroyPayload, context)\n }\n }\n return true\n }\n\n fileprivate func createSwitchEnum(\n atEndOf block: BasicBlock,\n cases: [(Int, BasicBlock)],\n _ context: some MutatingContext\n ) {\n let builder = Builder(atEndOf: block, location: location, context)\n builder.createSwitchEnum(enum: destroyedValue, cases: cases)\n }\n}\n\nextension DestroyAddrInst : DevirtualizableDestroy {\n fileprivate var shouldDropDeinit: Bool {\n // The deinit is always called by a destroy_addr. There must not be a `drop_deinit` as operand.\n false\n }\n\n fileprivate func createDeinitCall(to deinitializer: Function, _ context: some MutatingContext) {\n let builder = Builder(before: self, context)\n let subs = context.getContextSubstitutionMap(for: destroyedAddress.type)\n let deinitRef = builder.createFunctionRef(deinitializer)\n if !deinitializer.argumentConventions[deinitializer.selfArgumentIndex!].isIndirect {\n let value = builder.createLoad(fromAddress: destroyedAddress, ownership: .take)\n builder.createApply(function: deinitRef, subs, arguments: [value])\n } else {\n builder.createApply(function: deinitRef, subs, arguments: [destroyedAddress])\n }\n }\n\n fileprivate func devirtualizeStructFields(_ context: some MutatingContext) -> Bool {\n let builder = Builder(before: self, context)\n\n guard let fields = type.getNominalFields(in: parentFunction) else {\n return false\n }\n defer {\n context.erase(instruction: self)\n }\n if fields.allFieldsAreTrivial(in: parentFunction) {\n builder.createEndLifetime(of: operand.value)\n return true\n }\n var result = true\n for (fieldIdx, fieldTy) in fields.enumerated()\n where !fieldTy.isTrivial(in: parentFunction)\n {\n let fieldAddr = builder.createStructElementAddr(structAddress: destroyedAddress, fieldIndex: fieldIdx)\n let destroyField = builder.createDestroyAddr(address: fieldAddr)\n if !devirtualizeDeinits(of: destroyField, context) {\n result = false\n }\n }\n return result\n }\n\n fileprivate func devirtualizeEnumPayload(\n enumCase: EnumCase,\n in block: BasicBlock,\n _ context: some MutatingContext\n ) -> Bool {\n let builder = Builder(atBeginOf: block, location: location, context)\n if let payloadTy = enumCase.payload,\n !payloadTy.isTrivial(in: parentFunction)\n {\n let caseAddr = builder.createUncheckedTakeEnumDataAddr(enumAddress: destroyedAddress, caseIndex: enumCase.index)\n let destroyPayload = builder.createDestroyAddr(address: caseAddr)\n return devirtualizeDeinits(of: destroyPayload, context)\n }\n return true\n }\n\n fileprivate func createSwitchEnum(\n atEndOf block: BasicBlock,\n cases: [(Int, BasicBlock)],\n _ context: some MutatingContext\n ) {\n let builder = Builder(atEndOf: block, location: location, context)\n builder.createSwitchEnumAddr(enumAddress: destroyedAddress, cases: cases)\n }\n}\n\nprivate extension EnumCases {\n func allPayloadsAreTrivial(in function: Function) -> Bool {\n allSatisfy({ $0.payload?.isTrivial(in: function) ?? true })\n }\n}\n\nprivate extension NominalFieldsArray {\n func allFieldsAreTrivial(in function: Function) -> Bool {\n allSatisfy({ $0.isTrivial(in: function)})\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_Devirtualization.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_Devirtualization.swift
Swift
9,875
0.95
0.153558
0.117647
awesome-app
979
2024-06-28T03:44:45.974845
MIT
false
4d2094feadcc3a1dfa7850511999b0e9
//===--- EscapeUtils.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// This file provides utilities for transitively visiting all uses of a value.\n// The most common use case is to check if a value "escapes" to some destination\n// (e.g. an instruction) or if it "escapes" the current function at all.\n//\n// The APIs on `Value` and/or `ProjectedValue` are\n// * `isEscaping(using:)`\n// * `isEscapingWhenWalkingDown(using:)`\n// * `visit(using:)`\n// * `visitByWalkingDown(using:)`\n//\n// where a `EscapeVisitor` can be passed to the `using` argument to configure\n// the visit.\n//\n// The term "escaping" means that the "bit pattern" of the value is visible\n// at the destination. For example, in stack promotion we check if a reference to\n// an allocated object can escape it's function, i.e. if the bit pattern of the\n// reference can be visible outside it's function.\n// But it's also possible to check the "escapeness" of trivial values, e.g. an\n// `Int`. An `Int` escapes if its bit pattern is visible at the destination.\n// Though, by default trivial values are ignored. This can be configured with\n// `EscapeVisitor.followTrivialTypes`.\n//\n// By default, there is no distinction between addresses and value-type values.\n// Even if the value in question has an address type, it's considered escaping\n// if the stored value is escaping.\n// This can be configured with `EscapeVisitor.followLoads`.\n//\n// The visit algorithm works by starting a walk at the value and alternately\n// walking in two directions:\n// * Starting at root definitions, like allocations: walks down from defs to uses\n// ("Where does the value go to?")\n// * Starting at stores, walks up from uses to defs\n// ("Were does the value come from?")\n//\n// The value "escapes" if the walk reaches a point where the further flow of the value\n// cannot be tracked anymore.\n// Example:\n// \code\n// %1 = alloc_ref $X // 1. initial value: walk down to the `store`\n// %2 = alloc_stack $X // 3. walk down to %3\n// store %1 to %2 // 2. walk up to `%2`\n// %3 = load %2 // 4. continue walking down to the `return`\n// return %3 // 5. The value is escaping!\n// \endcode\n//\n// The traversal stops at points where the current path doesn't match the original projection.\n// For example, let's assume this function is called on a projected value with path `s0.c1`.\n// \code\n// %value : $Struct<X> // current path == s0.c1, the initial value\n// %ref = struct_extract %value, #field0 // current path == c1\n// %addr = ref_element_addr %ref, #field2 // mismatch: `c1` != `c2` -> ignored\n// \endcode\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nextension ProjectedValue {\n\n /// Returns true if the projected value escapes.\n ///\n /// The provided `visitor` can be used to override the handling a certain defs and uses during\n /// the walk. See `EscapeVisitor` for details.\n ///\n func isEscaping(\n using visitor: some EscapeVisitor = DefaultVisitor(),\n initialWalkingDirection: EscapeUtilityTypes.WalkingDirection = .up,\n complexityBudget: Int = Int.max,\n _ context: some Context\n ) -> Bool {\n var walker = EscapeWalker(visitor: visitor, complexityBudget: complexityBudget, context)\n let result: WalkResult\n switch initialWalkingDirection {\n case .up: result = walker.walkUp(addressOrValue: value, path: path.escapePath)\n case .down: result = walker.walkDown(addressOrValue: value, path: path.escapePath)\n }\n return result == .abortWalk\n }\n\n /// Returns the result of the visitor if the projected value does not escape.\n ///\n /// This function is similar to `isEscaping() -> Bool`, but instead of returning a Bool,\n /// it returns the `result` of the `visitor`, if the projected value does not escape.\n /// Returns nil, if the projected value escapes.\n ///\n func visit<V: EscapeVisitorWithResult>(\n using visitor: V,\n initialWalkingDirection: EscapeUtilityTypes.WalkingDirection = .up,\n complexityBudget: Int = Int.max,\n _ context: some Context\n ) -> V.Result? {\n var walker = EscapeWalker(visitor: visitor, complexityBudget: complexityBudget, context)\n let result: WalkResult\n switch initialWalkingDirection {\n case .up: result = walker.walkUp(addressOrValue: value, path: path.escapePath)\n case .down: result = walker.walkDown(addressOrValue: value, path: path.escapePath)\n }\n if result == .abortWalk {\n walker.visitor.cleanupOnAbort()\n return nil\n }\n return walker.visitor.result\n }\n}\n\nextension Value {\n /// The un-projected version of `ProjectedValue.isEscaping()`.\n func isEscaping(\n using visitor: some EscapeVisitor = DefaultVisitor(),\n initialWalkingDirection: EscapeUtilityTypes.WalkingDirection = .up,\n _ context: some Context\n ) -> Bool {\n return self.at(SmallProjectionPath()).isEscaping(using: visitor,\n initialWalkingDirection: initialWalkingDirection,\n context)\n }\n\n /// The un-projected version of `ProjectedValue.visit()`.\n func visit<V: EscapeVisitorWithResult>(\n using visitor: V,\n initialWalkingDirection: EscapeUtilityTypes.WalkingDirection = .up,\n _ context: some Context\n ) -> V.Result? {\n return self.at(SmallProjectionPath()).visit(using: visitor,\n initialWalkingDirection: initialWalkingDirection,\n context)\n }\n}\n\n/// This protocol is used to customize `ProjectedValue.isEscaping` (and similar functions)\n/// by implementing `visitUse` and `visitDef` which are called for all uses and definitions\n/// encountered during a walk.\nprotocol EscapeVisitor {\n typealias UseResult = EscapeUtilityTypes.UseVisitResult\n typealias DefResult = EscapeUtilityTypes.DefVisitResult\n typealias EscapePath = EscapeUtilityTypes.EscapePath\n \n /// Called during the DefUse walk for each use\n mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult\n \n /// Called during the UseDef walk for each definition\n mutating func visitDef(def: Value, path: EscapePath) -> DefResult\n\n /// If true, the traversals follow values with trivial types.\n var followTrivialTypes: Bool { get }\n\n /// If true, the traversal follows loaded values.\n var followLoads: Bool { get }\n}\n\nextension EscapeVisitor {\n mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {\n return .continueWalk\n }\n\n mutating func visitDef(def: Value, path: EscapePath) -> DefResult {\n return .continueWalkUp\n }\n\n var followTrivialTypes: Bool { false }\n\n var followLoads: Bool { true }\n}\n\n/// A visitor which returns a `result`.\nprotocol EscapeVisitorWithResult : EscapeVisitor {\n associatedtype Result\n var result: Result { get }\n\n mutating func cleanupOnAbort()\n}\n\nextension EscapeVisitorWithResult {\n mutating func cleanupOnAbort() {}\n}\n\n// FIXME: This ought to be marked private, but that triggers a compiler bug\n// in debug builds (rdar://117413192)\nstruct DefaultVisitor : EscapeVisitor {}\n\nstruct EscapeUtilityTypes {\n\n enum WalkingDirection {\n case up\n case down\n }\n\n /// The EscapePath is updated and maintained during the up-walk and down-walk.\n ///\n /// It's passed to the EscapeVisitor's `visitUse` and `visitDef`.\n struct EscapePath: SmallProjectionWalkingPath {\n /// During the walk, a projection path indicates where the initial value is\n /// contained in an aggregate.\n /// Example for a walk-down:\n /// \code\n /// %1 = alloc_ref // 1. initial value, path = empty\n /// %2 = struct $S (%1) // 2. path = s0\n /// %3 = tuple (%other, %1) // 3. path = t1.s0\n /// %4 = tuple_extract %3, 1 // 4. path = s0\n /// %5 = struct_extract %4, #field // 5. path = empty\n /// \endcode\n ///\n let projectionPath: SmallProjectionPath\n\n /// This flag indicates if stored values should be included in the walk.\n /// If the initial value is stored to some memory allocation, we usually don't\n /// care if other values are stored to that location as well. Example:\n /// \code\n /// %1 = alloc_ref $X // 1. initial value, walk down to the `store`\n /// %2 = alloc_stack $X // 3. walk down to the second `store`\n /// store %1 to %2 // 2. walk up to %2\n /// store %other to %2 // 4. ignore (followStores == false): %other doesn't impact the "escapeness" of %1\n /// \endcode\n ///\n /// But once the up-walk sees a load, it has to follow stores from that point on.\n /// Example:\n /// \code\n /// bb0(%function_arg): // 7. escaping! %1 escapes through %function_arg\n /// %1 = alloc_ref $X // 1. initial value, walk down to the second `store`\n /// %addr = alloc_stack %X // 5. walk down to the first `store`\n /// store %function_arg to %addr // 6. walk up to %function_arg (followStores == true)\n /// %2 = load %addr // 4. walk up to %addr, followStores = true\n /// %3 = ref_element_addr %2, #f // 3. walk up to %2\n /// store %1 to %3 // 2. walk up to %3\n /// \endcode\n ///\n let followStores: Bool\n\n /// Set to true if an address is stored.\n /// This unusual situation can happen if an address is converted to a raw pointer and that pointer\n /// is stored to a memory location.\n /// In this case the walkers need to follow load instructions even if the visitor and current projection\n /// path don't say so.\n let addressIsStored: Bool\n\n /// Not nil, if the exact type of the current value is know.\n ///\n /// This is used for destructor analysis.\n /// Example:\n /// \code\n /// %1 = alloc_ref $Derived // 1. initial value, knownType = $Derived\n /// %2 = upcast %1 to $Base // 2. knownType = $Derived\n /// destroy_value %2 : $Base // 3. We know that the destructor of $Derived is called here\n /// \endcode\n let knownType: Type?\n\n func with(projectionPath: SmallProjectionPath) -> Self {\n return Self(projectionPath: projectionPath, followStores: self.followStores,\n addressIsStored: self.addressIsStored, knownType: self.knownType)\n }\n\n func with(followStores: Bool) -> Self {\n return Self(projectionPath: self.projectionPath, followStores: followStores,\n addressIsStored: self.addressIsStored, knownType: self.knownType)\n }\n \n func with(addressStored: Bool) -> Self {\n return Self(projectionPath: self.projectionPath, followStores: self.followStores, addressIsStored: addressStored,\n knownType: self.knownType)\n }\n\n func with(knownType: Type?) -> Self {\n return Self(projectionPath: self.projectionPath, followStores: self.followStores,\n addressIsStored: self.addressIsStored, knownType: knownType)\n }\n \n func merge(with other: EscapePath) -> EscapePath {\n let mergedPath = self.projectionPath.merge(with: other.projectionPath)\n let mergedFollowStores = self.followStores || other.followStores\n let mergedAddrStored = self.addressIsStored || other.addressIsStored\n let mergedKnownType: Type?\n if let ty = self.knownType {\n if let otherTy = other.knownType, ty != otherTy {\n mergedKnownType = nil\n } else {\n mergedKnownType = ty\n }\n } else {\n mergedKnownType = other.knownType\n }\n return EscapePath(projectionPath: mergedPath, followStores: mergedFollowStores,\n addressIsStored: mergedAddrStored, knownType: mergedKnownType)\n }\n }\n \n enum DefVisitResult {\n case ignore\n case continueWalkUp\n case walkDown\n case abort\n }\n\n enum UseVisitResult {\n case ignore\n case continueWalk\n case abort\n }\n}\n\n/// EscapeWalker is both a DefUse walker and UseDef walker. It implements both, the up-, and down-walk.\nfileprivate struct EscapeWalker<V: EscapeVisitor> : ValueDefUseWalker,\n AddressDefUseWalker,\n ValueUseDefWalker,\n AddressUseDefWalker {\n typealias Path = EscapeUtilityTypes.EscapePath\n \n init(visitor: V, complexityBudget: Int = Int.max, _ context: some Context) {\n self.calleeAnalysis = context.calleeAnalysis\n self.visitor = visitor\n self.complexityBudget = complexityBudget\n }\n\n //===--------------------------------------------------------------------===//\n // Walking down\n //===--------------------------------------------------------------------===//\n \n mutating func walkDown(addressOrValue: Value, path: Path) -> WalkResult {\n if addressOrValue.type.isAddress {\n return walkDownUses(ofAddress: addressOrValue, path: path)\n } else {\n return walkDownUses(ofValue: addressOrValue, path: path)\n }\n }\n \n mutating func cachedWalkDown(addressOrValue: Value, path: Path) -> WalkResult {\n if let path = walkDownCache.needWalk(for: addressOrValue, path: path) {\n return walkDown(addressOrValue: addressOrValue, path: path)\n } else {\n return .continueWalk\n }\n }\n \n mutating func walkDown(value: Operand, path: Path) -> WalkResult {\n if complexityBudgetExceeded(value.value) {\n return .abortWalk\n }\n if hasRelevantType(value.value, at: path.projectionPath) {\n switch visitor.visitUse(operand: value, path: path) {\n case .continueWalk:\n return walkDownDefault(value: value, path: path)\n case .ignore:\n return .continueWalk\n case .abort:\n return .abortWalk\n }\n }\n return .continueWalk\n }\n \n /// ``ValueDefUseWalker`` conformance: called when the value def-use walk can't continue,\n /// i.e. when the result of the use is not a value.\n mutating func leafUse(value operand: Operand, path: Path) -> WalkResult {\n let instruction = operand.instruction\n switch instruction {\n case let rta as RefTailAddrInst:\n if let path = pop(.tailElements, from: path, yielding: rta) {\n return walkDownUses(ofAddress: rta, path: path.with(knownType: nil))\n }\n case let rea as RefElementAddrInst:\n if let path = pop(.classField, index: rea.fieldIndex, from: path, yielding: rea) {\n return walkDownUses(ofAddress: rea, path: path.with(knownType: nil))\n }\n case let pb as ProjectBoxInst:\n if let path = pop(.classField, index: pb.fieldIndex, from: path, yielding: pb) {\n return walkDownUses(ofAddress: pb, path: path.with(knownType: nil))\n }\n case is StoreInst, is StoreWeakInst, is StoreUnownedInst:\n let store = instruction as! StoringInstruction\n assert(operand == store.sourceOperand)\n if !followLoads(at: path) {\n return walkUp(address: store.destination, path: path.with(addressStored: true))\n }\n return walkUp(address: store.destination, path: path)\n case is DestroyValueInst, is ReleaseValueInst, is StrongReleaseInst:\n if handleDestroy(of: operand.value, path: path) == .abortWalk {\n return .abortWalk\n }\n case is ReturnInst:\n return isEscaping\n case is ApplyInst, is TryApplyInst, is BeginApplyInst:\n return walkDownCallee(argOp: operand, apply: instruction as! FullApplySite, path: path)\n case let pai as PartialApplyInst:\n // Check whether the partially applied argument can escape in the body.\n if walkDownCallee(argOp: operand, apply: pai, path: path.with(knownType: nil)) == .abortWalk {\n return .abortWalk\n }\n \n // Additionally we need to follow the partial_apply value for two reasons:\n // 1. the closure (with the captured values) itself can escape\n // and the use "transitively" escapes\n // 2. something can escape in a destructor when the context is destroyed\n return walkDownUses(ofValue: pai, path: path.with(knownType: nil))\n case let pta as PointerToAddressInst:\n return walkDownUses(ofAddress: pta, path: path.with(knownType: nil))\n case let cv as ConvertFunctionInst:\n return walkDownUses(ofValue: cv, path: path.with(knownType: nil))\n case let bi as BuiltinInst:\n switch bi.id {\n case .DestroyArray:\n // If it's not the array base pointer operand -> bail. Though, that shouldn't happen\n // because the other operands (metatype, count) shouldn't be visited anyway.\n if operand.index != 1 { return isEscaping }\n \n // Class references, which are directly located in the array elements cannot escape,\n // because those are passed as `self` to their deinits - and `self` cannot escape in a deinit.\n if !path.projectionPath.mayHaveClassProjection {\n return .continueWalk\n }\n return isEscaping\n\n case .AtomicLoad:\n // Treat atomic loads as regular loads and just walk down their uses.\n if !followLoads(at: path) {\n return .continueWalk\n }\n\n // Even when analyzing atomics, a loaded trivial value can be ignored.\n if hasRelevantType(bi, at: path.projectionPath) {\n return .continueWalk\n }\n\n return walkDownUses(ofValue: bi, path: path.with(knownType: nil))\n\n case .AtomicStore, .AtomicRMW:\n // If we shouldn't follow the store, then we can keep walking.\n if !path.followStores {\n return .continueWalk\n }\n\n // Be conservative and just say the store is escaping.\n return isEscaping\n\n case .CmpXChg:\n // If we have to follow loads or stores of a cmpxchg, then just bail.\n if followLoads(at: path) || path.followStores {\n return isEscaping\n }\n\n return .continueWalk\n\n case .Fence:\n // Fences do not affect escape analysis.\n return .continueWalk\n\n default:\n return isEscaping\n }\n case is StrongRetainInst, is RetainValueInst, is DebugValueInst, is ValueMetatypeInst,\n is InitExistentialMetatypeInst, is OpenExistentialMetatypeInst,\n is ExistentialMetatypeInst, is DeallocRefInst, is FixLifetimeInst,\n is ClassifyBridgeObjectInst, is BridgeObjectToWordInst, is EndBorrowInst,\n is StrongRetainInst, is RetainValueInst,\n is ClassMethodInst, is SuperMethodInst, is ObjCMethodInst,\n is ObjCSuperMethodInst, is WitnessMethodInst, is DeallocStackRefInst:\n return .continueWalk\n case is DeallocStackInst:\n // dealloc_stack %f : $@noescape @callee_guaranteed () -> ()\n // type is a value\n assert(operand.value.definingInstruction is PartialApplyInst)\n return .continueWalk\n default:\n return isEscaping\n }\n return .continueWalk\n }\n \n mutating func walkDown(address: Operand, path: Path) -> WalkResult {\n if complexityBudgetExceeded(address.value) {\n return .abortWalk\n }\n if hasRelevantType(address.value, at: path.projectionPath) {\n switch visitor.visitUse(operand: address, path: path) {\n case .continueWalk:\n return walkDownDefault(address: address, path: path)\n case .ignore:\n return .continueWalk\n case .abort:\n return .abortWalk\n }\n }\n return .continueWalk\n }\n \n /// ``AddressDefUseWalker`` conformance: called when the address def-use walk can't continue,\n /// i.e. when the result of the use is not an address.\n mutating func leafUse(address operand: Operand, path: Path) -> WalkResult {\n let instruction = operand.instruction\n switch instruction {\n case is StoreInst, is StoreWeakInst, is StoreUnownedInst:\n let store = instruction as! StoringInstruction\n assert(operand == store.destinationOperand)\n if let si = store as? StoreInst, si.storeOwnership == .assign {\n if handleDestroy(of: operand.value, path: path.with(knownType: nil)) == .abortWalk {\n return .abortWalk\n }\n }\n if path.followStores {\n return walkUp(value: store.source, path: path)\n }\n case let storeBorrow as StoreBorrowInst:\n assert(operand == storeBorrow.destinationOperand)\n return walkDownUses(ofAddress: storeBorrow, path: path)\n case let copyAddr as CopyAddrInst:\n if !followLoads(at: path) {\n return .continueWalk\n }\n if operand == copyAddr.sourceOperand {\n return walkUp(address: copyAddr.destination, path: path)\n } else {\n if !copyAddr.isInitializationOfDest {\n if handleDestroy(of: operand.value, path: path.with(knownType: nil)) == .abortWalk {\n return .abortWalk\n }\n }\n \n if path.followStores {\n assert(operand == copyAddr.destinationOperand)\n return walkUp(value: copyAddr.source, path: path)\n }\n }\n case is DestroyAddrInst:\n if handleDestroy(of: operand.value, path: path) == .abortWalk {\n return .abortWalk\n }\n case is ReturnInst:\n return isEscaping\n case is ApplyInst, is TryApplyInst, is BeginApplyInst:\n return walkDownCallee(argOp: operand, apply: instruction as! FullApplySite, path: path)\n case let pai as PartialApplyInst:\n if walkDownCallee(argOp: operand, apply: pai, path: path.with(knownType: nil)) == .abortWalk {\n return .abortWalk\n }\n\n // We need to follow the partial_apply value for two reasons:\n // 1. the closure (with the captured values) itself can escape\n // 2. something can escape in a destructor when the context is destroyed\n if followLoads(at: path) || pai.capturesAddress(of: operand) {\n return walkDownUses(ofValue: pai, path: path.with(knownType: nil))\n }\n case is LoadInst, is LoadWeakInst, is LoadUnownedInst, is LoadBorrowInst:\n if !followLoads(at: path) {\n return .continueWalk\n }\n let svi = instruction as! SingleValueInstruction\n \n // Even when analyzing addresses, a loaded trivial value can be ignored.\n if svi.hasTrivialNonPointerType { return .continueWalk }\n return walkDownUses(ofValue: svi, path: path.with(knownType: nil))\n case let atp as AddressToPointerInst:\n return walkDownUses(ofValue: atp, path: path.with(knownType: nil))\n case is DeallocStackInst, is InjectEnumAddrInst, is FixLifetimeInst, is EndBorrowInst, is EndAccessInst,\n is IsUniqueInst, is DebugValueInst:\n return .continueWalk\n case let uac as UncheckedAddrCastInst:\n if uac.type != uac.fromAddress.type {\n // It's dangerous to continue walking over an `unchecked_addr_cast` which casts between two different types.\n // We can only do this if the result is known to be the end of the walk, i.e. the cast result is not used\n // in a relevant way.\n for uacUse in uac.uses {\n // Following instructions turned out to appear in code coming from the stdlib.\n switch uacUse.instruction {\n case is IsUniqueInst:\n break\n case is LoadInst, is LoadBorrowInst, is ApplyInst, is TryApplyInst:\n if followLoads(at: path) {\n return .abortWalk\n }\n default:\n return .abortWalk\n }\n }\n }\n return walkDownUses(ofAddress: uac, path: path)\n default:\n return isEscaping\n }\n return .continueWalk\n }\n \n /// Check whether the value escapes through the deinitializer\n private func handleDestroy(of value: Value, path: Path) -> WalkResult {\n\n // Even if this is a destroy_value of a struct/tuple/enum, the called destructor(s) only take a\n // single class reference as parameter.\n let p = path.projectionPath.popAllValueFields()\n\n if p.isEmpty {\n // The object to destroy (= the argument of the destructor) cannot escape itself.\n return .continueWalk\n }\n if !visitor.followLoads && p.matches(pattern: SmallProjectionPath(.anyValueFields).push(.anyClassField)) {\n // Any address of a class property of the object to destroy cannot escape the destructor.\n // (Whereas a value stored in such a property could escape.)\n return .continueWalk\n }\n\n if path.followStores {\n return isEscaping\n }\n if let exactTy = path.knownType {\n guard let destructor = calleeAnalysis.getDestructor(ofExactType: exactTy) else {\n return isEscaping\n }\n if destructor.effects.escapeEffects.canEscape(argumentIndex: 0, path: pathForArgumentEscapeChecking(p)) {\n return isEscaping\n }\n } else {\n // We don't know the exact type, so get all possible called destructure from\n // the callee analysis.\n guard let destructors = calleeAnalysis.getDestructors(of: value.type) else {\n return isEscaping\n }\n for destructor in destructors {\n if destructor.effects.escapeEffects.canEscape(argumentIndex: 0, path: pathForArgumentEscapeChecking(p)) {\n return isEscaping\n }\n }\n }\n return .continueWalk\n }\n \n /// Handle an apply (full or partial) during the walk-down.\n private mutating\n func walkDownCallee(argOp: Operand, apply: ApplySite, path: Path) -> WalkResult {\n guard let calleeArgIdx = apply.calleeArgumentIndex(of: argOp) else {\n // The callee or a type dependent operand of the apply does not let escape anything.\n return .continueWalk\n }\n\n // Indirect arguments cannot escape the function, but loaded values from such can.\n if !followLoads(at: path) {\n if let beginApply = apply as? BeginApplyInst {\n // begin_apply can yield an address value.\n if !indirectResultEscapes(of: beginApply, path: path) {\n return .continueWalk\n }\n } else if !apply.isAddressable(operand: argOp) {\n // The result does not depend on the argument's address.\n return .continueWalk\n }\n }\n\n if argOp.value.type.isNoEscapeFunction {\n // Per definition a `partial_apply [on_stack]` cannot escape the callee.\n // Potential escapes of its captured values are already handled when visiting the `partial_apply`.\n return .continueWalk\n }\n\n // Argument effects do not consider any potential stores to the argument (or it's content).\n // Therefore, if we need to track stores, the argument effects do not correctly describe what we need.\n // For example, argument 0 in the following function is marked as not-escaping, although there\n // is a store to the argument:\n //\n // sil [escapes !%0.**] @callee(@inout X, @owned X) -> () {\n // bb0(%0 : $*X, %1 : $X):\n // store %1 to %0 : $*X\n // }\n if path.followStores {\n return isEscaping\n }\n\n guard let callees = calleeAnalysis.getCallees(callee: apply.callee) else {\n // The callees are not know, e.g. if the callee is a closure, class method, etc.\n return isEscaping\n }\n\n for callee in callees {\n let effects = callee.effects\n if !effects.escapeEffects.canEscape(argumentIndex: calleeArgIdx,\n path: pathForArgumentEscapeChecking(path.projectionPath)) {\n continue\n }\n if walkDownArgument(calleeArgIdx: calleeArgIdx, argPath: path,\n apply: apply, effects: effects) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n\n private mutating func indirectResultEscapes(of beginApply: BeginApplyInst, path: Path) -> Bool {\n for result in beginApply.yieldedValues where result.type.isAddress {\n if walkDownUses(ofAddress: result, path: path) == .abortWalk {\n return true\n }\n }\n return false\n }\n\n /// Handle `.escaping` effects for an apply argument during the walk-down.\n private mutating\n func walkDownArgument(calleeArgIdx: Int, argPath: Path,\n apply: ApplySite, effects: FunctionEffects) -> WalkResult {\n var matched = false\n for effect in effects.escapeEffects.arguments {\n switch effect.kind {\n case .escapingToArgument(let toArgIdx, let toPath):\n // Note: exclusive argument -> argument effects cannot appear, so we don't need to handle them here.\n if effect.matches(calleeArgIdx, argPath.projectionPath) {\n guard let argOp = apply.operand(forCalleeArgumentIndex: toArgIdx) else {\n return isEscaping\n }\n\n // Continue at the destination of an arg-to-arg escape.\n let arg = argOp.value\n \n let p = Path(projectionPath: toPath, followStores: false, addressIsStored: argPath.addressIsStored,\n knownType: nil)\n if walkUp(addressOrValue: arg, path: p) == .abortWalk {\n return .abortWalk\n }\n matched = true\n }\n case .escapingToReturn(let toPath, let exclusive):\n if effect.matches(calleeArgIdx, argPath.projectionPath) {\n guard let fas = apply as? FullApplySite, let result = fas.singleDirectResult else {\n return isEscaping\n }\n\n let p = Path(projectionPath: toPath, followStores: false, addressIsStored: argPath.addressIsStored,\n knownType: exclusive ? argPath.knownType : nil)\n\n if walkDownUses(ofValue: result, path: p) == .abortWalk {\n return .abortWalk\n }\n matched = true\n }\n case .notEscaping:\n break\n }\n }\n if !matched { return isEscaping }\n return .continueWalk\n }\n \n //===--------------------------------------------------------------------===//\n // Walking up\n //===--------------------------------------------------------------------===//\n \n mutating func walkUp(addressOrValue: Value, path: Path) -> WalkResult {\n if addressOrValue.type.isAddress {\n return walkUp(address: addressOrValue, path: path)\n } else {\n return walkUp(value: addressOrValue, path: path)\n }\n }\n \n mutating func walkUp(value: Value, path: Path) -> WalkResult {\n if complexityBudgetExceeded(value) {\n return .abortWalk\n }\n if hasRelevantType(value, at: path.projectionPath) {\n switch visitor.visitDef(def: value, path: path) {\n case .continueWalkUp:\n return walkUpDefault(value: value, path: path)\n case .walkDown:\n return cachedWalkDown(addressOrValue: value, path: path.with(knownType: nil))\n case .ignore:\n return .continueWalk\n case .abort:\n return .abortWalk\n }\n }\n return .continueWalk\n }\n \n /// ``ValueUseDefWalker`` conformance: called when the value use-def walk can't continue,\n /// i.e. when the operand (if any) of the instruction of a definition is not a value.\n mutating func rootDef(value def: Value, path: Path) -> WalkResult {\n switch def {\n case is AllocRefInst, is AllocRefDynamicInst:\n return cachedWalkDown(addressOrValue: def, path: path.with(knownType: def.type))\n case is AllocBoxInst:\n return cachedWalkDown(addressOrValue: def, path: path.with(knownType: nil))\n case let arg as Argument:\n guard let termResult = TerminatorResult(arg) else { return isEscaping }\n switch termResult.terminator {\n case let ta as TryApplyInst:\n if termResult.successor != ta.normalBlock { return isEscaping }\n return walkUpApplyResult(apply: ta, path: path.with(knownType: nil))\n default:\n return isEscaping\n }\n case let ap as ApplyInst:\n return walkUpApplyResult(apply: ap, path: path.with(knownType: nil))\n case is LoadInst, is LoadWeakInst, is LoadUnownedInst, is LoadBorrowInst:\n if !followLoads(at: path) {\n // When walking up we shouldn't end up at a load where followLoads is false,\n // because going from a (non-followLoads) address to a load always involves a class indirection.\n // There is one exception: loading a raw pointer, e.g.\n // %l = load %a : $Builtin.RawPointer\n // %a = pointer_to_address %l // the up-walk starts at %a\n return isEscaping\n }\n return walkUp(address: (def as! UnaryInstruction).operand.value,\n path: path.with(followStores: true).with(knownType: nil))\n case let atp as AddressToPointerInst:\n return walkUp(address: atp.address, path: path.with(knownType: nil))\n default:\n return isEscaping\n }\n }\n \n mutating func walkUp(address: Value, path: Path) -> WalkResult {\n if complexityBudgetExceeded(address) {\n return .abortWalk\n }\n if hasRelevantType(address, at: path.projectionPath) {\n switch visitor.visitDef(def: address, path: path) {\n case .continueWalkUp:\n return walkUpDefault(address: address, path: path)\n case .walkDown:\n return cachedWalkDown(addressOrValue: address, path: path)\n case .ignore:\n return .continueWalk\n case .abort:\n return .abortWalk\n }\n }\n return .continueWalk\n }\n \n /// ``AddressUseDefWalker`` conformance: called when the address use-def walk can't continue,\n /// i.e. when the operand (if any) of the instruction of a definition is not an address.\n mutating func rootDef(address def: Value, path: Path) -> WalkResult {\n switch def {\n case is AllocStackInst:\n return cachedWalkDown(addressOrValue: def, path: path.with(knownType: nil))\n case let arg as FunctionArgument:\n if !followLoads(at: path) && arg.convention.isExclusiveIndirect && !path.followStores {\n return cachedWalkDown(addressOrValue: def, path: path.with(knownType: nil))\n } else {\n return isEscaping\n }\n case is PointerToAddressInst:\n return walkUp(value: (def as! SingleValueInstruction).operands[0].value, path: path.with(knownType: nil))\n case let rta as RefTailAddrInst:\n return walkUp(value: rta.instance, path: path.push(.tailElements, index: 0).with(knownType: nil))\n case let rea as RefElementAddrInst:\n return walkUp(value: rea.instance, path: path.push(.classField, index: rea.fieldIndex).with(knownType: nil))\n case let pb as ProjectBoxInst:\n return walkUp(value: pb.box, path: path.push(.classField, index: pb.fieldIndex).with(knownType: nil))\n case let storeBorrow as StoreBorrowInst:\n return walkUp(address: storeBorrow.destination, path: path)\n default:\n return isEscaping\n }\n }\n \n /// Walks up from the return to the source argument if there is an "exclusive"\n /// escaping effect on an argument.\n private mutating\n func walkUpApplyResult(apply: FullApplySite,\n path: Path) -> WalkResult {\n guard let callees = calleeAnalysis.getCallees(callee: apply.callee) else {\n return .abortWalk\n }\n\n for callee in callees {\n var matched = false\n for effect in callee.effects.escapeEffects.arguments {\n switch effect.kind {\n case .escapingToReturn(let toPath, let exclusive):\n if exclusive && path.projectionPath.matches(pattern: toPath) {\n guard let argOp = apply.operand(forCalleeArgumentIndex: effect.argumentIndex) else {\n return .abortWalk\n }\n let arg = argOp.value\n \n let p = Path(projectionPath: effect.pathPattern, followStores: path.followStores,\n addressIsStored: path.addressIsStored, knownType: nil)\n if walkUp(addressOrValue: arg, path: p) == .abortWalk {\n return .abortWalk\n }\n matched = true\n }\n case .notEscaping, .escapingToArgument:\n break\n }\n }\n if !matched {\n return isEscaping\n }\n }\n return .continueWalk\n }\n \n //===--------------------------------------------------------------------===//\n // private state\n //===--------------------------------------------------------------------===//\n\n var visitor: V\n\n // The caches are not only useful for performance, but are need to avoid infinite\n // recursions of walkUp-walkDown cycles.\n var walkDownCache = WalkerCache<Path>()\n var walkUpCache = WalkerCache<Path>()\n\n // Only this number of up/and down walks are done until the walk aborts.\n // Used to avoid quadratic complexity in some scenarios.\n var complexityBudget: Int\n\n private let calleeAnalysis: CalleeAnalysis\n \n //===--------------------------------------------------------------------===//\n // private utility functions\n //===--------------------------------------------------------------------===//\n\n /// Tries to pop the given projection from path, if the projected `value` has a relevant type.\n private func pop(_ kind: Path.FieldKind, index: Int? = nil, from path: Path, yielding value: Value) -> Path? {\n if let newPath = path.popIfMatches(kind, index: index),\n hasRelevantType(value, at: newPath.projectionPath) {\n return newPath\n }\n return nil\n }\n\n private func hasRelevantType(_ value: Value, at path: SmallProjectionPath) -> Bool {\n if visitor.followTrivialTypes &&\n // When part of a class field only need to follow non-trivial types\n !path.hasClassProjection {\n return true\n }\n if !value.hasTrivialNonPointerType {\n return true\n }\n return false\n }\n\n private func followLoads(at path: Path) -> Bool {\n return visitor.followLoads ||\n // When part of a class field we have to follow loads.\n path.projectionPath.mayHaveClassProjection ||\n path.addressIsStored\n }\n\n private func pathForArgumentEscapeChecking(_ path: SmallProjectionPath) -> SmallProjectionPath {\n if visitor.followLoads {\n return path\n }\n return path.popLastClassAndValuesFromTail()\n }\n\n private mutating func complexityBudgetExceeded(_ v: Value) -> Bool {\n if complexityBudget <= 0 {\n return true\n }\n complexityBudget = complexityBudget &- 1\n return false\n }\n\n // Set a breakpoint here to debug when a value is escaping.\n private var isEscaping: WalkResult { .abortWalk }\n}\n\nprivate extension SmallProjectionPath {\n var escapePath: EscapeUtilityTypes.EscapePath {\n EscapeUtilityTypes.EscapePath(projectionPath: self, followStores: false, addressIsStored: false, knownType: nil)\n }\n}\n\nprivate extension PartialApplyInst {\n func capturesAddress(of operand: Operand) -> Bool {\n assert(operand.value.type.isAddress)\n guard let conv = convention(of: operand) else {\n fatalError("callee operand of partial_apply cannot have address type")\n }\n switch conv {\n case .indirectIn, .indirectInGuaranteed:\n // A partial_apply copies the values from indirect-in arguments, but does not capture the address.\n return false\n case .indirectInout, .indirectInoutAliasable, .packInout:\n return true\n case .directOwned, .directUnowned, .directGuaranteed, .packOwned, .packGuaranteed:\n fatalError("invalid convention for address operand")\n case .indirectOut, .packOut, .indirectInCXX:\n fatalError("invalid convention for partial_apply")\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_EscapeUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_EscapeUtils.swift
Swift
39,444
0.95
0.170363
0.255011
awesome-app
785
2023-10-09T00:39:10.698222
Apache-2.0
false
6ef571e8a39543775cd719714fd0721f
//===--- ForwardingUtils.swift - Utilities for ownership forwarding -------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n///\n/// TODO: Once the hasPointerEscape flags are implemented for\n/// BeginBorrowInst, MoveValueInst, and Allocation,\n/// ForwardingUseDefWalker should be used to check whether any value\n/// is part of a forward-extended lifetime that has a pointer escape.\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(_ message: @autoclosure () -> String) {\n if verbose {\n print("### \(message())")\n }\n}\n\n/// Return true if any use in `value`s forward-extend lifetime has\n/// .pointerEscape operand ownership.\n///\n/// TODO: the C++ implementation does not yet gather all\n/// forward-extended lifetime introducers.\n///\n/// TODO: Add [pointer_escape] flags to MoveValue, BeginBorrow, and\n/// Allocation. Then add a `Value.hasPointerEscapingUse` property that\n/// performs the use-def walk to pickup the flags. Then only call into\n/// this def-use walk to initially set the flags.\nfunc findPointerEscapingUse(of value: Value) -> Bool {\n value.bridged.findPointerEscape()\n}\n\n/// Visit the introducers of a forwarded lifetime (Value -> LifetimeIntroducer).\n///\n/// A lifetime introducer produces an initial OSSA lifetime which may\n/// be extended by forwarding instructions. The introducer is never\n/// itself the result of a ForwardingInstruction. Example:\n///\n/// # lifetime introducer\n/// %1 = apply -+ -+\n/// ... | OSSA lifetime |\n/// # forwarding instruction | |\n/// %2 = struct $S (%1) -+ -+ | forward-extended lifetime\n/// | OSSA lifetime |\n/// # non-forwarding consumer | |\n/// destroy_value %2 -+ -+\n///\n/// The lifetime of a single owned value ends when it is forwarded,\n/// but certain lifetime properties are relevant for the entire\n/// forward-extended lifetime. For example, if an owned lifetime has a\n/// pointer-escaping use, then all values in the forward-extended\n/// lifetime are also considered pointer-escaping. Certain properties,\n/// like lexical lifetimes, only exist on the forward introducer and\n/// apply to all forwarded values.\n///\n/// Note: Although move_value conceptually forwards an owned value, it\n/// also summarizes lifetime attributes; therefore, it is not formally\n/// a ForwardingInstruction.\n///\n/// The lifetime introducer of a guaranteed value is the borrow introducer:\n///\n/// # lifetime introducer / borrow introducer\n/// %1 = begin_borrow -+\n/// ... | OSSA lifetime == forwarded lifetime\n/// # forwarding instruction |\n/// %2 = struct $S (%1) | - forwarded uses are within the OSSA lifetime\n/// |\n/// end_borrow %1 -+\n///\n/// TODO: When a begin_borrow has no lifetime flags, it can be ignored\n/// as a lifetime introducer. In that case, an owned value may\n/// introduce guaranteed OSSA lifetimes.\n///\n/// Forwarded lifetimes also extend through phis. In this case,\n/// however, there is no ForwardingInstruction.\n///\n/// # lifetime introducer\n/// %1 = apply -+ -+\n/// ... | OSSA lifetime |\n/// # phi operand | |\n/// br bbContinue(%1: $S) -+ | forward-extended lifetime\n/// |\n/// bbContinue(%phi : $S): -+ OSSA lifetime |\n/// ... | |\n/// destroy_value %phi -+ -+\n///\n/// TODO: when phi lifetime flags are implemented, phis will introduce\n/// a lifetime in the same way as move_value.\n///\n/// This walker is used to query basic lifetime attributes on values,\n/// such as "escaping" or "lexical". It must be precise for\n/// correctness and is performance critical.\nprotocol ForwardingUseDefWalker {\n associatedtype PathContext\n\n mutating func introducer(_ value: Value, _ path: PathContext) -> WalkResult\n\n // Minimally, check a ValueSet. This walker may traverse chains of\n // aggregation and destructuring along with phis.\n mutating func needWalk(for value: Value, _ path: PathContext) -> Bool\n\n mutating func walkUp(value: Value, _ path: PathContext) -> WalkResult\n}\n\nextension ForwardingUseDefWalker {\n mutating func walkUp(value: Value, _ path: PathContext) -> WalkResult {\n walkUpDefault(forwarded: value, path)\n }\n mutating func walkUpDefault(forwarded value: Value, _ path: PathContext)\n -> WalkResult {\n if let inst = value.forwardingInstruction {\n return walkUp(instruction: inst, path)\n }\n if let phi = Phi(value) {\n return walkUp(phi: phi, path)\n }\n return introducer(value, path)\n }\n mutating func walkUp(instruction: ForwardingInstruction, _ path: PathContext)\n -> WalkResult {\n for operand in instruction.forwardedOperands {\n if needWalk(for: operand.value, path) {\n if walkUp(value: operand.value, path) == .abortWalk {\n return .abortWalk\n }\n }\n }\n return .continueWalk\n }\n mutating func walkUp(phi: Phi, _ path: PathContext) -> WalkResult {\n for operand in phi.incomingOperands {\n if needWalk(for: operand.value, path) {\n if walkUp(value: operand.value, path) == .abortWalk {\n return .abortWalk\n }\n }\n }\n return .continueWalk\n }\n}\n\n// This conveniently gathers all forward introducers and deinitializes\n// visitedValues before the caller has a chance to recurse.\nfunc gatherLifetimeIntroducers(for value: Value, _ context: Context) -> [Value] {\n var introducers: [Value] = []\n var walker = VisitLifetimeIntroducers(context) {\n introducers.append($0)\n return .continueWalk\n }\n defer { walker.deinitialize() }\n _ = walker.walkUp(value: value, ())\n return introducers\n}\n\n// TODO: visitor can be nonescaping when we have borrowed properties.\nfunc visitLifetimeIntroducers(for value: Value, _ context: Context,\n visitor: @escaping (Value) -> WalkResult)\n -> WalkResult {\n var walker = VisitLifetimeIntroducers(context, visitor: visitor)\n defer { walker.visitedValues.deinitialize() }\n return walker.walkUp(value: value, ())\n}\n\nprivate struct VisitLifetimeIntroducers : ForwardingUseDefWalker {\n var visitor: (Value) -> WalkResult\n var visitedValues: ValueSet\n \n init(_ context: Context, visitor: @escaping (Value) -> WalkResult) {\n self.visitor = visitor\n self.visitedValues = ValueSet(context)\n }\n \n mutating func deinitialize() { visitedValues.deinitialize() }\n\n mutating func needWalk(for value: Value, _: Void) -> Bool {\n visitedValues.insert(value)\n }\n\n mutating func introducer(_ value: Value, _: Void) -> WalkResult {\n visitor(value)\n }\n}\n\nenum ForwardingUseResult: CustomStringConvertible {\n case operand(Operand)\n case deadValue(Value, Operand?)\n\n var description: String {\n switch self {\n case .operand(let operand):\n return operand.description\n case .deadValue(let deadValue, let operand):\n var desc = "dead value: \(deadValue.description)"\n if let operand = operand {\n desc += "from: \(operand)"\n }\n return desc\n }\n }\n}\n\n/// Visit all the non-forwarding uses in a forward-extended lifetime\n/// (LifetimeIntroducer -> Operand).\n///\n/// Minimal requirements:\n/// needWalk(for value: Value) -> Bool\n/// nonForwardingUse(of operand: Operand) -> WalkResult\n/// deadValue(_ value: Value, using operand: Operand?) -> WalkResult\n///\n/// Start walking:\n/// walkDown(root: Value)\n///\nprotocol ForwardingDefUseWalker {\n /// Minimally, check a ValueSet. This walker may traverse chains of\n /// aggregation and destructuring by default. Implementations may\n /// handle phis.\n mutating func needWalk(for value: Value) -> Bool\n\n /// A nonForwarding use does not forward ownership, but may\n /// propagate the lifetime in other ways, such as an interior\n /// pointer.\n mutating func nonForwardingUse(of operand: Operand) -> WalkResult\n\n /// Report any initial or forwarded value with no uses. Only relevant for\n /// guaranteed values or incomplete OSSA. This could be a dead\n /// instruction, a terminator in which the result is dead on one\n /// path, or a dead phi.\n ///\n /// \p operand is nil if \p value is the root.\n mutating func deadValue(_ value: Value, using operand: Operand?) -> WalkResult\n\n /// This is called for every forwarded value. If the root was an\n /// owned value, then this identifies all OSSA lifetimes in the\n /// forward-extendd lifetime.\n mutating func walkDownUses(of: Value, using: Operand?) -> WalkResult\n \n mutating func walkDown(operand: Operand) -> WalkResult\n}\n\nextension ForwardingDefUseWalker {\n /// Start walking\n mutating func walkDown(root: Value) -> WalkResult {\n walkDownUses(of: root, using: nil)\n }\n\n mutating func walkDownUses(of value: Value, using operand: Operand?)\n -> WalkResult {\n return walkDownUsesDefault(forwarding: value, using: operand)\n }\n\n mutating func walkDownUsesDefault(forwarding value: Value,\n using operand: Operand?)\n -> WalkResult {\n if !needWalk(for: value) {\n return .continueWalk\n }\n var hasUse = false\n for use in value.uses where !use.isTypeDependent {\n if walkDown(operand: use) == .abortWalk {\n return .abortWalk\n }\n hasUse = true\n }\n if !hasUse {\n return deadValue(value, using: operand)\n }\n return .continueWalk\n }\n\n mutating func walkDown(operand: Operand) -> WalkResult {\n walkDownDefault(forwarding: operand)\n }\n\n mutating func walkDownDefault(forwarding operand: Operand) -> WalkResult {\n if let inst = operand.instruction as? ForwardingInstruction {\n let singleOper = inst.singleForwardedOperand\n if singleOper == nil || singleOper! == operand {\n return inst.forwardedResults.walk {\n walkDownUses(of: $0, using: operand)\n }\n }\n }\n if let phi = Phi(using: operand) {\n return walkDownUses(of: phi.value, using: operand)\n }\n return nonForwardingUse(of: operand)\n }\n}\n\n/// This conveniently allows a closure to be called for each leaf use\n/// of a forward-extended lifetime. It should be called on a forward\n/// introducer provided by ForwardingDefUseWalker.introducer() or\n/// gatherLifetimeIntroducers().\n///\n/// TODO: make the visitor non-escaping once Swift supports stored\n/// non-escaping closues.\nfunc visitForwardedUses(introducer: Value, _ context: Context,\n visitor: @escaping (ForwardingUseResult) -> WalkResult)\n-> WalkResult {\n var useVisitor = VisitForwardedUses(visitor: visitor, context)\n defer { useVisitor.visitedValues.deinitialize() }\n return useVisitor.walkDown(root: introducer)\n}\n\nprivate struct VisitForwardedUses : ForwardingDefUseWalker {\n var visitedValues: ValueSet\n var visitor: (ForwardingUseResult) -> WalkResult\n \n init(visitor: @escaping (ForwardingUseResult) -> WalkResult,\n _ context: Context) {\n self.visitedValues = ValueSet(context)\n self.visitor = visitor\n }\n\n mutating func needWalk(for value: Value) -> Bool {\n visitedValues.insert(value)\n }\n \n mutating func nonForwardingUse(of operand: Operand) -> WalkResult {\n return visitor(.operand(operand))\n }\n\n mutating func deadValue(_ value: Value, using operand: Operand?)\n -> WalkResult {\n return visitor(.deadValue(value, operand))\n }\n}\n\n/// Walk all uses of partial_apply [on_stack] that may propagate the closure context. Gather each FullApplySite that\n/// either invokes this closure as its callee, or passes the closure as an argument to another function.\n///\n/// Start walk:\n/// walkDown(closure:)\n///\n/// This is a subset of the functionality in LifetimeDependenceDefUseWalker, but significantly simpler. This avoids\n/// traversing lifetime dependencies that do not propagate context. For example, a mark_dependence on a closure extends\n/// its lifetime but cannot introduce any new uses of the closure context.\nstruct NonEscapingClosureDefUseWalker {\n let context: Context\n var visitedValues: ValueSet\n var applyOperandStack: Stack<Operand>\n\n /// `visitor` takes an operand whose instruction is always a FullApplySite.\n init(_ context: Context) {\n self.context = context\n self.visitedValues = ValueSet(context)\n self.applyOperandStack = Stack(context)\n }\n\n mutating func deinitialize() {\n visitedValues.deinitialize()\n applyOperandStack.deinitialize()\n }\n\n mutating func walkDown(closure: PartialApplyInst) -> WalkResult {\n assert(!closure.mayEscape)\n return walkDownUses(of: closure, using: nil)\n }\n\n mutating func closureContextLeafUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case is FullApplySite:\n applyOperandStack.push(operand)\n return .continueWalk\n case is MarkDependenceInst, is FixLifetimeInst, is DestroyValueInst:\n return .continueWalk\n default:\n if operand.instruction.isIncidentalUse {\n return .continueWalk\n }\n log(">>> Unexpected closure use \(operand)")\n // Escaping or unexpected closure use. Expected escaping uses include ReturnInst with a lifetime-dependent result.\n //\n // TODO: Check in the SIL verifier that all uses are expected.\n return .abortWalk\n }\n }\n}\n\nextension NonEscapingClosureDefUseWalker: ForwardingDefUseWalker {\n mutating func needWalk(for value: Value) -> Bool {\n visitedValues.insert(value)\n }\n\n mutating func nonForwardingUse(of operand: Operand) -> WalkResult {\n // Nonescaping closures may be moved, copied, or borrowed.\n switch operand.instruction {\n case let transition as OwnershipTransitionInstruction:\n return walkDownUses(of: transition.ownershipResult, using: operand)\n case let convert as ConvertEscapeToNoEscapeInst:\n return walkDownUses(of: convert, using: operand)\n default:\n // Otherwise, assume the use cannot propagate the closure context.\n return closureContextLeafUse(of: operand)\n }\n }\n\n mutating func deadValue(_ value: Value, using operand: Operand?) -> WalkResult {\n return .continueWalk\n }\n}\n\nlet forwardingUseDefTest = FunctionTest("forwarding_use_def_test") {\n function, arguments, context in\n let value = arguments.takeValue()\n for introducer in gatherLifetimeIntroducers(for: value, context) {\n print("INTRODUCER: \(introducer)")\n }\n}\n\nlet forwardingDefUseTest = FunctionTest("forwarding_def_use_test") {\n function, arguments, context in\n let value = arguments.takeValue()\n _ = visitForwardedUses(introducer: value, context) { useResult in\n print("USE: \(useResult)")\n return .continueWalk\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_ForwardingUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_ForwardingUtils.swift
Swift
15,111
0.95
0.119159
0.367188
react-lib
796
2025-03-26T03:30:54.758678
GPL-3.0
false
89013f58ebab93d04a5852cb8b9c7876
//===--- FunctionSignatureTransforms.swift ---------------------------------==//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\n/// Replace an apply with metatype arguments with an apply to a specialized function, where the\n/// metatype values are not passed, but rematerialized in the entry block of the specialized function\n///\n/// ```\n/// func caller() {\n/// callee(Int.self)\n/// }\n/// func callee(_ t: Int.Type) { // a thick metatype\n/// // ...\n/// }\n/// ```\n/// ->\n/// ```\n/// func caller() {\n/// specialized_callee()\n/// }\n/// func specialized_callee() {\n/// let t: Int.Type = Int.self\n/// // ...\n/// }\n/// // remains a thunk\n/// func callee(_ t: Int.Type) {\n/// specialized_callee()\n/// }\n/// ```\n///\nfunc specializeByRemovingMetatypeArguments(apply: FullApplySite, _ context: ModulePassContext) {\n guard let callee = apply.referencedFunction,\n !callee.isGeneric\n else {\n return\n }\n\n let deadArgIndices = callee.argumentTypes.enumerated()\n .filter { $0.element.isRemovableMetatype(in: callee) }\n .map { $0.offset }\n if deadArgIndices.isEmpty {\n return\n }\n\n let specializedFuncName = context.mangle(withDeadArguments: deadArgIndices, from: callee)\n\n let specializedCallee: Function\n if let existingSpecialization = context.lookupFunction(name: specializedFuncName) {\n specializedCallee = existingSpecialization\n } else {\n if !context.loadFunction(function: callee, loadCalleesRecursively: true) {\n return\n }\n specializedCallee = createSpecializedFunction(withName: specializedFuncName,\n withRemovedMetatypeArgumentsOf: apply,\n originalFunction: callee,\n context)\n }\n\n context.transform(function: apply.parentFunction) { funcContext in\n replace(apply: apply, to: specializedCallee, funcContext)\n }\n}\n\n/// Creates a specialized function by moving the whole function body of `originalFunction` to the new specialized\n/// function and calling the specialized function in the original function (which is now a thunk).\nprivate func createSpecializedFunction(\n withName name: String,\n withRemovedMetatypeArgumentsOf apply: FullApplySite,\n originalFunction: Function,\n _ context: ModulePassContext\n) -> Function {\n let (aliveParameters, hasSelfParameter) = getAliveParameters(of: originalFunction)\n\n let specializedFunction = context.createEmptyFunction(\n name: name,\n parameters: aliveParameters,\n hasSelfParameter: hasSelfParameter,\n fromOriginal: originalFunction)\n\n let thunkLoc = originalFunction.entryBlock.instructions.first!.location.autoGenerated\n\n context.moveFunctionBody(from: originalFunction, to: specializedFunction)\n // originalFunction is now empty and used as the thunk.\n let thunk = originalFunction\n\n context.transform(function: thunk) { funcContext in\n thunk.set(thunkKind: .signatureOptimizedThunk, funcContext)\n createEntryBlock(in: thunk, usingArguments: specializedFunction.arguments, funcContext)\n }\n\n context.transform(function: specializedFunction) { funcContext in\n removeMetatypArguments(in: specializedFunction, funcContext)\n }\n\n context.transform(function: thunk) { funcContext in\n createForwardingApply(to: specializedFunction,\n in: thunk,\n originalApply: apply,\n debugLocation: thunkLoc,\n funcContext)\n }\n\n return specializedFunction\n}\n\nprivate func getAliveParameters(of originalFunction: Function) -> ([ParameterInfo], hasSelfParameter: Bool) {\n let convention = originalFunction.convention\n var aliveParams = [ParameterInfo]()\n var hasSelfParameter = originalFunction.hasSelfArgument\n for (paramIdx, origParam) in convention.parameters.enumerated() {\n let argIdx = paramIdx + convention.indirectSILResultCount\n if !originalFunction.argumentTypes[argIdx].isRemovableMetatype(in: originalFunction) {\n aliveParams.append(origParam)\n } else if hasSelfParameter && originalFunction.selfArgumentIndex == argIdx {\n hasSelfParameter = false\n }\n }\n return (aliveParams, hasSelfParameter)\n}\n\nprivate func createEntryBlock(\n in function: Function,\n usingArguments: some Sequence<FunctionArgument>,\n _ context: FunctionPassContext\n) {\n let entryBlock = function.appendNewBlock(context)\n for arg in usingArguments {\n _ = entryBlock.addFunctionArgument(type: arg.type, context)\n }\n}\n\nprivate func removeMetatypArguments(in specializedFunction: Function, _ context: FunctionPassContext) {\n let entryBlock = specializedFunction.entryBlock\n var funcArgIdx = 0\n while funcArgIdx < specializedFunction.entryBlock.arguments.count {\n let funcArg = specializedFunction.arguments[funcArgIdx]\n if funcArg.type.isRemovableMetatype(in: specializedFunction) {\n // Rematerialize the metatype value in the entry block.\n let builder = Builder(atBeginOf: entryBlock, context)\n let instanceType = funcArg.type.canonicalType.instanceTypeOfMetatype\n let metatype = builder.createMetatype(ofInstanceType: instanceType, representation: .thick)\n funcArg.uses.replaceAll(with: metatype, context)\n entryBlock.eraseArgument(at: funcArgIdx, context)\n } else {\n funcArgIdx += 1\n }\n }\n}\n\nprivate func createForwardingApply(\n to specializedFunction: Function,\n in thunk: Function,\n originalApply: FullApplySite,\n debugLocation: Location,\n _ context: FunctionPassContext\n) {\n let applyArgs = Array(thunk.arguments.filter { !$0.type.isRemovableMetatype(in: thunk) })\n\n let builder = Builder(atEndOf: thunk.entryBlock, location: debugLocation, context)\n let callee = builder.createFunctionRef(specializedFunction)\n\n // Use the original apply as template to create the forwarding apply\n switch originalApply {\n case let ai as ApplyInst:\n let newApply = builder.createApply(function: callee,\n ai.substitutionMap,\n arguments: applyArgs,\n isNonThrowing: ai.isNonThrowing,\n isNonAsync: ai.isNonAsync,\n specializationInfo: ai.specializationInfo)\n builder.createReturn(of: newApply)\n case let tai as TryApplyInst:\n let normalBlock = thunk.appendNewBlock(context)\n let errorBlock = thunk.appendNewBlock(context)\n builder.createTryApply(function: callee,\n tai.substitutionMap,\n arguments: applyArgs,\n normalBlock: normalBlock,\n errorBlock: errorBlock,\n specializationInfo: tai.specializationInfo)\n let originalArg = tai.normalBlock.arguments[0]\n let returnVal = normalBlock.addArgument(type: originalArg.type, ownership: originalArg.ownership, context)\n let returnBuilder = Builder(atEndOf: normalBlock, location: debugLocation, context)\n returnBuilder.createReturn(of: returnVal)\n\n let errorArg = tai.errorBlock.arguments[0]\n let errorVal = errorBlock.addArgument(type: errorArg.type, ownership: errorArg.ownership, context)\n let errorBuilder = Builder(atEndOf: errorBlock, location: debugLocation, context)\n errorBuilder.createThrow(of: errorVal)\n default:\n fatalError("unknown full apply instruction \(originalApply)")\n }\n}\n\nprivate func replace(apply: FullApplySite, to specializedCallee: Function, _ context: FunctionPassContext) {\n let builder = Builder(before: apply, context)\n let callee = builder.createFunctionRef(specializedCallee)\n let args = Array(apply.arguments.filter { !$0.type.isRemovableMetatype(in: apply.parentFunction) })\n switch apply {\n case let ai as ApplyInst:\n let newApply = builder.createApply(function: callee,\n ai.substitutionMap,\n arguments: args,\n isNonThrowing: ai.isNonThrowing,\n isNonAsync: ai.isNonAsync,\n specializationInfo: ai.specializationInfo)\n ai.uses.replaceAll(with: newApply, context)\n case let tai as TryApplyInst:\n builder.createTryApply(function: callee,\n tai.substitutionMap,\n arguments: args,\n normalBlock: tai.normalBlock,\n errorBlock: tai.errorBlock,\n specializationInfo: tai.specializationInfo)\n default:\n fatalError("unknown full apply instruction \(apply)")\n }\n context.erase(instruction: apply)\n}\n\nprivate extension Type {\n func isRemovableMetatype(in function: Function) -> Bool {\n if isMetatype {\n if representationOfMetatype == .thick {\n let instanceTy = loweredInstanceTypeOfMetatype(in: function)\n // For structs and enums we know the metatype statically.\n return instanceTy.isStruct || instanceTy.isEnum\n }\n }\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_FunctionSignatureTransforms.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_FunctionSignatureTransforms.swift
Swift
9,552
0.95
0.144033
0.195455
react-lib
27
2024-05-04T12:39:59.420859
GPL-3.0
false
fd33c3b7a310e5af86deab3a8bea2425
//===--- GenericSpecialization.swift ---------------------------------------==//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\nfunc specializeVTable(forClassType classType: Type,\n errorLocation: Location,\n _ context: ModulePassContext,\n notifyNewFunction: (Function) -> ())\n{\n var specializer = VTableSpecializer(errorLocation: errorLocation, context)\n specializer.specializeVTable(forClassType: classType, notifyNewFunction)\n}\n\nprivate struct VTableSpecializer {\n let errorLocation: Location\n let context: ModulePassContext\n\n // The type of the first class in the hierarchy which implements a method\n private var baseTypesOfMethods = Dictionary<Function, Type>()\n\n init(errorLocation: Location, _ context: ModulePassContext) {\n self.errorLocation = errorLocation\n self.context = context\n }\n\n mutating func specializeVTable(forClassType classType: Type, _ notifyNewFunction: (Function) -> ()) {\n // First handle super classes.\n // This is also required for non-generic classes - in case a superclass is generic, e.g.\n // `class Derived : Base<Int> {}` - for two reasons:\n // * A vtable of a derived class references the vtable of the super class. And of course the referenced\n // super-class vtable needs to be a specialized vtable.\n // * Even a non-generic derived class can contain generic methods of the base class in case a base-class\n // method is not overridden.\n //\n if let superClassTy = classType.superClassType {\n specializeVTable(forClassType: superClassTy, notifyNewFunction)\n }\n\n let classDecl = classType.nominal! as! ClassDecl\n guard let origVTable = context.lookupVTable(for: classDecl) else {\n if context.enableWMORequiredDiagnostics {\n context.diagnosticEngine.diagnose(.cannot_specialize_class, classType, at: errorLocation)\n }\n return\n }\n\n for entry in origVTable.entries {\n if baseTypesOfMethods[entry.implementation] == nil {\n baseTypesOfMethods[entry.implementation] = classType\n }\n }\n\n if classType.isGenericAtAnyLevel {\n if context.lookupSpecializedVTable(for: classType) != nil {\n // We already specialized the vtable\n return\n }\n let newEntries = specializeEntries(of: origVTable, notifyNewFunction)\n context.createSpecializedVTable(entries: newEntries, for: classType, isSerialized: false)\n } else {\n if !origVTable.entries.contains(where: { $0.implementation.isGeneric }) {\n // The vtable (of the non-generic class) doesn't contain any generic functions (from a generic base class).\n return\n }\n let newEntries = specializeEntries(of: origVTable, notifyNewFunction)\n context.replaceVTableEntries(of: origVTable, with: newEntries)\n }\n }\n\n private func specializeEntries(of vTable: VTable, _ notifyNewFunction: (Function) -> ()) -> [VTable.Entry] {\n return vTable.entries.map { entry in\n if !entry.implementation.isGeneric {\n return entry\n }\n let baseType = baseTypesOfMethods[entry.implementation]!\n let classContextSubs = baseType.contextSubstitutionMap\n let methodSubs = classContextSubs.getMethodSubstitutions(for: entry.implementation)\n\n guard !methodSubs.conformances.contains(where: {!$0.isValid}),\n context.loadFunction(function: entry.implementation, loadCalleesRecursively: true),\n let specializedMethod = context.specialize(function: entry.implementation, for: methodSubs) else\n {\n return entry\n }\n notifyNewFunction(specializedMethod)\n\n context.deserializeAllCallees(of: specializedMethod, mode: .allFunctions)\n specializedMethod.set(linkage: .public, context)\n specializedMethod.set(isSerialized: false, context)\n\n return VTable.Entry(kind: entry.kind, isNonOverridden: entry.isNonOverridden,\n methodDecl: entry.methodDecl, implementation: specializedMethod)\n }\n }\n}\n\n/// Specializes a witness table of `conformance` for the concrete type of the conformance.\nfunc specializeWitnessTable(for conformance: Conformance,\n _ context: ModulePassContext,\n _ notifyNewWitnessTable: (WitnessTable) -> ())\n{\n if let existingSpecialization = context.lookupWitnessTable(for: conformance),\n existingSpecialization.isSpecialized\n {\n return\n }\n\n let baseConf = conformance.isInherited ? conformance.inheritedConformance: conformance\n if !baseConf.isSpecialized {\n var visited = Set<Conformance>()\n specializeDefaultMethods(for: conformance, visited: &visited, context, notifyNewWitnessTable)\n return\n }\n\n guard let witnessTable = context.lookupWitnessTable(for: baseConf.genericConformance) else {\n fatalError("no witness table found")\n }\n assert(witnessTable.isDefinition, "No witness table available")\n let substitutions = baseConf.specializedSubstitutions\n\n let newEntries = witnessTable.entries.map { origEntry in\n switch origEntry {\n case .invalid:\n return WitnessTable.Entry.invalid\n case .method(let requirement, let witness):\n guard let origMethod = witness else {\n return origEntry\n }\n let methodSubs = substitutions.getMethodSubstitutions(for: origMethod,\n // Generic self types need to be handled specially (see `getMethodSubstitutions`)\n selfType: origMethod.hasGenericSelf(context) ? conformance.type.canonical : nil)\n\n guard !methodSubs.conformances.contains(where: {!$0.isValid}),\n context.loadFunction(function: origMethod, loadCalleesRecursively: true),\n let specializedMethod = context.specialize(function: origMethod, for: methodSubs) else\n {\n return origEntry\n }\n return .method(requirement: requirement, witness: specializedMethod)\n case .baseProtocol(let requirement, let witness):\n let baseConf = context.getSpecializedConformance(of: witness,\n for: conformance.type,\n substitutions: conformance.specializedSubstitutions)\n specializeWitnessTable(for: baseConf, context, notifyNewWitnessTable)\n return .baseProtocol(requirement: requirement, witness: baseConf)\n case .associatedType(let requirement, let witness):\n let substType = witness.subst(with: conformance.specializedSubstitutions)\n return .associatedType(requirement: requirement, witness: substType)\n case .associatedConformance(let requirement, let assocConf):\n // TODO: once we have the API, replace this with:\n // let concreteAssociateConf = assocConf.subst(with: conformance.specializedSubstitutions)\n let concreteAssociateConf = conformance.getAssociatedConformance(ofAssociatedType: requirement.rawType,\n to: assocConf.protocol)\n if concreteAssociateConf.isSpecialized {\n specializeWitnessTable(for: concreteAssociateConf, context, notifyNewWitnessTable)\n }\n return .associatedConformance(requirement: requirement,\n witness: concreteAssociateConf)\n }\n }\n let newWT = context.createSpecializedWitnessTable(entries: newEntries,conformance: conformance,\n linkage: .shared, serialized: false)\n notifyNewWitnessTable(newWT)\n}\n\n/// Specializes the default methods of a non-generic witness table.\n/// Default implementations (in protocol extentions) of non-generic protocol methods have a generic\n/// self argument. Specialize such methods with the concrete type. Note that it is important to also\n/// specialize inherited conformances so that the concrete self type is correct, even for derived classes.\nprivate func specializeDefaultMethods(for conformance: Conformance,\n visited: inout Set<Conformance>,\n _ context: ModulePassContext,\n _ notifyNewWitnessTable: (WitnessTable) -> ())\n{\n // Avoid infinite recursion, which may happen if an associated conformance is the conformance itself.\n guard visited.insert(conformance).inserted,\n let witnessTable = context.lookupWitnessTable(for: conformance.rootConformance)\n else {\n return\n }\n\n assert(witnessTable.isDefinition, "No witness table available")\n\n var specialized = false\n\n let newEntries = witnessTable.entries.map { origEntry in\n switch origEntry {\n case .invalid:\n return WitnessTable.Entry.invalid\n case .method(let requirement, let witness):\n guard let origMethod = witness,\n // Is it a generic method where only self is generic (= a default witness method)?\n origMethod.isGeneric, origMethod.isNonGenericWitnessMethod(context)\n else {\n return origEntry\n }\n // Replace the generic self type with the concrete type.\n let methodSubs = SubstitutionMap(genericSignature: origMethod.genericSignature,\n replacementTypes: [conformance.type])\n\n guard !methodSubs.conformances.contains(where: {!$0.isValid}),\n context.loadFunction(function: origMethod, loadCalleesRecursively: true),\n let specializedMethod = context.specialize(function: origMethod, for: methodSubs) else\n {\n return origEntry\n }\n specialized = true\n return .method(requirement: requirement, witness: specializedMethod)\n case .baseProtocol(_, let witness):\n specializeDefaultMethods(for: witness, visited: &visited, context, notifyNewWitnessTable)\n return origEntry\n case .associatedType:\n return origEntry\n case .associatedConformance(_, let assocConf):\n specializeDefaultMethods(for: assocConf, visited: &visited, context, notifyNewWitnessTable)\n return origEntry\n }\n }\n // If the witness table does not contain any default methods, there is no need to create a\n // specialized witness table.\n if specialized {\n let newWT = context.createSpecializedWitnessTable(entries: newEntries,conformance: conformance,\n linkage: .shared, serialized: false)\n notifyNewWitnessTable(newWT)\n }\n}\n\nprivate extension Function {\n // True, if this is a non-generic method which might have a generic self argument.\n // Default implementations (in protocol extentions) of non-generic protocol methods have a generic\n // self argument.\n func isNonGenericWitnessMethod(_ context: some Context) -> Bool {\n switch loweredFunctionType.invocationGenericSignatureOfFunction.genericParameters.count {\n case 0:\n return true\n case 1:\n return hasGenericSelf(context)\n default:\n return false\n }\n }\n\n // True, if the self argument is a generic parameter.\n func hasGenericSelf(_ context: some Context) -> Bool {\n let convention = FunctionConvention(for: loweredFunctionType,\n hasLoweredAddresses: context.moduleHasLoweredAddresses)\n if convention.hasSelfParameter,\n let selfParam = convention.parameters.last,\n selfParam.type.isGenericTypeParameter\n {\n return true\n }\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_GenericSpecialization.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_GenericSpecialization.swift
Swift
11,740
0.95
0.229323
0.161826
awesome-app
844
2025-02-28T11:27:16.589270
Apache-2.0
false
3ade5fe44ab7d5191dcf79d56a1851fe
//===--- LifetimeDependenceUtils.swift - Utils for lifetime dependence ----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Utilities that specify lifetime dependence:\n//\n// gatherVariableIntroducers(for:) is a use-def walk that returns the values that most closely associated with the\n// variable declarations that the given value holds an instance of.\n//\n// LifetimeDependence.init models the lifetime dependence for a FunctionArgument or a MarkDependenceInstruction,\n// categorizing the kind of dependence scope that the lifetime represents.\n//\n// LifetimeDependence.Scope.computeRange() computes the instruction range covered by a dependence scope.\n//\n// LifetimeDependenceDefUseWalker walks the def-use chain to find all values that depend on the given OSSA lifetime.\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(prefix: Bool = true, _ message: @autoclosure () -> String) {\n if verbose {\n debugLog(prefix: prefix, message())\n }\n}\n\n/// A lifetime dependence represents a scope in which some parent value is alive and accessible along with a dependent\n/// value. All values derived from the dependent value must be used within this scope. This supports diagnostics on\n/// non-copyable and non-escapable types.\n///\n/// A lifetime dependence is produced by either 'mark_dependence [nonescaping]':\n///\n/// %dependent = mark_dependence [nonescaping] %value on %parent\n///\n/// or a non-escapable function argument:\n///\n/// bb0(%dependent : NonEscapableThing):\n///\n/// A lifetime dependence identifies its parent value, the kind of scope that the parent value represents, and a\n/// dependent value.\nstruct LifetimeDependence : CustomStringConvertible {\n enum Scope : CustomStringConvertible {\n /// A guaranteed or inout argument whose scope is provided by the caller\n /// and covers the entire function and any dependent results or yields.\n case caller(FunctionArgument)\n /// An access scope.\n case access(BeginAccessInst)\n /// A coroutine.\n case yield(Value)\n /// An owned value whose OSSA lifetime encloses nonescapable values, or a trivial variable introduced by move_value.\n case owned(Value)\n /// A borrowed value whose OSSA lifetime encloses nonescapable values, or a trivial variable introduced by\n /// begin_borrow.\n case borrowed(BeginBorrowValue)\n /// A local variable scope without ownership. The scope must be introduced by either move_value or\n /// begin_borrow. LinearLiveness computes the scope boundary.\n case local(VariableScopeInstruction)\n /// A directly accessed global variable without exclusivity. Presumably immutable and therefore immortal.\n case global(GlobalAccessBase)\n /// Singly-initialized addressable storage (likely for an immutable address-only value). The lifetime extends until\n /// the memory is destroyed. e.g. A value produced by an @in FunctionArgument, an @out apply, or an @inout\n /// FunctionArgument that is never modified inside the callee. Modified @inout FunctionArguments have caller scoped\n /// instead, and a separate analysis diagnoses mutation after the dependence is formed.\n case initialized(AccessBase.Initializer)\n // Unknown includes: stack allocations that are not singly initialized, and globals that don't have an access scope.\n case unknown(Value)\n\n var parentValue: Value {\n switch self {\n case let .caller(argument): return argument\n case let .access(beginAccess): return beginAccess\n case let .yield(value): return value\n case let .owned(value): return value\n case let .borrowed(beginBorrow): return beginBorrow.value\n case let .local(varScope): return varScope.scopeBegin\n case let .global(ga): return ga.address\n case let .initialized(initializer): return initializer.initialAddress\n case let .unknown(value): return value\n }\n }\n\n func checkPrecondition() {\n switch self {\n case let .caller(argument):\n precondition(argument.ownership != .owned, "only guaranteed or inout arguments have a caller scope")\n case .access, .local, .global, .unknown:\n break \n case let .yield(value):\n precondition(value.definingInstruction is BeginApplyInst)\n case let .owned(value):\n precondition(value.ownership == .owned)\n case let .borrowed(beginBorrow):\n precondition(beginBorrow.value.ownership == .guaranteed)\n case let .initialized(initializer):\n let initialAddress = initializer.initialAddress\n precondition(initialAddress.type.isAddress, "expected an address")\n precondition(initialAddress is AllocStackInst || initialAddress is FunctionArgument\n || initialAddress is StoreBorrowInst,\n "expected storage for a a local 'let'")\n if case let .store(store, _) = initializer {\n precondition(store is StoringInstruction || store is SourceDestAddrInstruction || store is FullApplySite\n || store is StoreBorrowInst,\n "expected a store")\n }\n }\n }\n var description: String {\n {\n switch self {\n case .caller: return "Caller: "\n case .access: return "Access: "\n case .yield: return "Yield: "\n case .owned: return "Owned: "\n case .borrowed: return "Borrowed: "\n case .local: return "Local: "\n case .global: return "Global: "\n case .initialized: return "Initialized: "\n case .unknown: return "Unknown: "\n }\n }() + "\(parentValue)"\n }\n }\n let scope: Scope\n let dependentValue: Value\n let markDepInst: MarkDependenceInstruction?\n \n var parentValue: Value { scope.parentValue }\n\n var function: Function {\n dependentValue.parentFunction\n }\n\n var description: String {\n return scope.description + "\nDependent: \(dependentValue)"\n }\n}\n\nextension LifetimeDependence {\n /// Construct LifetimeDependence from a function argument.\n ///\n /// Returns 'nil' for indirect results.\n init?(_ arg: FunctionArgument, _ context: some Context) {\n if arg.isIndirectResult {\n return nil\n }\n self.scope = Scope(base: arg, context)\n self.dependentValue = arg\n self.markDepInst = nil\n }\n\n // Construct a LifetimeDependence from a return value. This only\n // constructs a dependence for ~Escapable results that do not have a\n // lifetime dependence (@_unsafeNonescapableResult).\n //\n // This is necessary because inserting a mark_dependence placeholder for such an unsafe dependence would illegally\n // have the same base and value operand.\n //\n // TODO: handle indirect results\n init?(unsafeApplyResult value: Value, _ context: some Context) {\n if value.isEscapable {\n return nil\n }\n if (value.definingInstructionOrTerminator as! FullApplySite).hasResultDependence {\n return nil\n }\n assert(value.ownership == .owned, "unsafe apply result must be owned")\n self.scope = Scope(base: value, context)\n self.dependentValue = value\n self.markDepInst = nil\n }\n\n /// Construct LifetimeDependence from mark_dependence [unresolved] or mark_dependence [nonescaping].\n ///\n /// For a LifetimeDependence constructed from a mark_dependence, its `dependentValue` is the result of the\n /// mark_dependence. For a mark_dependence_addr, `dependentValue` is the address operand.\n ///\n /// Returns 'nil' for unknown dependence.\n init?(_ markDep: MarkDependenceInstruction, _ context: some Context) {\n self.init(scope: Scope(base: markDep.base, context), markDep: markDep)\n }\n\n /// Construct LifetimeDependence from mark_dependence [unresolved] or mark_dependence [nonescaping] with a custom\n /// Scope.\n ///\n /// Returns 'nil' for unknown dependence.\n init?(scope: LifetimeDependence.Scope, markDep: MarkDependenceInstruction) {\n switch markDep.dependenceKind {\n case .Unresolved, .NonEscaping:\n self.scope = scope\n switch markDep {\n case let md as MarkDependenceInst:\n self.dependentValue = md\n case let md as MarkDependenceAddrInst:\n self.dependentValue = md.address\n default:\n fatalError("unexpected MarkDependenceInstruction")\n }\n self.markDepInst = markDep\n case .Escaping:\n return nil\n }\n }\n\n /// Compute the range of the dependence scope.\n ///\n /// Returns nil if the dependence scope covers the entire function\n /// or if 'dependentValue' is part of the parent's forwarded\n /// lifetime.\n ///\n /// Note: The caller must deinitialize the returned range.\n func computeRange(_ context: Context) -> InstructionRange? {\n if dependentValue.isForwarded(from: parentValue) {\n return nil\n }\n return scope.computeRange(context)\n }\n\n func resolve(_ context: some Context) {\n if let mdi = markDepInst {\n mdi.resolveToNonEscaping()\n }\n }\n}\n\n// Scope initialization.\nextension LifetimeDependence.Scope {\n /// Construct a lifetime dependence scope from the base value that other values depend on. This derives the kind of\n /// dependence scope and its parentValue from `base`.\n ///\n /// The returned Scope must be the only scope for the given 'base' value. This is generally non-recursive, except\n /// that it tries to find the single borrow introducer. General use-def walking is handled by a utility such as\n /// VariableIntroducerUseDefWalker, which can handle multiple introducers.\n ///\n /// `base` represents the OSSA lifetime that the dependent value must be used within. If `base` is owned, then it\n /// directly defines the parent lifetime. If `base` is guaranteed, then it must have a single borrow introducer, which\n /// defines the parent lifetime. `base` must not be derived from a guaranteed phi or forwarded (via struct/tuple) from\n /// multiple guaranteed values.\n init(base: Value, _ context: some Context) {\n if base.type.isAddress {\n self.init(enclosingAccess: base.enclosingAccessScope, address: base, context)\n return\n }\n switch base.ownership {\n case .owned:\n self = .owned(base)\n case .guaranteed:\n self.init(guaranteed: base, context)\n case .none:\n self.init(trivial: base, context)\n case .unowned:\n self = .unknown(base)\n }\n }\n\n init(enclosingAccess: EnclosingAccessScope, address: Value, _ context: some Context) {\n switch enclosingAccess {\n case let .access(access):\n self = .access(access)\n case let .base(accessBase):\n self.init(accessBase: accessBase, address: address, context)\n case let .dependence(markDep):\n self = .unknown(markDep)\n }\n }\n\n init(accessBase: AccessBase, address: Value, _ context: some Context) {\n switch accessBase {\n case let .box(projectBox):\n // Note: the box may be in a borrow scope.\n self.init(base: projectBox.operand.value, context)\n case .stack, .class, .tail, .pointer, .index:\n self = .unknown(accessBase.address!)\n case .unidentified:\n self = .unknown(address)\n case .global:\n // TODO: When AccessBase directly stores GlobalAccessBase, we don't need a check here and don't need to pass\n // 'address' in to this function.\n if let ga = GlobalAccessBase(address: address) {\n self = .global(ga)\n } else {\n self = .unknown(accessBase.address ?? address)\n }\n case let .argument(arg):\n if arg.convention.isIndirectIn {\n if arg.convention.isGuaranteed {\n // The entire scope is in the caller.\n self = .caller(arg)\n } else {\n // The argument's lifetime ends locally, so model it as a local scope initialized by the argument.\n self = .initialized(.argument(arg))\n }\n } else if arg.convention.isIndirectOut || arg.convention.isInout {\n // @out arguments belong to the caller because they can never be reassigned. If they were locally mutable, then\n // the dependence would be on an access scope instead.\n //\n // @inout arguments belong to the caller because, if local mutation or reassignment were relevant, then the\n // dependence would be on an access scope instead. For example, the dependence may have a trivial type, or it\n // the argument may never be mutated in the function even though it is @inout.\n self = .caller(arg)\n } else {\n self = .unknown(address)\n }\n case let .yield(result):\n self.init(yield: result)\n case .storeBorrow(let sb):\n // Don't follow the stored value in case the dependence requires addressability.\n self = .initialized(.store(initializingStore: sb, initialAddress: sb))\n }\n }\n\n // TODO: Add a SIL verifier check that a mark_dependence [nonescaping]\n // base is never a guaranteed phi and that reborrows are never introduced for mark_dependence [nonescaping].\n //\n // TODO: If we need to handle guaranteed tuple/struct with multiple scopes, replace\n // LifetimeDependenceself.init(markDep) with a gatherDependenceScopes() utility used by both\n // LifetimeDependenceInsertion and LifetimeDependenceScopeFixup.\n private init(guaranteed base: Value, _ context: some Context) {\n var iter = base.getBorrowIntroducers(context).makeIterator()\n // If no borrow introducer was found, then this is a borrow of a trivial value. Since we can assume a single\n // introducer here, then this is the only condition under which we have a trivial introducer.\n guard let beginBorrow = iter.next() else {\n self.init(trivial: base, context)\n return\n }\n assert(iter.next() == nil,\n "guaranteed phis not allowed when diagnosing lifetime dependence")\n switch beginBorrow {\n case .beginBorrow, .loadBorrow:\n self = .borrowed(beginBorrow)\n case let .beginApply(value):\n self = .yield(value)\n case let .functionArgument(arg):\n self = .caller(arg)\n case .uncheckOwnershipConversion:\n self = .unknown(base)\n case .reborrow:\n // Reborrows do not happen during diagnostics, but this utility may be called anywhere. The optimizer should avoid\n // creating a reborrow for a mark_dependence [nonescaping]; it could violate ownership unless we can handle all\n // reborrowed inputs. It is easier to prevent this.\n fatalError("reborrows are not supported in diagnostics")\n }\n }\n\n private init(trivial value: Value, _ context: some Context) {\n if let arg = value as? FunctionArgument {\n self = .caller(arg)\n } else if let varScope = VariableScopeInstruction(value.definingInstruction) {\n self = .local(varScope)\n } else if let ga = GlobalAccessBase(address: value) {\n self = .global(ga)\n } else {\n self = .unknown(value)\n }\n }\n\n private init(yield result: MultipleValueInstructionResult) {\n // Consider an @in yield an .initialized scope because we must find the destroys.\n let apply = result.parentInstruction as! FullApplySite\n if apply.convention(of: result).isIndirectIn {\n self = .initialized(.yield(result))\n return\n }\n // @inout arguments belong to the coroutine because they are valid for the duration of the yield, and, if local\n // mutation or reassignment were relevant, then the dependence would be on an access scope instead.\n self = .yield(result)\n }\n}\n\nextension LifetimeDependence.Scope {\n /// Ignore "irrelevent" borrow scopes: load_borrow or begin_borrow without [var_decl]\n func ignoreBorrowScope(_ context: some Context) -> LifetimeDependence.Scope? {\n guard case let .borrowed(beginBorrowVal) = self else {\n return nil\n }\n switch beginBorrowVal {\n case let .beginBorrow(bb):\n if bb.isFromVarDecl {\n return nil\n }\n return LifetimeDependence.Scope(base: bb.borrowedValue, context).ignoreBorrowScope(context)\n case let .loadBorrow(lb):\n return LifetimeDependence.Scope(base: lb.address, context)\n default:\n fatalError("Scope.borrowed must begin begin_borrow or load_borrow")\n }\n }\n}\n\nextension LifetimeDependence.Scope {\n /// Compute the range of the dependence scope. \n ///\n /// Returns nil if the dependence scope covers the entire function. Returns an empty range for an unknown scope.\n ///\n /// Note: The caller must deinitialize the returned range.\n func computeRange(_ context: Context) -> InstructionRange? {\n switch self {\n case .caller, .global:\n return nil\n case let .access(beginAccess):\n var range = InstructionRange(begin: beginAccess, context)\n range.insert(contentsOf: beginAccess.endInstructions)\n return range\n case let .yield(value):\n // This assumes @inout or @in_guaranteed convention.\n let def = value.definingInstruction!\n var range = InstructionRange(begin: def, context)\n _ = BorrowingInstruction(def)!.visitScopeEndingOperands(context) {\n range.insert($0.instruction)\n return .continueWalk\n }\n return range\n case let .owned(value):\n // Note: This could compute forwarded liveness instead of linear\n // liveness. That would be more forgiving for copies. But, then\n // how would we ensure that the borrowed mark_dependence value\n // is within this value's OSSA lifetime?\n return computeLinearLiveness(for: value, context)\n case let .borrowed(beginBorrow):\n return computeLinearLiveness(for: beginBorrow.value, context)\n case let .local(varScope):\n var range = InstructionRange(for: varScope.scopeBegin, context)\n // Compute liveness.\n for use in varScope.endOperands {\n range.insert(use.instruction)\n }\n return range\n case let .initialized(initializer):\n if case let .argument(arg) = initializer, arg.convention.isInout {\n return nil\n }\n return LifetimeDependence.Scope.computeInitializedRange(initializer: initializer, context)\n case let .unknown(value):\n // Ignore the lifetime of temporary trivial values. Temporaries have an unknown Scope, which means that\n // LifetimeDependence.Scope did not recognize a VariableScopeInstruction. This is important to promote\n // mark_dependence instructions emitted by SILGen to [nonescaping] (e.g. unsafeAddressor). It also allows trivial\n // value to be "extended" without actually tracking their scope, which is expected behavior. For example:\n //\n // let span = Span(buffer.baseAddress)\n //\n // If 'baseAddress' is an opaque getter, then the temporary pointer is effectively valid\n // until the end of the function.\n if value.type.isTrivial(in: value.parentFunction) {\n return nil\n }\n // Return an empty range.\n return InstructionRange(for: value, context)\n }\n }\n\n // Note: an initialized range should always have a destroy_addr. For trivial 'var' variables, we have a alloc_box,\n // which has a destroy_value. For concrete trivial 'let' variables, we load the trivial value:\n // %l = load [trivial] %0\n // %m = move_value [var_decl] %2\n //\n // For generic trivial (BitwiseCopyable) 'let' variables, we emit a destroy_addr for the alloc_stack.\n private static func computeInitializedRange(initializer: AccessBase.Initializer, _ context: Context)\n -> InstructionRange {\n\n let initialAddress = initializer.initialAddress\n var range: InstructionRange\n switch initializer {\n case .argument, .yield:\n range = InstructionRange(for: initialAddress, context)\n case let .store(initializingStore, _):\n range = InstructionRange(begin: initializingStore, context)\n }\n for use in initialAddress.uses {\n let inst = use.instruction\n switch inst {\n case is DestroyAddrInst:\n range.insert(inst)\n case let sdai as SourceDestAddrInstruction\n where sdai.sourceOperand == use && sdai.isTakeOfSrc:\n range.insert(inst)\n case let li as LoadInst where li.loadOwnership == .take:\n range.insert(inst)\n case is EndBorrowInst:\n range.insert(inst)\n default:\n break\n }\n }\n return range\n }\n}\n\n// =============================================================================\n// LifetimeDependenceDefUseWalker - downward walk\n// =============================================================================\n\n/// Walk down dependent values.\n///\n/// First classifies all values using OwnershipUseVisitor. Delegates forwarding uses to the ForwardingUseDefWalker.\n/// Transitively follows OwnershipTransitionInstructions (copy, move, borrow, and mark_dependence). Transitively\n/// follows interior pointers using AddressUseVisitor. Handles stores to and loads from local variables using\n/// LocalVariableReachabilityCache.\n///\n/// Ignores trivial values (~Escapable types are never trivial. Escapable types may only be lifetime-dependent values if\n/// they are non-trivial).\n///\n/// Skips uses within nested borrow scopes.\n///\n/// Minimal requirements:\n/// needWalk(for value: Value) -> Bool\n/// leafUse(of: Operand) -> WalkResult\n/// deadValue(_ value: Value, using operand: Operand?) -> WalkResult\n/// escapingDependence(on operand: Operand) -> WalkResult\n/// inoutDependence(argument: FunctionArgument, on: Operand) -> WalkResult\n/// returnedDependence(result: Operand) -> WalkResult\n/// returnedDependence(address: FunctionArgument, on: Operand) -> WalkResult\n/// yieldedDependence(result: Operand) -> WalkResult\n/// Start walking:\n/// walkDown(dependence: LifetimeDependence)\n///\n/// Note: this may visit values that are not dominated by `dependence` because of dependent phi operands.\nprotocol LifetimeDependenceDefUseWalker : ForwardingDefUseWalker,\n OwnershipUseVisitor,\n AddressUseVisitor {\n var function: Function { get }\n\n /// Dependence tracking through local variables.\n var localReachabilityCache: LocalVariableReachabilityCache { get }\n\n mutating func leafUse(of operand: Operand) -> WalkResult\n\n mutating func escapingDependence(on operand: Operand) -> WalkResult\n\n // Assignment to an inout argument. This does not include the indirect out result, which is considered a return\n // value.\n mutating func inoutDependence(argument: FunctionArgument, on: Operand) -> WalkResult\n\n mutating func returnedDependence(result: Operand) -> WalkResult\n\n mutating func returnedDependence(address: FunctionArgument, on: Operand) -> WalkResult\n\n mutating func yieldedDependence(result: Operand) -> WalkResult\n\n mutating func storeToYieldDependence(address: Value, of operand: Operand) -> WalkResult\n}\n\nextension LifetimeDependenceDefUseWalker {\n // Use a distict context name to avoid rdar://123424566 (Unable to open existential)\n var walkerContext: Context { context }\n}\n\n// Start a forward walk.\nextension LifetimeDependenceDefUseWalker {\n mutating func walkDown(dependence: LifetimeDependence) -> WalkResult {\n if let mdAddr = dependence.markDepInst as? MarkDependenceAddrInst {\n // All reachable uses of the dependent address are dependent uses. Treat the mark_dependence_addr base operand as\n // if it was a store's address operand. Diagnostics will consider this the point of variable initialization.\n return visitStoredUses(of: mdAddr.baseOperand, into: mdAddr.address)\n }\n let root = dependence.dependentValue\n if root.type.isAddress { \n // The root address may be an escapable mark_dependence that guards its address uses (unsafeAddress), or an\n // allocation or incoming argument. In all these cases, it is sufficient to walk down the address uses.\n return walkDownAddressUses(of: root)\n }\n return walkDownUses(of: root, using: nil)\n }\n}\n\n// Implement ForwardingDefUseWalker\nextension LifetimeDependenceDefUseWalker {\n // Override ForwardingDefUseWalker.\n mutating func walkDownUses(of value: Value, using operand: Operand?)\n -> WalkResult {\n // Only track ~Escapable and @noescape types.\n if value.mayEscape {\n return .continueWalk\n }\n return walkDownUsesDefault(forwarding: value, using: operand)\n }\n\n // Override ForwardingDefUseWalker.\n mutating func walkDown(operand: Operand) -> WalkResult {\n // Initially delegate all uses to OwnershipUseVisitor.\n // forwardingUse() will be called for uses that forward ownership, which then delegates to walkDownDefault().\n return classify(operand: operand)\n }\n\n // Callback from (a) ForwardingDefUseWalker or (b) ownershipLeafUse.\n //\n // (a) OwnershipUseVisitor classified this as a forwardingUse(), but\n // ForwardingDefUseWalker does not recognize it as a forwarding\n // instruction. This includes apply arguments.\n //\n // (b) OwnershipUseVisitor classified this as a ownershipLeafUse(), but\n // it was not a recognized copy, destroy, or instantaneous use.\n mutating func nonForwardingUse(of operand: Operand) -> WalkResult {\n if let apply = operand.instruction as? FullApplySite {\n return visitAppliedUse(of: operand, by: apply)\n }\n if operand.instruction is ReturnInst, !operand.value.isEscapable {\n return returnedDependence(result: operand)\n }\n if operand.instruction is YieldInst, !operand.value.isEscapable {\n return yieldedDependence(result: operand)\n }\n return escapingDependence(on: operand)\n }\n}\n\n// Implement OwnershipUseVisitor\nextension LifetimeDependenceDefUseWalker {\n // Handle uses that do not propagate the OSSA lifetime. They may still\n // copy the value, which propagates the dependence.\n mutating func ownershipLeafUse(of operand: Operand, isInnerLifetime: Bool)\n -> WalkResult {\n if operand.ownership == .endBorrow {\n // Record the leaf use here because, in some cases, like\n // begin_apply, we have skipped the inner uses.\n return leafUse(of: operand)\n }\n switch operand.instruction {\n case let transition as OwnershipTransitionInstruction:\n return walkDownUses(of: transition.ownershipResult, using: operand)\n\n case let mdi as MarkDependenceInst where mdi.isUnresolved:\n // Override mark_dependence [unresolved] to handle them just\n // like [nonescaping] even though they are not considered OSSA\n // borrows until after resolution.\n assert(operand == mdi.baseOperand)\n return dependentUse(of: operand, dependentValue: mdi)\n\n case is ExistentialMetatypeInst, is FixLifetimeInst, is WitnessMethodInst,\n is DynamicMethodBranchInst, is ValueMetatypeInst,\n is DestroyNotEscapedClosureInst, is ClassMethodInst, is SuperMethodInst,\n is ClassifyBridgeObjectInst, is DebugValueInst,\n is ObjCMethodInst, is ObjCSuperMethodInst, is UnmanagedRetainValueInst,\n is UnmanagedReleaseValueInst, is SelectEnumInst, is IgnoredUseInst:\n // Catch .instantaneousUse operations that are dependence leaf uses.\n return leafUse(of: operand)\n\n case is DestroyValueInst, is EndLifetimeInst, is DeallocRefInst,\n is DeallocBoxInst, is DeallocExistentialBoxInst,\n is BeginCOWMutationInst, is EndCOWMutationInst,\n is EndInitLetRefInst, is DeallocPartialRefInst, is BeginDeallocRefInst:\n // Catch .destroyingConsume operations that are dependence leaf\n // uses.\n return leafUse(of: operand)\n\n case let si as StoringInstruction where si.sourceOperand == operand:\n return visitStoredUses(of: operand, into: si.destinationOperand.value)\n\n case let tai as TupleAddrConstructorInst:\n return visitStoredUses(of: operand, into: tai.destinationOperand.value)\n\n default:\n return nonForwardingUse(of: operand)\n }\n }\n\n mutating func forwardingUse(of operand: Operand, isInnerLifetime: Bool)\n -> WalkResult {\n // Lifetime dependence is only interested in dominated uses. Treat a returned phi like a dominated use by stopping\n // at the phi operand rather than following the forwarded value to the ReturnInst.\n if let phi = Phi(using: operand), phi.isReturnValue {\n return returnedDependence(result: operand)\n }\n // Delegate ownership forwarding operations to the ForwardingDefUseWalker.\n return walkDownDefault(forwarding: operand)\n }\n\n mutating func interiorPointerUse(of: Operand, into address: Value)\n -> WalkResult {\n return walkDownAddressUses(of: address)\n }\n\n mutating func pointerEscapingUse(of operand: Operand) -> WalkResult {\n return escapingDependence(on: operand)\n }\n\n // Handle address or non-address operands.\n mutating func dependentUse(of operand: Operand, dependentValue value: Value)\n -> WalkResult {\n return walkDownUses(of: value, using: operand)\n }\n\n // Handle address or non-address operands.\n mutating func dependentUse(of operand: Operand, dependentAddress address: Value)\n -> WalkResult {\n // Consider this a leaf use in addition to the dependent address uses, which might all occur earlier.\n if leafUse(of: operand) == .abortWalk {\n return .abortWalk\n }\n // The lifetime dependence is effectively "copied into" the dependent address. Find all uses of the dependent\n // address as if this were a stored use.\n return visitStoredUses(of: operand, into: address)\n }\n\n mutating func borrowingUse(of operand: Operand,\n by borrowInst: BorrowingInstruction)\n -> WalkResult {\n return visitAllBorrowUses(of: operand, by: borrowInst)\n }\n\n // TODO: Consider supporting lifetime dependence analysis of\n // guaranteed phis. See InteriorUseWalker.walkDown(guaranteedPhi: Phi)\n mutating func reborrowingUse(of operand: Operand, isInnerLifetime: Bool)\n -> WalkResult {\n return escapingDependence(on: operand)\n }\n}\n\n// Implement AddressUseVisitor\nextension LifetimeDependenceDefUseWalker {\n /// An address projection produces a single address result and does not\n /// escape its address operand in any other way.\n mutating func projectedAddressUse(of operand: Operand, into value: Value)\n -> WalkResult {\n return walkDownAddressUses(of: value)\n }\n\n mutating func scopedAddressUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case let ba as BeginAccessInst:\n return walkDownAddressUses(of: ba)\n case let ba as BeginApplyInst:\n // visitAppliedUse only calls scopedAddressUse for ~Escapable\n // arguments that are not propagated to a result. Here, we only\n // care about the scope of the call.\n return ba.token.uses.walk { leafUse(of: $0) }\n case is StoreBorrowInst:\n return leafUse(of: operand)\n case let load as LoadBorrowInst:\n return walkDownUses(of: load, using: operand)\n default:\n fatalError("Unrecognized scoped address use: \(operand.instruction)")\n }\n }\n\n mutating func scopeEndingAddressUse(of operand: Operand) -> WalkResult {\n return leafUse(of: operand)\n }\n\n // Includes StoringInstruction.\n mutating func leafAddressUse(of operand: Operand) -> WalkResult {\n return leafUse(of: operand)\n }\n\n mutating func appliedAddressUse(of operand: Operand,\n by apply: FullApplySite) -> WalkResult {\n return visitAppliedUse(of: operand, by: apply)\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoValue value: Value) -> WalkResult {\n // Record the load itself, in case the loaded value is Escapable.\n if leafUse(of: operand) == .abortWalk {\n return .abortWalk\n }\n return walkDownUses(of: value, using: operand)\n } \n\n // copy_addr\n mutating func loadedAddressUse(of operand: Operand, intoAddress address: Operand) -> WalkResult {\n if leafUse(of: operand) == .abortWalk {\n return .abortWalk\n }\n return visitStoredUses(of: operand, into: address.value)\n }\n\n mutating func yieldedAddressUse(of operand: Operand) -> WalkResult {\n if operand.value.isEscapable {\n return leafUse(of: operand)\n } else {\n return yieldedDependence(result: operand)\n }\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentValue value: Value) -> WalkResult {\n dependentUse(of: operand, dependentValue: value)\n } \n\n // mark_dependence_addr\n mutating func dependentAddressUse(of operand: Operand, dependentAddress address: Value) -> WalkResult {\n dependentUse(of: operand, dependentAddress: address)\n }\n\n mutating func escapingAddressUse(of operand: Operand) -> WalkResult {\n if let mdi = operand.instruction as? MarkDependenceInst {\n assert(!mdi.isUnresolved && !mdi.isNonEscaping,\n "should be handled as a dependence by AddressUseVisitor")\n }\n // Escaping an address\n return escapingDependence(on: operand)\n }\n\n mutating func unknownAddressUse(of operand: Operand) -> WalkResult {\n return .abortWalk\n }\n\n private mutating func walkDownAddressUses(of address: Value) -> WalkResult {\n address.uses.ignoreTypeDependence.walk {\n return classifyAddress(operand: $0)\n }\n }\n}\n\n// Helpers\nextension LifetimeDependenceDefUseWalker {\n // Visit uses of borrowing instruction (operandOwnerhip == .borrow).\n private mutating func visitAllBorrowUses(\n of operand: Operand, by borrowInst: BorrowingInstruction) -> WalkResult {\n switch borrowInst {\n case let .beginBorrow(bbi):\n return walkDownUses(of: bbi, using: operand)\n case let .borrowedFrom(bfi):\n return walkDownUses(of: bfi, using: operand)\n case let .storeBorrow(sbi):\n return walkDownAddressUses(of: sbi)\n case .beginApply:\n // Skip the borrow scope; the type system enforces non-escapable\n // arguments.\n return visitInnerBorrowUses(of: borrowInst, operand: operand)\n case .partialApply, .markDependence:\n fatalError("OwnershipUseVisitor should bypass partial_apply [on_stack] "\n + "and mark_dependence [nonescaping]")\n case .startAsyncLet:\n // TODO: If async-let takes a non-escaping closure, we can\n // consider it nonescaping and visit the endAsyncLetLifetime\n // uses here.\n return escapingDependence(on: operand)\n }\n }\n\n // Visit a dependent local variable (alloc_box), or temporary storage (alloc_stack). The depenedency is typically from\n // storing a dependent value at `address`, but may be from an outright `mark_dependence_addr`.\n //\n // This handles stores of the entire value and stores into a member. Storing into a member makes the entire aggregate\n // a dependent value.\n //\n // If 'operand' is an address, then the "store" corresponds to a dependency on another in-memory value. This may\n // result from `copy_addr`, `mark_dependence_addr`, or initialization of an applied `@out` argument that depends on\n // another indirect parameter.\n private mutating func visitStoredUses(of operand: Operand,\n into address: Value) -> WalkResult {\n assert(address.type.isAddress)\n\n var allocation: Value?\n switch address.accessBase {\n case let .box(projectBox):\n allocation = projectBox.box.referenceRoot\n case let .stack(allocStack):\n allocation = allocStack\n case let .argument(arg):\n if arg.convention.isIndirectIn || arg.convention.isInout {\n allocation = arg\n } else if arg.convention.isIndirectOut, !arg.isEscapable {\n return returnedDependence(address: arg, on: operand)\n }\n break\n case .yield:\n return storeToYieldDependence(address: address, of: operand)\n case .global, .class, .tail, .storeBorrow, .pointer, .index, .unidentified:\n // An address produced by .storeBorrow should never be stored into.\n //\n // TODO: allow storing an immortal value into a global.\n break\n }\n if let allocation = allocation {\n if !allocation.isEscapable {\n return visitLocalStore(allocation: allocation, storedOperand: operand, storeAddress: address)\n }\n }\n if address.isEscapable {\n return .continueWalk\n }\n return escapingDependence(on: operand)\n }\n\n private mutating func visitLocalStore(allocation: Value, storedOperand: Operand, storeAddress: Value) -> WalkResult {\n guard let localReachability = localReachabilityCache.reachability(for: allocation, walkerContext) else {\n return escapingDependence(on: storedOperand)\n }\n var accessStack = Stack<LocalVariableAccess>(walkerContext)\n defer { accessStack.deinitialize() }\n\n // Get the local variable access that encloses this store.\n var storeAccess = storedOperand.instruction\n if case let .access(beginAccess) = storeAddress.enclosingAccessScope {\n storeAccess = beginAccess\n }\n if !localReachability.gatherAllReachableUses(of: storeAccess, in: &accessStack) {\n return escapingDependence(on: storedOperand)\n }\n for localAccess in accessStack {\n if visitLocalAccess(allocation: allocation, localAccess: localAccess, initialValue: storedOperand) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n\n private mutating func visitLocalAccess(allocation: Value, localAccess: LocalVariableAccess, initialValue: Operand)\n -> WalkResult {\n switch localAccess.kind {\n case .beginAccess:\n return scopedAddressUse(of: localAccess.operand!)\n case .load:\n switch localAccess.instruction! {\n case let load as LoadInst:\n return loadedAddressUse(of: localAccess.operand!, intoValue: load)\n case let load as LoadBorrowInst:\n return loadedAddressUse(of: localAccess.operand!, intoValue: load)\n case let copyAddr as SourceDestAddrInstruction:\n return loadedAddressUse(of: localAccess.operand!, intoAddress: copyAddr.destinationOperand)\n default:\n return .abortWalk\n }\n case .dependenceSource:\n switch localAccess.instruction! {\n case let md as MarkDependenceInst:\n if md.type.isAddress {\n return loadedAddressUse(of: localAccess.operand!, intoAddress: md.valueOperand)\n }\n return loadedAddressUse(of: localAccess.operand!, intoValue: md)\n case let md as MarkDependenceAddrInst:\n return loadedAddressUse(of: localAccess.operand!, intoAddress: md.addressOperand)\n default:\n return .abortWalk\n }\n case .dependenceDest:\n // Simply a marker that indicates the start of an in-memory dependent value. If this was a mark_dependence, uses\n // of its forwarded address has were visited by LocalVariableAccessWalker and recorded as separate local accesses.\n return .continueWalk\n case .store, .storeBorrow:\n // A store does not use the previous in-memory value.\n return .continueWalk\n case .apply:\n return visitAppliedUse(of: localAccess.operand!, by: localAccess.instruction as! FullApplySite)\n case .escape:\n log("Local variable: \(allocation)\n escapes at: \(localAccess.instruction!)")\n return escapingDependence(on: localAccess.operand!)\n case .outgoingArgument:\n let arg = allocation as! FunctionArgument\n assert(arg.type.isAddress, "returned local must be allocated with an indirect argument")\n return inoutDependence(argument: arg, on: initialValue)\n case .inoutYield:\n return yieldedDependence(result: localAccess.operand!)\n case .incomingArgument:\n fatalError("Incoming arguments are never reachable")\n }\n }\n\n private mutating func visitAppliedUse(of operand: Operand, by apply: FullApplySite) -> WalkResult {\n if let conv = apply.convention(of: operand), conv.isIndirectOut {\n return leafUse(of: operand)\n }\n if apply.isCallee(operand: operand) {\n return leafUse(of: operand)\n }\n if let dep = apply.resultDependence(on: operand),\n !dep.isScoped {\n // Operand is nonescapable and passed as a call argument. If the\n // result inherits its lifetime, then consider any nonescapable\n // result value to be a dependent use.\n //\n // If the lifetime dependence is scoped, then we can ignore it\n // because a mark_dependence [nonescaping] represents the\n // dependence.\n if let result = apply.singleDirectResult, !result.isEscapable {\n if dependentUse(of: operand, dependentValue: result) == .abortWalk {\n return .abortWalk\n }\n }\n for resultAddr in apply.indirectResultOperands\n where !resultAddr.value.isEscapable {\n if dependentUse(of: operand, dependentAddress: resultAddr.value) == .abortWalk {\n return .abortWalk\n }\n }\n }\n // Regardless of lifetime dependencies, consider the operand to be\n // use for the duration of the call.\n if apply is BeginApplyInst {\n return scopedAddressUse(of: operand)\n }\n return leafUse(of: operand)\n }\n}\n\nlet lifetimeDependenceScopeTest = FunctionTest("lifetime_dependence_scope") {\n function, arguments, context in\n let markDep = arguments.takeValue() as! MarkDependenceInst\n guard let dependence = LifetimeDependence(markDep, context) else {\n print("Invalid Dependence")\n return\n }\n print(dependence)\n guard var range = dependence.scope.computeRange(context) else {\n print("Caller range")\n return\n }\n defer { range.deinitialize() }\n print(range)\n}\n\nprivate struct LifetimeDependenceUsePrinter : LifetimeDependenceDefUseWalker {\n let context: Context\n let function: Function\n let localReachabilityCache = LocalVariableReachabilityCache()\n var visitedValues: ValueSet\n \n init(function: Function, _ context: Context) {\n self.context = context\n self.function = function\n self.visitedValues = ValueSet(context)\n }\n \n mutating func deinitialize() {\n visitedValues.deinitialize()\n }\n\n mutating func needWalk(for value: Value) -> Bool {\n visitedValues.insert(value)\n }\n\n mutating func deadValue(_ value: Value, using operand: Operand?)\n -> WalkResult {\n print("Dead value: \(value)")\n return .continueWalk\n }\n\n mutating func leafUse(of operand: Operand) -> WalkResult {\n print("Leaf use: \(operand)")\n return .continueWalk\n }\n\n mutating func escapingDependence(on operand: Operand) -> WalkResult {\n print("Escaping use: \(operand)")\n return .continueWalk\n }\n\n mutating func inoutDependence(argument: FunctionArgument, on operand: Operand) -> WalkResult {\n print("Out use: \(operand) in: \(argument)")\n return .continueWalk\n }\n\n mutating func returnedDependence(result: Operand) -> WalkResult {\n print("Returned use: \(result)")\n return .continueWalk\n }\n\n mutating func returnedDependence(address: FunctionArgument,\n on operand: Operand) -> WalkResult {\n print("Returned use: \(operand) in: \(address)")\n return .continueWalk\n }\n\n mutating func yieldedDependence(result: Operand) -> WalkResult {\n print("Yielded use: \(result)")\n return .continueWalk\n }\n\n mutating func storeToYieldDependence(address: Value, of operand: Operand) -> WalkResult {\n print("Store to yield use: \(operand) to: \(address)")\n return .continueWalk\n }\n}\n\n// =============================================================================\n// LifetimeDependenceUseDefWalker - upward walk\n// =============================================================================\n\n/// Walk up lifetime dependencies to the first value associated with a variable declaration.\n///\n/// To start walking:\n/// walkUp(newLifetime: Value) -> WalkResult\n///\n/// This utility finds a value or address that is the best-effort "root" of the chain of temporary lifetime-dependent\n/// values.\n///\n/// This "looks through" projections: a property that is either visible as a stored property or access via\n/// unsafe[Mutable]Address.\n///\n/// dependsOn(lvalue.field) // finds 'lvalue' when 'field' is a stored property\n///\n/// dependsOn(lvalue.computed) // finds the temporary value directly returned by a getter.\n///\n/// SILGen emits temporary copies that violate lifetime dependence semantcs. This utility looks through such temporary\n/// copies, stopping at a value that introduces an immutable variable: move_value [var_decl] or begin_borrow [var_decl],\n/// or at an access of a mutable variable: begin_access [read] or begin_access [modify].\n///\n/// In this example, the dependence "root" is copied, borrowed, and forwarded before being used as the base operand of\n/// `mark_dependence`. The dependence "root" is the parent of the outer-most dependence scope.\n///\n/// %root = apply // lifetime dependence root\n/// %copy = copy_value %root\n/// %parent = begin_borrow %copy // lifetime dependence parent value\n/// %base = struct_extract %parent // lifetime dependence base value\n/// %dependent = mark_dependence [nonescaping] %value on %base\n///\n/// LifetimeDependenceUseDefWalker extends the ForwardingUseDefWalker to follow copies, moves, and\n/// borrows. ForwardingUseDefWalker treats these as forward-extended lifetime introducers. But they inherit a lifetime\n/// dependency from their operand because non-escapable values can be copied, moved, and borrowed. Nonetheless, all of\n/// their uses must remain within original dependence scope.\n///\n/// # owned lifetime dependence\n/// %parent = apply // begin dependence scope -+\n/// ... |\n/// %1 = mark_dependence [nonescaping] %value on %parent |\n/// ... |\n/// %2 = copy_value %1 -+ |\n/// # forwarding instruction | |\n/// %3 = struct $S (%2) | forward-extended lifetime |\n/// | | OSSA Lifetime\n/// %4 = move_value %3 -+ |\n/// ... | forward-extended lifetime |\n/// %5 = begin_borrow %4 | -+ |\n/// # dependent use of %1 | | forward-extended lifetime|\n/// end_borrow %5 | -+ |\n/// destroy_value %4 -+ |\n/// ... |\n/// destroy_value %parent // end dependence scope -+\n///\n/// All of the dependent uses including `end_borrow %5` and `destroy_value %4` must be before the end of the dependence\n/// scope: `destroy_value %parent`. In this case, the dependence parent is an owned value, so the scope is simply the\n/// value's OSSA lifetime.\n///\n/// The ForwardingUseDefWalker's PathContext is the most recent lifetime owner (Value?). If we ever want to track the\n/// access path as well, then we can aggregate both the owner and access path in a single PathContext.\nprotocol LifetimeDependenceUseDefValueWalker : ForwardingUseDefWalker where PathContext == Value? {\n var context: Context { get }\n\n // 'path' is the lifetime "owner": the "def" into which the current 'value' is eventually forwarded.\n mutating func introducer(_ value: Value, _ path: PathContext) -> WalkResult\n\n // Minimally, check a ValueSet. This walker may traverse chains of\n // aggregation and destructuring along with phis.\n //\n // 'path' is the "owner" of the forwarded value.\n mutating func needWalk(for value: Value, _ path: PathContext) -> Bool\n\n // The 'newLifetime' value is not forwarded to its uses.\n mutating func walkUp(newLifetime: Value) -> WalkResult\n\n // 'owner' is the "def" into which the current 'value' is eventually forwarded.\n mutating func walkUp(value: Value, _ owner: Value?) -> WalkResult\n}\n\n// Defaults\nextension LifetimeDependenceUseDefValueWalker {\n mutating func walkUp(value: Value, _ owner: Value?) -> WalkResult {\n walkUpDefault(value: value, owner)\n }\n}\n\n// Helpers\nextension LifetimeDependenceUseDefValueWalker {\n mutating func walkUpDefault(value: Value, _ owner: Value?) -> WalkResult {\n switch value.definingInstruction {\n case let transition as OwnershipTransitionInstruction:\n return walkUp(newLifetime: transition.operand.value)\n case let load as LoadInstruction:\n return walkUp(newLifetime: load.address)\n default:\n break\n }\n // If the dependence chain has a phi, consider it a root. Dependence roots dominate all dependent values.\n if Phi(value) != nil {\n return introducer(value, owner)\n }\n // ForwardingUseDefWalker will callback to introducer() when it finds no forwarding instruction.\n return walkUpDefault(forwarded: value, owner)\n }\n}\n\nprotocol LifetimeDependenceUseDefAddressWalker {\n var context: Context { get }\n\n // If the scoped value is trivial, then only the variable's lexical scope is relevant, and access scopes can be\n // ignored.\n var isTrivialScope: Bool { get }\n\n mutating func addressIntroducer(_ address: Value, access: AccessBaseAndScopes) -> WalkResult\n\n // The 'newLifetime' value is not forwarded to its uses. It may be a non-address or an address.\n mutating func walkUp(newLifetime: Value) -> WalkResult\n\n mutating func walkUp(address: Value, access: AccessBaseAndScopes) -> WalkResult\n}\n\n// Defaults\nextension LifetimeDependenceUseDefAddressWalker {\n mutating func walkUp(address: Value, access: AccessBaseAndScopes) -> WalkResult {\n walkUpDefault(address: address, access: access)\n }\n}\n\n// Helpers\nextension LifetimeDependenceUseDefAddressWalker {\n mutating func walkUp(address: Value) -> WalkResult {\n walkUp(address: address, access: address.accessBaseWithScopes)\n }\n\n mutating func walkUpDefault(address: Value, access: AccessBaseAndScopes) -> WalkResult {\n // Continue walking for some kinds of access base.\n switch access.base {\n case .box, .global, .class, .tail, .pointer, .index, .unidentified:\n break\n case let .stack(allocStack):\n // Ignore stack locations. Their access scopes do not affect lifetime dependence.\n return walkUp(stackInitializer: allocStack, at: address, access: access)\n case let .argument(arg):\n // Ignore access scopes for @in or @in_guaranteed arguments when all scopes are reads. Do not ignore a [read]\n // access of an inout argument or outer [modify]. Mutation later with the outer scope could invalidate the\n // borrowed state in this narrow scope. Do not ignore any mark_depedence on the address.\n if arg.convention.isIndirectIn && access.isOnlyReadAccess {\n return addressIntroducer(arg, access: access)\n }\n // @inout arguments may be singly initialized (when no modification exists in this function), but this is not\n // relevant here because they require nested access scopes which can never be ignored.\n case let .yield(yieldedAddress):\n // Ignore access scopes for @in or @in_guaranteed yields when all scopes are reads.\n let apply = yieldedAddress.definingInstruction as! FullApplySite\n if apply.convention(of: yieldedAddress).isIndirectIn && access.isOnlyReadAccess {\n return addressIntroducer(yieldedAddress, access: access)\n }\n case .storeBorrow(let sb):\n // Walk up through a store into a temporary.\n if access.scopes.isEmpty,\n case .stack = sb.destinationOperand.value.accessBase {\n return walkUp(newLifetime: sb.source)\n }\n }\n // Skip the access scope for unsafe[Mutable]Address. Treat it like a projection of 'self' rather than a separate\n // variable access.\n if case let .access(innerAccess) = access.scopes.first,\n let addressorSelf = innerAccess.unsafeAddressorSelf {\n return walkUp(newLifetime: addressorSelf)\n }\n // Ignore the acces scope for trivial values regardless of whether it is singly-initialized. Trivial values do not\n // need to be kept alive in memory and can be safely be overwritten in the same scope. Lifetime dependence only\n // cares that the loaded value is within the lexical scope of the trivial value's variable declaration. Rather than\n // skipping all access scopes, call 'walkUp' on each nested access in case one of them needs to redirect the walk,\n // as required for 'access.unsafeAddressorSelf'.\n if isTrivialScope {\n switch access.scopes.first {\n case .none, .base:\n break\n case let .access(beginAccess):\n return walkUp(newLifetime: beginAccess.address)\n case let .dependence(markDep):\n return walkUp(newLifetime: markDep.value)\n }\n }\n return addressIntroducer(access.enclosingAccess.address ?? address, access: access)\n }\n\n // Handle singly-initialized temporary stack locations.\n mutating func walkUp(stackInitializer allocStack: AllocStackInst, at address: Value,\n access: AccessBaseAndScopes) -> WalkResult {\n guard let initializer = allocStack.accessBase.findSingleInitializer(context) else {\n return addressIntroducer(address, access: access)\n }\n if case let .store(store, _) = initializer {\n switch store {\n case let store as StoringInstruction:\n return walkUp(newLifetime: store.source)\n case let srcDestInst as SourceDestAddrInstruction:\n return walkUp(newLifetime: srcDestInst.destination)\n case let apply as FullApplySite:\n if let f = apply.referencedFunction, f.isConvertPointerToPointerArgument {\n return walkUp(newLifetime: apply.parameterOperands[0].value)\n }\n default:\n break\n }\n }\n return addressIntroducer(address, access: access)\n }\n}\n\n/// Walk up through all new lifetimes to find the roots of a lifetime dependence chain.\nstruct LifetimeDependenceRootWalker : LifetimeDependenceUseDefValueWalker, LifetimeDependenceUseDefAddressWalker {\n // The ForwardingUseDefWalker's context is the most recent lifetime owner.\n typealias PathContext = Value?\n\n let context: Context\n\n // If the scoped value is trivial, then only the variable's lexical scope is relevant, and access scopes can be\n // ignored.\n let isTrivialScope: Bool\n\n // This visited set is only really needed for instructions with\n // multiple results, including phis.\n private var visitedValues: ValueSet\n\n var roots: SingleInlineArray<Value> = SingleInlineArray<Value>()\n\n init(_ context: Context, scopedValue: Value) {\n self.context = context\n self.isTrivialScope = scopedValue.type.isAddress\n ? scopedValue.type.objectType.isTrivial(in: scopedValue.parentFunction)\n : scopedValue.isTrivial(context)\n self.visitedValues = ValueSet(context)\n }\n\n mutating func deinitialize() {\n visitedValues.deinitialize()\n }\n \n mutating func introducer(_ value: Value, _ owner: Value?) -> WalkResult {\n roots.push(value)\n return .continueWalk\n }\n\n mutating func addressIntroducer(_ address: Value, access: AccessBaseAndScopes) -> WalkResult {\n roots.push(address)\n return .continueWalk\n }\n\n mutating func needWalk(for value: Value, _ owner: Value?) -> Bool {\n visitedValues.insert(value)\n }\n\n mutating func walkUp(newLifetime: Value) -> WalkResult {\n if newLifetime.type.isAddress {\n return walkUp(address: newLifetime)\n }\n let newOwner = newLifetime.ownership == .owned ? newLifetime : nil\n return walkUp(value: newLifetime, newOwner)\n }\n}\n\n// =============================================================================\n// Unit tests\n// =============================================================================\n\n\nlet lifetimeDependenceUseTest = FunctionTest("lifetime_dependence_use") {\n function, arguments, context in\n let value = arguments.takeValue()\n var dependence: LifetimeDependence?\n switch value {\n case let arg as FunctionArgument:\n dependence = LifetimeDependence(arg, context)\n case let md as MarkDependenceInstruction:\n dependence = LifetimeDependence(md, context)\n default:\n break\n }\n guard let dependence = dependence else {\n print("Invalid dependence scope: \(value)")\n return\n }\n print("LifetimeDependence uses of: \(value)")\n var printer = LifetimeDependenceUsePrinter(function: function, context)\n defer { printer.deinitialize() }\n _ = printer.walkDown(dependence: dependence)\n}\n\nlet lifetimeDependenceRootTest = FunctionTest("lifetime_dependence_root") {\n function, arguments, context in\n let value = arguments.takeValue()\n print("Lifetime dependence roots of: \(value)")\n var walker = LifetimeDependenceRootWalker(context, scopedValue: value)\n let result = walker.walkUp(newLifetime: value)\n assert(result == .continueWalk)\n for root in walker.roots {\n print("root: \(root)")\n }\n walker.deinitialize()\n}\n\n// SIL Unit tests\n\nlet argumentConventionsTest = FunctionTest("argument_conventions") {\n function, arguments, context in\n if arguments.hasUntaken {\n let value = arguments.takeValue()\n let applySite = value.definingInstruction as! ApplySite\n print("Conventions for call: \(applySite)")\n print(applySite.calleeArgumentConventions)\n } else {\n print("Conventions for function: \(function.name)")\n print(function.argumentConventions)\n }\n // TODO: print ~Escapable conformance and lifetime dependencies\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_LifetimeDependenceUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_LifetimeDependenceUtils.swift
Swift
57,082
0.75
0.123475
0.288522
react-lib
627
2025-04-18T06:25:11.099808
Apache-2.0
false
23fbf42392ddf4bef34afea8b4f4b2b6
//===--- LocalVariableUtils.swift - Utilities for local variable access ---===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n///\n/// SIL operates on three kinds of addressable memory:\n///\n/// 1. Temporary RValues. These are recognied by AddressInitializationWalker. These largely disappear with opaque SIL\n/// values.\n///\n/// 2. Local variables. These are always introduced by either a VarDeclInstruction or a Function argument with non-nil\n/// Argument.varDecl. They are accessed according to the structural rules define in this file. Loading or reassigning a\n/// property requires a formal access (begin_access).\n///\n/// 3. Stored properties in heap objects or global variables. These are always formally accessed.\n///\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(prefix: Bool = true, _ message: @autoclosure () -> String) {\n if verbose {\n debugLog(prefix: prefix, message())\n }\n}\n\n// Local variables are accessed in one of these ways.\n//\n// Note: @in is only immutable up to when it is destroyed, so still requires a local live range.\n//\n// A .dependenceSource access creates a new dependent value that keeps this local alive.\n//\n// %local = alloc_stack // this local\n// %md = mark_dependence %val on %local\n// mark_dependence_addr %adr on %local\n//\n// The effect of .dependenceSource on reachability is like a load of this local. The dependent value depends on any\n// value in this local that reaches this point.\n//\n// A .dependenceDest access is the point where another value becomes dependent on this local:\n//\n// %local = alloc_stack // this local\n// %md = mark_dependence %local on %val\n// mark_dependence_addr %local on %val\n//\n// The effect of .dependenceDest on reachability is like a store of this local. All uses of this local reachable from\n// this point are uses of the dependence base.\n//\n// Note that the same mark_dependence_addr often involves two locals:\n//\n// mark_dependence_addr %localDest on %localSource\n//\nstruct LocalVariableAccess: CustomStringConvertible {\n enum Kind {\n case incomingArgument // @in, @inout, @inout_aliasable\n case outgoingArgument // @inout, @inout_aliasable\n case inoutYield // indirect yield from this accessor\n case beginAccess // Reading or reassigning a 'var'\n case load // Reading a 'let'. Returning 'var' from an initializer.\n case dependenceSource // A value/address depends on this local here (like a load)\n case dependenceDest // This local depends on another value/address here (like a store)\n case store // 'var' initialization and destruction\n case storeBorrow // scoped initialization of temporaries\n case apply // indirect arguments\n case escape // alloc_box captures\n }\n let kind: Kind\n // All access have an operand except .incomingArgument and .outgoingArgument.\n let operand: Operand?\n\n // All access have a representative instruction except .incomingArgument.\n var instruction: Instruction?\n\n init(_ kind: Kind, _ operand: Operand) {\n self.kind = kind\n self.operand = operand\n self.instruction = operand.instruction\n }\n\n init(_ kind: Kind, _ instruction: Instruction?) {\n self.kind = kind\n self.operand = nil\n self.instruction = instruction\n }\n\n /// Does this access either fully or partially modify the variable?\n var isModify: Bool {\n switch kind {\n case .beginAccess:\n switch (instruction as! BeginAccessInst).accessKind {\n case .read, .deinit:\n return false\n case .`init`, .modify:\n return true\n }\n case .load, .dependenceSource, .dependenceDest:\n return false\n case .incomingArgument, .outgoingArgument, .store, .storeBorrow, .inoutYield:\n return true\n case .apply:\n let apply = instruction as! FullApplySite\n if let convention = apply.convention(of: operand!) {\n // A direct argument may modify a captured variable.\n return !convention.isIndirectIn\n }\n // A callee argument may modify a captured variable.\n return true\n case .escape:\n return true\n }\n }\n\n var isEscape: Bool {\n switch kind {\n case .escape:\n return true\n default:\n return false\n }\n }\n\n var description: String {\n var str = ""\n switch self.kind {\n case .incomingArgument:\n str += "incomingArgument"\n case .outgoingArgument:\n str += "outgoingArgument"\n case .inoutYield:\n str += "inoutYield"\n case .beginAccess:\n str += "beginAccess"\n case .load:\n str += "load"\n case .dependenceSource:\n str += "dependenceSource"\n case .dependenceDest:\n str += "dependenceDest"\n case .store:\n str += "store"\n case .storeBorrow:\n str += "storeBorrow"\n case .apply:\n str += "apply"\n case .escape:\n str += "escape"\n }\n if let inst = instruction {\n str += "\(inst)"\n }\n return str\n }\n}\n\n/// Class instance for caching local variable information.\nclass LocalVariableAccessInfo: CustomStringConvertible {\n let access: LocalVariableAccess\n\n private var _isFullyAssigned: Bool?\n\n /// Cache whether the allocation has escaped prior to this access.\n /// This returns `nil` until reachability is computed.\n var hasEscaped: Bool?\n\n init(localAccess: LocalVariableAccess) {\n self.access = localAccess\n switch localAccess.kind {\n case .beginAccess:\n switch (localAccess.instruction as! BeginAccessInst).accessKind {\n case .read, .deinit:\n self._isFullyAssigned = false\n case .`init`, .modify:\n break // lazily compute full assignment\n }\n case .load, .dependenceSource, .dependenceDest:\n self._isFullyAssigned = false\n case .store, .storeBorrow:\n if let store = localAccess.instruction as? StoringInstruction {\n self._isFullyAssigned = LocalVariableAccessInfo.isBase(address: store.destination)\n } else {\n self._isFullyAssigned = true\n }\n case .apply:\n let apply = localAccess.instruction as! FullApplySite\n if let convention = apply.convention(of: localAccess.operand!) {\n self._isFullyAssigned = convention.isIndirectOut\n } else {\n self._isFullyAssigned = false\n }\n case .escape:\n self._isFullyAssigned = false\n self.hasEscaped = true\n case .inoutYield:\n self._isFullyAssigned = false\n case .incomingArgument, .outgoingArgument:\n fatalError("Function arguments are never mapped to LocalVariableAccessInfo")\n }\n }\n\n var instruction: Instruction { access.instruction! }\n\n var isModify: Bool { access.isModify }\n\n var isEscape: Bool { access.isEscape }\n\n /// Is this access a full assignment such that none of the variable's components are reachable from a previous\n /// access.\n func isFullyAssigned(_ context: Context) -> Bool {\n if let cached = _isFullyAssigned {\n return cached\n }\n if access.kind != .beginAccess {\n fatalError("Invalid LocalVariableAccess")\n }\n assert(isModify)\n let beginAccess = access.instruction as! BeginAccessInst\n let initializer = AddressInitializationWalker.findSingleInitializer(ofAddress: beginAccess, context: context)\n _isFullyAssigned = (initializer != nil) ? true : false\n return _isFullyAssigned!\n }\n\n var description: String {\n return "assign: \(_isFullyAssigned == nil ? "unknown" : String(describing: _isFullyAssigned!)), "\n + "\(access)"\n }\n\n // Does this address correspond to the local variable's base address? Any writes to this address will be a full\n // assignment. This should match any instructions that the LocalVariableAccessMap initializer below recognizes as an\n // allocation.\n static private func isBase(address: Value) -> Bool {\n // TODO: create an API alternative to 'accessPath' that bails out on the first path component and succeeds on the\n // first begin_access.\n let path = address.accessPath\n return path.base.isLocal && path.projectionPath.isEmpty\n }\n}\n\n/// Model the formal accesses of an addressable variable introduced by an alloc_box, alloc_stack, or indirect\n/// FunctionArgument.\n///\n/// This instantiates a unique LocalVariableAccessInfo instances for each access instruction, caching it an an access\n/// map.\n///\n/// TODO: In addition to isFullyAssigned, consider adding a lazily computed access path if any need arises.\nstruct LocalVariableAccessMap: Collection, CustomStringConvertible {\n let context: Context\n let allocation: Value\n\n let liveInAccess: LocalVariableAccess?\n\n // All mapped accesses have a valid instruction.\n //\n // TODO: replace the List,Dictionary with an OrderedDictionary.\n private var accessList: [LocalVariableAccessInfo]\n private var accessMap: Dictionary<Instruction, LocalVariableAccessInfo>\n\n var function: Function { allocation.parentFunction }\n\n var isBoxed: Bool { allocation is AllocBoxInst }\n\n var mayAlias: Bool {\n if let arg = allocation as? FunctionArgument, arg.convention == .indirectInoutAliasable {\n return true\n }\n return false\n }\n\n init?(allocation: Value, _ context: Context) {\n switch allocation {\n case is AllocBoxInst, is AllocStackInst:\n self.liveInAccess = nil\n break\n case let arg as FunctionArgument:\n switch arg.convention {\n case .indirectIn, .indirectInout, .indirectInoutAliasable:\n self.liveInAccess = LocalVariableAccess(.incomingArgument, nil)\n default:\n return nil\n }\n default:\n return nil\n }\n self.context = context\n self.allocation = allocation\n accessList = []\n accessMap = [:]\n if walkAccesses(context) == .abortWalk {\n return nil\n }\n }\n\n private mutating func walkAccesses(_ context: Context) -> WalkResult {\n var walker = LocalVariableAccessWalker(context)\n defer { walker.deinitialize() }\n if walker.walkDown(allocation: allocation) == .abortWalk {\n return .abortWalk\n }\n for localAccess in walker.accessStack {\n let info = LocalVariableAccessInfo(localAccess: localAccess)\n if mayAlias {\n // Local allocations can only escape prior to assignment if they are boxed or inout_aliasable.\n info.hasEscaped = true\n } else if !isBoxed {\n // Boxed allocation requires reachability to determine whether the box escaped prior to assignment.\n info.hasEscaped = info.isEscape\n }\n accessMap[localAccess.instruction!] = info\n accessList.append(info)\n }\n return .continueWalk\n }\n\n var startIndex: Int { 0 }\n\n var endIndex: Int { accessList.count }\n\n func index(after index: Int) -> Int {\n return index + 1\n }\n\n subscript(_ accessIndex: Int) -> LocalVariableAccessInfo { accessList[accessIndex] }\n\n subscript(instruction: Instruction) -> LocalVariableAccessInfo? { accessMap[instruction] }\n\n var description: String {\n "Access map for: \(allocation)\n" + map({String(describing: $0)}).joined(separator: "\n")\n }\n}\n\n/// Gather the accesses of a local allocation: alloc_box, alloc_stack, @in, @inout.\n///\n/// This is used to populate LocalVariableAccessMap.\n///\n/// Start walk:\n/// walkDown(allocation:)\n///\n/// TODO: This should only handle allocations that have a var decl. And SIL verification should guarantee that the\n/// allocated address is never used by a path projection outside of an access.\nstruct LocalVariableAccessWalker {\n let context: Context\n var visitedValues: ValueSet\n var accessStack: Stack<LocalVariableAccess>\n\n init(_ context: Context) {\n self.context = context\n self.visitedValues = ValueSet(context)\n self.accessStack = Stack(context)\n }\n\n mutating func deinitialize() {\n visitedValues.deinitialize()\n accessStack.deinitialize()\n }\n\n mutating func walkDown(allocation: Value) -> WalkResult {\n if allocation.type.isAddress {\n return walkDownAddressUses(address: allocation)\n }\n return walkDown(root: allocation)\n }\n\n private mutating func visit(_ localAccess: LocalVariableAccess) {\n accessStack.push(localAccess)\n }\n}\n\n// Extend ForwardingDefUseWalker to walk down uses of the box.\nextension LocalVariableAccessWalker : ForwardingDefUseWalker {\n mutating func needWalk(for value: Value) -> Bool {\n visitedValues.insert(value)\n }\n\n mutating func nonForwardingUse(of operand: Operand) -> WalkResult {\n if operand.instruction.isIncidentalUse {\n return .continueWalk\n }\n switch operand.instruction {\n case let pbi as ProjectBoxInst:\n return walkDownAddressUses(address: pbi)\n case let transition as OwnershipTransitionInstruction:\n return walkDownUses(of: transition.ownershipResult, using: operand)\n case is DestroyValueInst:\n visit(LocalVariableAccess(.store, operand))\n case is DeallocBoxInst:\n break\n case let markDep as MarkDependenceInst:\n assert(markDep.baseOperand == operand)\n visit(LocalVariableAccess(.dependenceSource, operand))\n default:\n visit(LocalVariableAccess(.escape, operand))\n }\n return .continueWalk\n }\n\n mutating func deadValue(_ value: Value, using operand: Operand?) -> WalkResult {\n return .continueWalk\n }\n}\n\n// Extend AddressUseVisitor to find all access scopes, initializing stores, and captures.\nextension LocalVariableAccessWalker: AddressUseVisitor {\n private mutating func walkDownAddressUses(address: Value) -> WalkResult {\n for operand in address.uses.ignoreTypeDependence {\n if classifyAddress(operand: operand) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n\n // Handle storage type projections, like MarkUninitializedInst. Path projections are visited for field\n // initialization because SILGen does not emit begin_access [init] consistently.\n //\n // Stack-allocated temporaries are also treated like local variables for the purpose of finding all uses. Such\n // temporaries do not have access scopes, so we need to walk down any projection that may be used to initialize the\n // temporary.\n mutating func projectedAddressUse(of operand: Operand, into value: Value) -> WalkResult {\n if let md = value as? MarkDependenceInst {\n if operand == md.valueOperand {\n // Intercept mark_dependence destination to record an access point which can be used like a store when finding\n // all uses that affect the base after the point that the dependence was marked.\n visit(LocalVariableAccess(.dependenceDest, operand))\n // walk down the forwarded address as usual...\n } else {\n // A dependence is similar to loading from its source. Downstream uses are not accesses of the original local.\n visit(LocalVariableAccess(.dependenceSource, operand))\n return .continueWalk\n }\n }\n return walkDownAddressUses(address: value)\n }\n\n mutating func scopedAddressUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case is BeginAccessInst:\n visit(LocalVariableAccess(.beginAccess, operand))\n return .continueWalk\n case is BeginApplyInst:\n visit(LocalVariableAccess(.apply, operand))\n return .continueWalk\n case is LoadBorrowInst:\n visit(LocalVariableAccess(.load, operand))\n return .continueWalk\n case is StoreBorrowInst:\n visit(LocalVariableAccess(.storeBorrow, operand))\n return .continueWalk\n default:\n // A StoreBorrow should be guarded by an access scope.\n //\n // TODO: verify that we never hit this case.\n return .abortWalk // unexpected\n }\n }\n\n mutating func scopeEndingAddressUse(of operand: Operand) -> WalkResult {\n return .abortWalk // unexpected\n }\n\n mutating func leafAddressUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case is StoringInstruction, is SourceDestAddrInstruction, is DestroyAddrInst, is DeinitExistentialAddrInst,\n is InjectEnumAddrInst, is SwitchEnumAddrInst, is TupleAddrConstructorInst, is InitBlockStorageHeaderInst,\n is PackElementSetInst:\n // Handle instructions that initialize both temporaries and local variables.\n visit(LocalVariableAccess(.store, operand))\n case let md as MarkDependenceAddrInst:\n assert(operand == md.addressOperand)\n visit(LocalVariableAccess(.dependenceDest, operand))\n case is DeallocStackInst:\n break\n default:\n if !operand.instruction.isIncidentalUse {\n visit(LocalVariableAccess(.escape, operand))\n }\n }\n return .continueWalk\n }\n\n mutating func appliedAddressUse(of operand: Operand, by apply: FullApplySite) -> WalkResult {\n visit(LocalVariableAccess(.apply, operand))\n return .continueWalk\n }\n\n mutating func yieldedAddressUse(of operand: Operand) -> WalkResult {\n visit(LocalVariableAccess(.inoutYield, operand))\n return .continueWalk\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentValue value: Value) -> WalkResult {\n // Find all uses of partial_apply [on_stack].\n if let pai = value as? PartialApplyInst, !pai.mayEscape {\n var walker = NonEscapingClosureDefUseWalker(context)\n defer { walker.deinitialize() }\n if walker.walkDown(closure: pai) == .abortWalk {\n return .abortWalk\n }\n for operand in walker.applyOperandStack {\n visit(LocalVariableAccess(.apply, operand))\n }\n }\n // No other dependent uses can access to memory at this address.\n return .continueWalk\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentAddress address: Value) -> WalkResult {\n // No other dependent uses can access to memory at this address.\n return .continueWalk\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoValue value: Value) -> WalkResult {\n visit(LocalVariableAccess(.load, operand))\n return .continueWalk\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoAddress address: Operand) -> WalkResult {\n visit(LocalVariableAccess(.load, operand))\n return .continueWalk\n }\n\n mutating func escapingAddressUse(of operand: Operand) -> WalkResult {\n visit(LocalVariableAccess(.escape, operand))\n return .continueWalk\n }\n\n mutating func unknownAddressUse(of operand: Operand) -> WalkResult {\n return .abortWalk\n }\n}\n\n/// Map LocalVariableAccesses to basic blocks.\n///\n/// This caches flow-insensitive information about the local variable's accesses, for use with a flow-sensitive\n/// analysis.\n///\n/// This allocates a dictionary for the block state rather than using BasicBlockSets in case the client wants to cache\n/// it as an analysis. We expect a very small number of accesses per local variable.\nstruct LocalVariableAccessBlockMap {\n // Lattice, from most information to least information:\n // none -> read -> modify -> escape -> assign\n enum BlockEffect: Int {\n case read // no modification or escape\n case modify // no full assignment or escape\n case escape // no full assignment\n case assign // full assignment, other accesses may be before or after it.\n\n /// Return a merged lattice state such that the result has strictly less information.\n func meet(_ other: BlockEffect?) -> BlockEffect {\n guard let other else {\n return self\n }\n return other.rawValue > self.rawValue ? other : self\n }\n }\n struct BlockInfo {\n var effect: BlockEffect?\n var hasDealloc: Bool\n }\n var blockAccess: Dictionary<BasicBlock, BlockInfo>\n\n subscript(_ block: BasicBlock) -> BlockInfo? { blockAccess[block] }\n\n init(accessMap: LocalVariableAccessMap) {\n blockAccess = [:]\n for accessInfo in accessMap {\n let block = accessInfo.instruction.parentBlock\n let oldEffect = blockAccess[block]?.effect\n let newEffect = BlockEffect(for: accessInfo, accessMap.context).meet(oldEffect)\n blockAccess[block] = BlockInfo(effect: newEffect, hasDealloc: false)\n }\n // Find blocks that end the variable's scope. This is destroy_value for boxes.\n //\n // TODO: SIL verify that owned boxes are never forwarded.\n let deallocations = accessMap.allocation.uses.lazy.filter {\n $0.instruction is Deallocation || $0.instruction is DestroyValueInst\n }\n for dealloc in deallocations {\n let block = dealloc.instruction.parentBlock\n blockAccess[block, default: BlockInfo(effect: nil, hasDealloc: true)].hasDealloc = true\n }\n }\n}\n\nextension LocalVariableAccessBlockMap.BlockEffect {\n init(for accessInfo: LocalVariableAccessInfo, _ context: some Context) {\n // Assign from the lowest to the highest lattice values...\n self = .read\n if accessInfo.isModify {\n self = .modify\n }\n if accessInfo.isEscape {\n self = .escape\n }\n if accessInfo.isFullyAssigned(context) {\n self = .assign\n }\n }\n}\n\n/// Map an allocation (alloc_box, alloc_stack, @in, @inout) onto its reachable accesses.\nclass LocalVariableReachabilityCache {\n var cache = Dictionary<HashableValue, LocalVariableReachableAccess>()\n\n func reachability(for allocation: Value, _ context: some Context) -> LocalVariableReachableAccess? {\n if let reachability = cache[allocation.hashable] {\n return reachability\n }\n if let reachabilty = LocalVariableReachableAccess(allocation: allocation, context) {\n cache[allocation.hashable] = reachabilty\n return reachabilty\n }\n return nil\n }\n}\n\n/// Flow-sensitive, pessimistic data flow of local variable access. This finds all potentially reachable uses of an\n/// assignment. This does not determine whether the assignment is available at each use; that would require optimistic,\n/// iterative data flow. The only data flow state is pessimistic reachability, which is implicit in the block worklist.\nstruct LocalVariableReachableAccess {\n let context: Context\n let accessMap: LocalVariableAccessMap\n let blockMap: LocalVariableAccessBlockMap\n\n init?(allocation: Value, _ context: Context) {\n guard let accessMap = LocalVariableAccessMap(allocation: allocation, context) else {\n return nil\n }\n self.context = context\n self.accessMap = accessMap\n self.blockMap = LocalVariableAccessBlockMap(accessMap: accessMap)\n }\n}\n\n// Find reaching assignments...\nextension LocalVariableReachableAccess {\n // Gather all fully assigned accesses that reach 'instruction'. If 'instruction' is itself a modify access, it is\n // ignored and the nearest assignments above 'instruction' are still gathered.\n func gatherReachingAssignments(for instruction: Instruction, in accessStack: inout Stack<LocalVariableAccess>)\n -> Bool {\n var blockList = BasicBlockWorklist(context)\n defer { blockList.deinitialize() }\n\n var initialEffect: BlockEffect? = nil\n if let prev = instruction.previous {\n initialEffect = backwardScanAccesses(before: prev, accessStack: &accessStack)\n }\n if !backwardPropagateEffect(in: instruction.parentBlock, effect: initialEffect, blockList: &blockList,\n accessStack: &accessStack) {\n return false\n }\n while let block = blockList.pop() {\n let blockInfo = blockMap[block]\n var currentEffect = blockInfo?.effect\n // lattice: none -> read -> modify -> escape -> assign\n //\n // `blockInfo.effect` is the same as `currentEffect` returned by backwardScanAccesses, except when an early escape\n // happens below an assign, in which case we report the escape here.\n switch currentEffect {\n case .none, .read, .modify, .escape:\n break\n case .assign:\n currentEffect = backwardScanAccesses(before: block.instructions.reversed().first!, accessStack: &accessStack)\n }\n if !backwardPropagateEffect(in: block, effect: currentEffect, blockList: &blockList, accessStack: &accessStack) {\n return false\n }\n }\n // TODO: Verify that the accessStack.isEmpty condition never occurs.\n return !accessStack.isEmpty\n }\n\n private func backwardPropagateEffect(in block: BasicBlock, effect: BlockEffect?, blockList: inout BasicBlockWorklist,\n accessStack: inout Stack<LocalVariableAccess>)\n -> Bool {\n switch effect {\n case .none, .read, .modify:\n if block != accessMap.allocation.parentBlock {\n for predecessor in block.predecessors { blockList.pushIfNotVisited(predecessor) }\n } else if block == accessMap.function.entryBlock {\n accessStack.push(accessMap.liveInAccess!)\n }\n case .assign:\n break\n case .escape:\n return false\n }\n return true\n }\n\n // Check all instructions in this block before and including `first`. Return a BlockEffect indicating the combined\n // effects seen before stopping the scan. A .escape or .assign stops the scan.\n private func backwardScanAccesses(before first: Instruction, accessStack: inout Stack<LocalVariableAccess>)\n -> BlockEffect? {\n var currentEffect: BlockEffect?\n for inst in ReverseInstructionList(first: first) {\n guard let accessInfo = accessMap[inst] else {\n continue\n }\n currentEffect = BlockEffect(for: accessInfo, accessMap.context).meet(currentEffect)\n switch currentEffect! {\n case .read, .modify:\n continue\n case .assign:\n accessStack.push(accessInfo.access)\n case .escape:\n break\n }\n break\n }\n return currentEffect\n }\n}\n\n// Find reachable accesses...\nextension LocalVariableReachableAccess {\n /// This performs a forward CFG walk to find known reachable uses from `assignment`. This ignores aliasing and\n /// escapes.\n ///\n /// The known live range is the range in which the assigned value is valid and may be used by dependent values. It\n /// includes the destroy or reassignment of the local.\n func gatherKnownLifetimeUses(from assignment: LocalVariableAccess,\n in accessStack: inout Stack<LocalVariableAccess>) {\n if let modifyInst = assignment.instruction {\n _ = gatherReachableUses(after: modifyInst, in: &accessStack, lifetime: true)\n return\n }\n gatherKnownLifetimeUsesFromEntry(in: &accessStack)\n }\n\n /// This performs a forward CFG walk to find known reachable uses from the function entry. This ignores aliasing and\n /// escapes.\n private func gatherKnownLifetimeUsesFromEntry(in accessStack: inout Stack<LocalVariableAccess>) {\n assert(accessMap.liveInAccess!.kind == .incomingArgument, "only an argument access is live in to the function")\n let firstInst = accessMap.function.entryBlock.instructions.first!\n _ = gatherReachableUses(onOrAfter: firstInst, in: &accessStack, lifetime: true)\n }\n\n /// This performs a forward CFG walk to find all reachable uses of `modifyInst`. `modifyInst` may be a `begin_access\n /// [modify]` or instruction that initializes the local variable.\n ///\n /// This does not include the destroy or reassignment of the value set by `modifyInst`.\n ///\n /// Returns true if all possible reachable uses were visited. Returns false if any escapes may reach `modifyInst` are\n /// reachable from `modifyInst`.\n ///\n /// This does not gather the escaping accesses themselves. When escapes are reachable, it also does not guarantee that\n /// previously reachable accesses are gathered.\n ///\n /// This computes reachability separately for each store. If this store is a fully assigned access, then\n /// this never repeats work (it is a linear-time analysis over all assignments), because the walk always stops at the\n /// next fully-assigned access. Field assignment can result in an analysis that is quadratic in the number\n /// stores. Nonetheless, the analysis is highly efficient because it maintains no block state other than the\n /// block's intrusive bit set.\n func gatherAllReachableUses(of modifyInst: Instruction, in accessStack: inout Stack<LocalVariableAccess>) -> Bool {\n guard let accessInfo = accessMap[modifyInst] else {\n return false\n }\n if accessInfo.hasEscaped == nil {\n findAllEscapesPriorToAccess()\n }\n if accessInfo.hasEscaped! {\n return false\n }\n return gatherReachableUses(after: modifyInst, in: &accessStack, lifetime: false)\n }\n\n /// This performs a forward CFG walk to find all uses of this local variable reachable after `begin`.\n ///\n /// If `lifetime` is true, then this gathers the full known lifetime, includeing destroys and reassignments ignoring\n /// escapes.\n ///\n /// If `lifetime` is false, then this returns `false` if the walk ended early because of a reachable escape.\n private func gatherReachableUses(after begin: Instruction, in accessStack: inout Stack<LocalVariableAccess>,\n lifetime: Bool) -> Bool {\n if let term = begin as? TermInst {\n for succ in term.successors {\n if !gatherReachableUses(onOrAfter: succ.instructions.first!, in: &accessStack, lifetime: lifetime) {\n return false\n }\n }\n return true\n } else {\n return gatherReachableUses(onOrAfter: begin.next!, in: &accessStack, lifetime: lifetime)\n }\n }\n\n /// This performs a forward CFG walk to find all uses of this local variable reachable after and including `begin`.\n ///\n /// If `lifetime` is true, then this returns false if the walk ended early because of a reachable escape.\n private func gatherReachableUses(onOrAfter begin: Instruction, in accessStack: inout Stack<LocalVariableAccess>,\n lifetime: Bool) -> Bool {\n var blockList = BasicBlockWorklist(context)\n defer { blockList.deinitialize() }\n\n let initialBlock = begin.parentBlock\n let initialEffect = forwardScanAccesses(after: begin, accessStack: &accessStack, lifetime: lifetime)\n if !lifetime, initialEffect == .escape {\n return false\n }\n forwardPropagateEffect(in: initialBlock, blockInfo: blockMap[initialBlock], effect: initialEffect,\n blockList: &blockList, accessStack: &accessStack)\n while let block = blockList.pop() {\n let blockInfo = blockMap[block]\n var currentEffect = blockInfo?.effect\n // lattice: none -> read -> modify -> escape -> assign\n //\n // `blockInfo.effect` is the same as `currentEffect` returned by forwardScanAccesses, except when an early\n // disallowed escape happens before an assign.\n switch currentEffect {\n case .none:\n break\n case .escape:\n if !lifetime {\n break\n }\n fallthrough\n case .read, .modify, .assign:\n let firstInst = block.instructions.first!\n currentEffect = forwardScanAccesses(after: firstInst, accessStack: &accessStack, lifetime: lifetime)\n }\n if !lifetime, currentEffect == .escape {\n return false\n }\n forwardPropagateEffect(in: block, blockInfo: blockInfo, effect: currentEffect, blockList: &blockList,\n accessStack: &accessStack)\n }\n log("\n\(accessMap)")\n log(prefix: false, "Reachable access:\n\(accessStack.map({ String(describing: $0)}).joined(separator: "\n"))")\n return true\n }\n\n typealias BlockEffect = LocalVariableAccessBlockMap.BlockEffect\n typealias BlockInfo = LocalVariableAccessBlockMap.BlockInfo\n\n private func forwardPropagateEffect(in block: BasicBlock, blockInfo: BlockInfo?, effect: BlockEffect?,\n blockList: inout BasicBlockWorklist,\n accessStack: inout Stack<LocalVariableAccess>) {\n switch effect {\n case .none, .read, .modify, .escape:\n if let blockInfo, blockInfo.hasDealloc {\n break\n }\n if block.terminator.isFunctionExiting {\n accessStack.push(LocalVariableAccess(.outgoingArgument, block.terminator))\n } else {\n for successor in block.successors { blockList.pushIfNotVisited(successor) }\n }\n case .assign:\n break\n }\n }\n\n // Check all instructions in this block after and including `begin`. Return a BlockEffect indicating the combined\n // effects seen before stopping the scan. An .assign stops the scan. A .escape stops the scan if lifetime is false.\n private func forwardScanAccesses(after first: Instruction, accessStack: inout Stack<LocalVariableAccess>,\n lifetime: Bool)\n -> BlockEffect? {\n var currentEffect: BlockEffect?\n for inst in InstructionList(first: first) {\n guard let accessInfo = accessMap[inst] else {\n continue\n }\n currentEffect = BlockEffect(for: accessInfo, accessMap.context).meet(currentEffect)\n switch currentEffect! {\n case .assign:\n if lifetime {\n accessStack.push(accessInfo.access)\n }\n return currentEffect\n case .escape:\n if !lifetime {\n log("Local variable: \(accessMap.allocation)\n escapes at \(inst)")\n return currentEffect\n }\n fallthrough\n case .read, .modify:\n accessStack.push(accessInfo.access)\n }\n }\n return currentEffect\n }\n}\n\n// Find prior escapes...\nextension LocalVariableReachableAccess {\n /// For alloc_box only, find escapes (captures) of the box prior to each access.\n /// As a result, AccessInfo.hasEscaped will be non-nil for every access.\n ///\n /// This is an optimistic forward dataflow that propagates the escape bit to accesses.\n /// A block can be scanned at most twice. Once after it is marked visited to find any escapes within the block. The\n /// second time after it is marked escaped to propagate the hasEscaped bit to accesses within the block.\n private func findAllEscapesPriorToAccess() {\n var visitedBlocks = BasicBlockSet(context)\n var escapedBlocks = BasicBlockSet(context)\n var blockList = Stack<BasicBlock>(context)\n defer {\n visitedBlocks.deinitialize()\n escapedBlocks.deinitialize()\n blockList.deinitialize()\n }\n let forwardPropagate = { (from: BasicBlock, hasEscaped: Bool) in\n if let blockInfo = blockMap[from], blockInfo.hasDealloc {\n return\n }\n for successor in from.successors {\n if hasEscaped {\n if escapedBlocks.insert(successor) {\n blockList.push(successor)\n }\n } else if visitedBlocks.insert(successor) {\n blockList.push(successor)\n }\n }\n }\n var hasEscaped = propagateEscapeInBlock(after: accessMap.allocation.nextInstruction, hasEscaped: false)\n forwardPropagate(accessMap.allocation.parentBlock, hasEscaped)\n while let block = blockList.pop() {\n hasEscaped = escapedBlocks.contains(block)\n hasEscaped = propagateEscapeInBlock(after: block.instructions.first!, hasEscaped: hasEscaped)\n forwardPropagate(block, hasEscaped)\n }\n }\n\n private func propagateEscapeInBlock(after begin: Instruction, hasEscaped: Bool) -> Bool {\n var hasEscaped = hasEscaped\n for inst in InstructionList(first: begin) {\n guard let accessInfo = accessMap[inst] else {\n continue\n }\n if accessInfo.isEscape {\n hasEscaped = true\n } else {\n accessInfo.hasEscaped = hasEscaped\n }\n }\n return hasEscaped\n }\n}\n\nlet localVariableReachingAssignmentsTest = FunctionTest("local_variable_reaching_assignments") {\n function, arguments, context in\n let allocation = arguments.takeValue()\n let instruction = arguments.takeInstruction()\n print("### Allocation: \(allocation)")\n let localReachabilityCache = LocalVariableReachabilityCache()\n guard let localReachability = localReachabilityCache.reachability(for: allocation, context) else {\n print("No reachability")\n return\n }\n print("### Access map:")\n print(localReachability.accessMap)\n print("### Instruction: \(instruction)")\n var reachingAssignments = Stack<LocalVariableAccess>(context)\n defer { reachingAssignments.deinitialize() }\n guard localReachability.gatherReachingAssignments(for: instruction, in: &reachingAssignments) else {\n print("!!! Reaching escape")\n return\n }\n print("### Reachable assignments:")\n print(reachingAssignments.map({ String(describing: $0)}).joined(separator: "\n"))\n}\n\nlet localVariableReachableUsesTest = FunctionTest("local_variable_reachable_uses") {\n function, arguments, context in\n let allocation = arguments.takeValue()\n let modify = arguments.takeInstruction()\n print("### Allocation: \(allocation)")\n let localReachabilityCache = LocalVariableReachabilityCache()\n guard let localReachability = localReachabilityCache.reachability(for: allocation, context) else {\n print("No reachability")\n return\n }\n print("### Access map:")\n print(localReachability.accessMap)\n print("### Modify: \(modify)")\n var reachableUses = Stack<LocalVariableAccess>(context)\n defer { reachableUses.deinitialize() }\n guard localReachability.gatherAllReachableUses(of: modify, in: &reachableUses) else {\n print("!!! Reachable escape")\n return\n }\n print("### Reachable access:")\n print(reachableUses.map({ String(describing: $0)}).joined(separator: "\n"))\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_LocalVariableUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_LocalVariableUtils.swift
Swift
37,220
0.95
0.118952
0.196487
awesome-app
948
2024-06-20T13:56:40.742149
MIT
false
59b683b9acd2237eaeb32a3cefe447f8
//===--- OptUtils.swift - Utilities for optimizations ---------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SIL\nimport OptimizerBridging\n\n// Default to SIL.Type within the Optimizer module.\ntypealias Type = SIL.`Type`\n\nextension Value {\n var lookThroughBorrow: Value {\n if let beginBorrow = self as? BeginBorrowInst {\n return beginBorrow.borrowedValue.lookThroughBorrow\n }\n return self\n }\n\n var lookThroughCopy: Value {\n if let copy = self as? CopyValueInst {\n return copy.fromValue.lookThroughCopy\n }\n return self\n }\n\n var lookThoughOwnershipInstructions: Value {\n switch self {\n case let beginBorrow as BeginBorrowInst:\n return beginBorrow.borrowedValue.lookThoughOwnershipInstructions\n case let copy as CopyValueInst:\n return copy.fromValue.lookThoughOwnershipInstructions\n case let move as MoveValueInst:\n return move.fromValue.lookThoughOwnershipInstructions\n default:\n return self\n }\n }\n\n func isInLexicalLiverange(_ context: some Context) -> Bool {\n var worklist = ValueWorklist(context)\n defer { worklist.deinitialize() }\n\n worklist.pushIfNotVisited(self)\n while let v = worklist.pop() {\n if v.ownership == .none {\n continue\n }\n if v.isLexical {\n return true\n }\n switch v {\n case let fw as ForwardingInstruction:\n worklist.pushIfNotVisited(contentsOf: fw.definedOperands.lazy.map { $0.value })\n case let bf as BorrowedFromInst:\n worklist.pushIfNotVisited(bf.borrowedValue)\n case let bb as BeginBorrowInst:\n worklist.pushIfNotVisited(bb.borrowedValue)\n case let arg as Argument:\n if let phi = Phi(arg) {\n worklist.pushIfNotVisited(contentsOf: phi.incomingValues)\n } else if let termResult = TerminatorResult(arg),\n let fw = termResult.terminator as? ForwardingInstruction\n {\n worklist.pushIfNotVisited(contentsOf: fw.definedOperands.lazy.map { $0.value })\n }\n default:\n continue\n }\n }\n return false\n }\n\n /// Walks over all fields of an aggregate and checks if a reference count\n /// operation for this value is required. This differs from a simple `Type.isTrivial`\n /// check, because it treats a value_to_bridge_object instruction as "trivial".\n /// It can also handle non-trivial enums with trivial cases.\n func isTrivial(_ context: some Context) -> Bool {\n var worklist = ValueWorklist(context)\n defer { worklist.deinitialize() }\n\n worklist.pushIfNotVisited(self)\n while let v = worklist.pop() {\n if v.type.isTrivial(in: parentFunction) {\n continue\n }\n if v.type.isValueTypeWithDeinit {\n return false\n }\n switch v {\n case is ValueToBridgeObjectInst:\n break\n case let si as StructInst:\n worklist.pushIfNotVisited(contentsOf: si.operands.values)\n case let ti as TupleInst:\n worklist.pushIfNotVisited(contentsOf: ti.operands.values)\n case let en as EnumInst:\n if let payload = en.payload {\n worklist.pushIfNotVisited(payload)\n }\n default:\n return false\n }\n }\n return true\n }\n\n func createProjection(path: SmallProjectionPath, builder: Builder) -> Value {\n let (kind, index, subPath) = path.pop()\n switch kind {\n case .root:\n return self\n case .structField:\n let structExtract = builder.createStructExtract(struct: self, fieldIndex: index)\n return structExtract.createProjection(path: subPath, builder: builder)\n case .tupleField:\n let tupleExtract = builder.createTupleExtract(tuple: self, elementIndex: index)\n return tupleExtract.createProjection(path: subPath, builder: builder)\n default:\n fatalError("path is not materializable")\n }\n }\n\n func createAddressProjection(path: SmallProjectionPath, builder: Builder) -> Value {\n let (kind, index, subPath) = path.pop()\n switch kind {\n case .root:\n return self\n case .structField:\n let structExtract = builder.createStructElementAddr(structAddress: self, fieldIndex: index)\n return structExtract.createAddressProjection(path: subPath, builder: builder)\n case .tupleField:\n let tupleExtract = builder.createTupleElementAddr(tupleAddress: self, elementIndex: index)\n return tupleExtract.createAddressProjection(path: subPath, builder: builder)\n default:\n fatalError("path is not materializable")\n }\n }\n\n func createProjectionAndCopy(path: SmallProjectionPath, builder: Builder) -> Value {\n if path.isEmpty {\n return self.copyIfNotTrivial(builder)\n }\n if self.ownership == .owned {\n let borrow = builder.createBeginBorrow(of: self)\n let projectedValue = borrow.createProjection(path: path, builder: builder)\n let result = projectedValue.copyIfNotTrivial(builder)\n builder.createEndBorrow(of: borrow)\n return result\n }\n let projectedValue = self.createProjection(path: path, builder: builder)\n return projectedValue.copyIfNotTrivial(builder)\n }\n\n func copyIfNotTrivial(_ builder: Builder) -> Value {\n if type.isTrivial(in: parentFunction) {\n return self\n }\n return builder.createCopyValue(operand: self)\n }\n\n /// True if this value is a valid in a static initializer, including all its operands.\n func isValidGlobalInitValue(_ context: some Context) -> Bool {\n guard let svi = self as? SingleValueInstruction else {\n return false\n }\n if let beginAccess = svi as? BeginAccessInst {\n return beginAccess.address.isValidGlobalInitValue(context)\n }\n if !svi.isValidInStaticInitializerOfGlobal(context) {\n return false\n }\n for op in svi.operands {\n if !op.value.isValidGlobalInitValue(context) {\n return false\n }\n }\n return true\n }\n\n /// Performs a simple dominance check without using the dominator tree.\n /// Returns true if `instruction` is in the same block as this value, but "after" this value,\n /// or if this value is a function argument.\n func triviallyDominates(_ instruction: Instruction) -> Bool {\n switch self {\n case is FunctionArgument:\n return true\n case let arg as Argument:\n return arg.parentBlock == instruction.parentBlock\n case let svi as SingleValueInstruction:\n return svi.dominatesInSameBlock(instruction)\n case let mvi as MultipleValueInstructionResult:\n return mvi.parentInstruction.dominatesInSameBlock(instruction)\n default:\n return false\n }\n }\n}\n\nextension FullApplySite {\n func isSemanticCall(_ name: StaticString, withArgumentCount: Int) -> Bool {\n if arguments.count == withArgumentCount,\n let callee = referencedFunction,\n callee.hasSemanticsAttribute(name)\n {\n return true\n }\n return false\n }\n}\n\nextension Builder {\n static func insert(after inst: Instruction, _ context: some MutatingContext, insertFunc: (Builder) -> ()) {\n Builder.insert(after: inst, location: inst.location, context, insertFunc: insertFunc)\n }\n\n static func insert(after inst: Instruction, location: Location,\n _ context: some MutatingContext, insertFunc: (Builder) -> ()) {\n if inst is TermInst {\n for succ in inst.parentBlock.successors {\n assert(succ.hasSinglePredecessor,\n "the terminator instruction must not have critical successors")\n let builder = Builder(before: succ.instructions.first!, location: location,\n context)\n insertFunc(builder)\n }\n } else {\n let builder = Builder(after: inst, location: location, context)\n insertFunc(builder)\n }\n }\n\n func destroyCapturedArgs(for paiOnStack: PartialApplyInst) {\n precondition(paiOnStack.isOnStack, "Function must only be called for `partial_apply`s on stack!")\n self.bridged.destroyCapturedArgs(paiOnStack.bridged)\n }\n}\n\nextension Value {\n /// Return true if all elements occur on or after `instruction` in\n /// control flow order. If this returns true, then zero or more uses\n /// of `self` may be operands of `instruction` itself.\n ///\n /// This performs a backward CFG walk from `instruction` to `self`.\n func usesOccurOnOrAfter(instruction: Instruction, _ context: some Context)\n -> Bool {\n var users = InstructionSet(context)\n defer { users.deinitialize() }\n users.insert(contentsOf: self.users)\n\n var worklist = InstructionWorklist(context)\n defer { worklist.deinitialize() }\n\n let pushPreds = { (block: BasicBlock) in\n block.predecessors.lazy.map({ pred in pred.terminator }).forEach {\n worklist.pushIfNotVisited($0)\n }\n }\n if let prev = instruction.previous {\n worklist.pushIfNotVisited(prev)\n } else {\n pushPreds(instruction.parentBlock)\n }\n let definingInst = self.definingInstruction\n while let lastInst = worklist.pop() {\n for inst in ReverseInstructionList(first: lastInst) {\n if users.contains(inst) {\n return false\n }\n if inst == definingInst {\n break\n }\n }\n if lastInst.parentBlock != self.parentBlock {\n pushPreds(lastInst.parentBlock)\n }\n }\n return true\n }\n}\n\nextension Value {\n /// Makes this new owned value available to be used in the block `destBlock`.\n ///\n /// Inserts required `copy_value` and `destroy_value` operations in case the `destBlock`\n /// is in a different control region than this value. For example, if `destBlock` is\n /// in a loop while this value is not in that loop, the value has to be copied for\n /// each loop iteration.\n func makeAvailable(in destBlock: BasicBlock, _ context: some MutatingContext) -> Value {\n assert(uses.isEmpty)\n assert(ownership == .owned)\n\n let beginBlock = parentBlock\n var useToDefRange = BasicBlockRange(begin: beginBlock, context)\n defer { useToDefRange.deinitialize() }\n\n useToDefRange.insert(destBlock)\n\n // The value needs to be destroyed at every exit of the liverange.\n for exitBlock in useToDefRange.exits {\n let builder = Builder(before: exitBlock.instructions.first!, context)\n builder.createDestroyValue(operand: self)\n }\n \n if useToDefRange.contains(destBlock) {\n // The `destBlock` is within a loop, so we need to copy the value at each iteration.\n let builder = Builder(before: destBlock.instructions.first!, context)\n return builder.createCopyValue(operand: self)\n }\n return self\n }\n\n /// Copies this value at `insertionPoint` and makes the copy available to be used in `destBlock`.\n ///\n /// For details see `makeAvailable`.\n func copy(at insertionPoint: Instruction, andMakeAvailableIn destBlock: BasicBlock,\n _ context: some MutatingContext) -> Value {\n let builder = Builder(before: insertionPoint, context)\n let copiedValue = builder.createCopyValue(operand: self)\n return copiedValue.makeAvailable(in: destBlock, context)\n }\n}\n\nextension SingleValueInstruction {\n /// Replaces all uses with `replacement` and then erases the instruction.\n func replace(with replacement: Value, _ context: some MutatingContext) {\n uses.replaceAll(with: replacement, context)\n context.erase(instruction: self)\n }\n}\n\nextension Instruction {\n var isTriviallyDead: Bool {\n if results.contains(where: { !$0.uses.isEmpty }) {\n return false\n }\n return self.canBeRemovedIfNotUsed\n }\n\n var isTriviallyDeadIgnoringDebugUses: Bool {\n if results.contains(where: { !$0.uses.ignoreDebugUses.isEmpty }) {\n return false\n }\n return self.canBeRemovedIfNotUsed\n }\n\n private var canBeRemovedIfNotUsed: Bool {\n // TODO: it is horrible to hard-code exceptions here, but currently there is no Instruction API for this.\n switch self {\n case is TermInst, is MarkUninitializedInst, is DebugValueInst:\n return false\n case is BorrowedFromInst:\n // A dead borrowed-from can only be removed if the argument (= operand) is also removed.\n return false\n case let bi as BuiltinInst:\n if bi.id == .OnFastPath {\n return false\n }\n case is UncheckedEnumDataInst:\n // Don't remove UncheckedEnumDataInst in OSSA in case it is responsible\n // for consuming an enum value.\n return !parentFunction.hasOwnership\n case is ExtendLifetimeInst:\n // An extend_lifetime can only be removed if the operand is also removed.\n // If its operand is trivial, it will be removed by MandatorySimplification.\n return false\n default:\n break\n }\n return !mayReadOrWriteMemory && !hasUnspecifiedSideEffects\n }\n\n func isValidInStaticInitializerOfGlobal(_ context: some Context) -> Bool {\n // Rule out SILUndef and SILArgument.\n if operands.contains(where: { $0.value.definingInstruction == nil }) {\n return false\n }\n switch self {\n case let bi as BuiltinInst:\n switch bi.id {\n case .ZeroInitializer:\n let type = bi.type.isBuiltinVector ? bi.type.builtinVectorElementType : bi.type\n return type.isBuiltinInteger || type.isBuiltinFloat\n case .PtrToInt:\n return bi.operands[0].value is StringLiteralInst\n case .IntToPtr:\n return bi.operands[0].value is IntegerLiteralInst\n case .StringObjectOr:\n // The first operand can be a string literal (i.e. a pointer), but the\n // second operand must be a constant. This enables creating a\n // a pointer+offset relocation.\n // Note that StringObjectOr requires the or'd bits in the first\n // operand to be 0, so the operation is equivalent to an addition.\n return bi.operands[1].value is IntegerLiteralInst\n case .ZExtOrBitCast:\n return true;\n case .USubOver:\n // Handle StringObjectOr(tuple_extract(usub_with_overflow(x, offset)), bits)\n // This pattern appears in UTF8 String literal construction.\n if let tei = bi.uses.getSingleUser(ofType: TupleExtractInst.self),\n tei.isResultOfOffsetSubtract {\n return true\n }\n return false\n case .OnFastPath:\n return true\n default:\n return false\n }\n case let tei as TupleExtractInst:\n // Handle StringObjectOr(tuple_extract(usub_with_overflow(x, offset)), bits)\n // This pattern appears in UTF8 String literal construction.\n if tei.isResultOfOffsetSubtract,\n let bi = tei.uses.getSingleUser(ofType: BuiltinInst.self),\n bi.id == .StringObjectOr {\n return true\n }\n return false\n case let sli as StringLiteralInst:\n switch sli.encoding {\n case .Bytes, .UTF8, .UTF8_OSLOG:\n return true\n case .ObjCSelector:\n // Objective-C selector string literals cannot be used in static\n // initializers.\n return false\n }\n case let gvi as GlobalValueInst:\n return context.canMakeStaticObjectReadOnly(objectType: gvi.type)\n case is StructInst,\n is TupleInst,\n is EnumInst,\n is IntegerLiteralInst,\n is FloatLiteralInst,\n is ObjectInst,\n is VectorInst,\n is UncheckedRefCastInst,\n is UpcastInst,\n is ValueToBridgeObjectInst,\n is ConvertFunctionInst,\n is ThinToThickFunctionInst,\n is AddressToPointerInst,\n is GlobalAddrInst,\n is FunctionRefInst:\n return true\n default:\n return false\n }\n }\n\n /// Returns true if `otherInst` is in the same block and is strictly dominated by this instruction.\n /// To be used as simple dominance check if both instructions are most likely located in the same block\n /// and no DominatorTree is available (like in instruction simplification).\n func dominatesInSameBlock(_ otherInst: Instruction) -> Bool {\n if parentBlock != otherInst.parentBlock {\n return false\n }\n // Walk in both directions. This is most efficient if both instructions are located nearby but it's not clear\n // which one comes first in the block's instruction list.\n var forwardIter = self\n var backwardIter = self\n while let f = forwardIter.next {\n if f == otherInst {\n return true\n }\n forwardIter = f\n if let b = backwardIter.previous {\n if b == otherInst {\n return false\n }\n backwardIter = b\n }\n }\n return false\n }\n\n /// If this instruction uses a (single) existential archetype, i.e. it has a type-dependent operand,\n /// returns the concrete type if it is known.\n var concreteTypeOfDependentExistentialArchetype: CanonicalType? {\n // For simplicity only support a single type dependent operand, which is true in most of the cases anyway.\n if let openArchetypeOp = typeDependentOperands.singleElement,\n // Match the sequence\n // %1 = metatype $T\n // %2 = init_existential_metatype %1, any P.Type\n // %3 = open_existential_metatype %2 to $@opened(...)\n // this_instruction_which_uses $@opened(...) // type-defs: %3\n let oemt = openArchetypeOp.value as? OpenExistentialMetatypeInst,\n let iemt = oemt.operand.value as? InitExistentialMetatypeInst,\n let mt = iemt.metatype as? MetatypeInst\n {\n return mt.type.canonicalType.instanceTypeOfMetatype\n }\n // TODO: also handle open_existential_addr and open_existential_ref.\n // Those cases are currently handled in SILCombine's `propagateConcreteTypeOfInitExistential`.\n // Eventually we want to replace the SILCombine implementation with this one.\n return nil\n }\n}\n\n// Match the pattern:\n// tuple_extract(usub_with_overflow(x, integer_literal, integer_literal 0), 0)\nprivate extension TupleExtractInst {\n var isResultOfOffsetSubtract: Bool {\n if fieldIndex == 0,\n let bi = tuple as? BuiltinInst,\n bi.id == .USubOver,\n bi.operands[1].value is IntegerLiteralInst,\n let overflowLiteral = bi.operands[2].value as? IntegerLiteralInst,\n let overflowValue = overflowLiteral.value,\n overflowValue == 0\n {\n return true\n }\n return false\n }\n}\n\nextension StoreInst {\n func trySplit(_ context: FunctionPassContext) {\n let builder = Builder(after: self, context)\n let type = source.type\n if type.isStruct {\n if (type.nominal as! StructDecl).hasUnreferenceableStorage {\n return\n }\n if parentFunction.hasOwnership && source.ownership != .none {\n let destructure = builder.createDestructureStruct(struct: source)\n for (fieldIdx, fieldValue) in destructure.results.enumerated() {\n let destFieldAddr = builder.createStructElementAddr(structAddress: destination, fieldIndex: fieldIdx)\n builder.createStore(source: fieldValue, destination: destFieldAddr, ownership: splitOwnership(for: fieldValue))\n }\n } else {\n guard let fields = type.getNominalFields(in: parentFunction) else {\n return\n }\n for idx in 0..<fields.count {\n let srcField = builder.createStructExtract(struct: source, fieldIndex: idx)\n let fieldAddr = builder.createStructElementAddr(structAddress: destination, fieldIndex: idx)\n builder.createStore(source: srcField, destination: fieldAddr, ownership: splitOwnership(for: srcField))\n }\n }\n } else if type.isTuple {\n if parentFunction.hasOwnership && source.ownership != .none {\n let destructure = builder.createDestructureTuple(tuple: source)\n for (elementIdx, elementValue) in destructure.results.enumerated() {\n let elementAddr = builder.createTupleElementAddr(tupleAddress: destination, elementIndex: elementIdx)\n builder.createStore(source: elementValue, destination: elementAddr, ownership: splitOwnership(for: elementValue))\n }\n } else {\n for idx in 0..<type.tupleElements.count {\n let srcField = builder.createTupleExtract(tuple: source, elementIndex: idx)\n let destFieldAddr = builder.createTupleElementAddr(tupleAddress: destination, elementIndex: idx)\n builder.createStore(source: srcField, destination: destFieldAddr, ownership: splitOwnership(for: srcField))\n }\n }\n } else {\n return\n }\n context.erase(instruction: self)\n }\n\n private func splitOwnership(for fieldValue: Value) -> StoreOwnership {\n switch self.storeOwnership {\n case .trivial, .unqualified:\n return self.storeOwnership\n case .assign, .initialize:\n return fieldValue.type.isTrivial(in: parentFunction) ? .trivial : self.storeOwnership\n }\n }\n}\n\nextension LoadInst {\n @discardableResult\n func trySplit(_ context: FunctionPassContext) -> Bool {\n var elements = [Value]()\n let builder = Builder(before: self, context)\n if type.isStruct {\n if (type.nominal as! StructDecl).hasUnreferenceableStorage {\n return false\n }\n guard let fields = type.getNominalFields(in: parentFunction) else {\n return false\n }\n for idx in 0..<fields.count {\n let fieldAddr = builder.createStructElementAddr(structAddress: address, fieldIndex: idx)\n let splitLoad = builder.createLoad(fromAddress: fieldAddr, ownership: self.splitOwnership(for: fieldAddr))\n elements.append(splitLoad)\n }\n let newStruct = builder.createStruct(type: self.type, elements: elements)\n self.replace(with: newStruct, context)\n return true\n } else if type.isTuple {\n var elements = [Value]()\n let builder = Builder(before: self, context)\n for idx in 0..<type.tupleElements.count {\n let fieldAddr = builder.createTupleElementAddr(tupleAddress: address, elementIndex: idx)\n let splitLoad = builder.createLoad(fromAddress: fieldAddr, ownership: self.splitOwnership(for: fieldAddr))\n elements.append(splitLoad)\n }\n let newTuple = builder.createTuple(type: self.type, elements: elements)\n self.replace(with: newTuple, context)\n return true\n }\n return false\n }\n\n private func splitOwnership(for fieldValue: Value) -> LoadOwnership {\n switch self.loadOwnership {\n case .trivial, .unqualified:\n return self.loadOwnership\n case .copy, .take:\n return fieldValue.type.isTrivial(in: parentFunction) ? .trivial : self.loadOwnership\n }\n }\n}\n\nextension FunctionPassContext {\n /// Returns true if any blocks were removed.\n func removeDeadBlocks(in function: Function) -> Bool {\n var reachableBlocks = ReachableBlocks(function: function, self)\n defer { reachableBlocks.deinitialize() }\n\n var blocksRemoved = false\n for block in function.blocks {\n if !reachableBlocks.isReachable(block: block) {\n block.dropAllReferences(self)\n erase(block: block)\n blocksRemoved = true\n }\n }\n return blocksRemoved\n }\n\n func removeTriviallyDeadInstructionsPreservingDebugInfo(in function: Function) {\n for inst in function.reversedInstructions {\n if inst.isTriviallyDead {\n erase(instruction: inst)\n }\n }\n }\n\n func removeTriviallyDeadInstructionsIgnoringDebugUses(in function: Function) {\n for inst in function.reversedInstructions {\n if inst.isTriviallyDeadIgnoringDebugUses {\n erase(instructionIncludingDebugUses: inst)\n }\n }\n }\n}\n\nextension BasicBlock {\n func dropAllReferences(_ context: FunctionPassContext) {\n for arg in arguments {\n arg.uses.replaceAll(with: Undef.get(type: arg.type, context), context)\n }\n for inst in instructions.reversed() {\n for result in inst.results {\n result.uses.replaceAll(with: Undef.get(type: result.type, context), context)\n }\n context.erase(instruction: inst)\n }\n }\n}\n\nextension SimplifyContext {\n\n /// Replaces a pair of redundant instructions, like\n /// ```\n /// %first = enum $E, #E.CaseA!enumelt, %replacement\n /// %second = unchecked_enum_data %first : $E, #E.CaseA!enumelt\n /// ```\n /// Replaces `%second` with `%replacement` and deletes the instructions if possible - or required.\n /// The operation is not done if it would require to insert a copy due to keep ownership correct.\n func tryReplaceRedundantInstructionPair(first: SingleValueInstruction, second: SingleValueInstruction,\n with replacement: Value) {\n let singleUse = preserveDebugInfo ? first.uses.singleUse : first.uses.ignoreDebugUses.singleUse\n let canEraseFirst = singleUse?.instruction == second\n\n if !canEraseFirst && first.parentFunction.hasOwnership {\n if replacement.ownership == .owned {\n // We cannot add more uses to `replacement` without inserting a copy.\n return\n }\n if first.ownership == .owned {\n // We have to insert a compensating destroy because we are deleting the second instruction but\n // not the first one. This can happen if the first instruction is an `enum` which constructs a\n // non-trivial enum from a trivial payload.\n let builder = Builder(before: second, self)\n builder.createDestroyValue(operand: first)\n }\n }\n\n second.replace(with: replacement, self)\n\n if canEraseFirst {\n erase(instructionIncludingDebugUses: first)\n }\n }\n}\n\nextension ProjectedValue {\n /// Returns true if the address can alias with `rhs`.\n ///\n /// Example:\n /// %1 = struct_element_addr %s, #field1\n /// %2 = struct_element_addr %s, #field2\n ///\n /// `%s`.canAddressAlias(with: `%1`) -> true\n /// `%s`.canAddressAlias(with: `%2`) -> true\n /// `%1`.canAddressAlias(with: `%2`) -> false\n ///\n func canAddressAlias(with rhs: ProjectedValue, complexityBudget: Int = Int.max, _ context: some Context) -> Bool {\n // self -> rhs will succeed (= return false) if self is a non-escaping "local" object,\n // but not necessarily rhs.\n if !isEscaping(using: EscapesToValueVisitor(target: rhs), complexityBudget: complexityBudget, context) {\n return false\n }\n // The other way round: rhs -> self will succeed if rhs is a non-escaping "local" object,\n // but not necessarily self.\n if !rhs.isEscaping(using: EscapesToValueVisitor(target: self), complexityBudget: complexityBudget, context) {\n return false\n }\n return true\n }\n}\n\nprivate struct EscapesToValueVisitor : EscapeVisitor {\n let target: ProjectedValue\n\n mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {\n if operand.value == target.value && path.projectionPath.mayOverlap(with: target.path) {\n return .abort\n }\n if operand.instruction is ReturnInst {\n // Anything which is returned cannot escape to an instruction inside the function.\n return .ignore\n }\n return .continueWalk\n }\n\n var followTrivialTypes: Bool { true }\n var followLoads: Bool { false }\n}\n\nextension Function {\n var initializedGlobal: GlobalVariable? {\n if !isGlobalInitOnceFunction {\n return nil\n }\n for inst in entryBlock.instructions {\n if let allocGlobal = inst as? AllocGlobalInst {\n return allocGlobal.global\n }\n }\n return nil\n }\n\n /// True if this function has a dynamic-self metadata argument and any instruction is type dependent on it.\n var mayBindDynamicSelf: Bool {\n guard let dynamicSelf = self.dynamicSelfMetadata else {\n return false\n }\n return dynamicSelf.uses.contains { $0.isTypeDependent }\n }\n}\n\nextension FullApplySite {\n var inliningCanInvalidateStackNesting: Bool {\n guard let calleeFunction = referencedFunction else {\n return false\n }\n\n // In OSSA `partial_apply [on_stack]`s are represented as owned values rather than stack locations.\n // It is possible for their destroys to violate stack discipline.\n // When inlining into non-OSSA, those destroys are lowered to dealloc_stacks.\n // This can result in invalid stack nesting.\n if calleeFunction.hasOwnership && !parentFunction.hasOwnership {\n return true\n }\n // Inlining of coroutines can result in improperly nested stack allocations.\n if self is BeginApplyInst {\n return true\n }\n return false\n }\n}\n\nextension BeginApplyInst {\n var canInline: Bool { BeginApply_canInline(bridged) }\n}\n\nextension GlobalVariable {\n /// Removes all `begin_access` and `end_access` instructions from the initializer.\n ///\n /// Access instructions are not allowed in the initializer, because the initializer must not contain\n /// instructions with side effects (initializer instructions are not executed).\n /// Exclusivity checking does not make sense in the initializer.\n ///\n /// The initializer functions of globals, which reference other globals by address, contain access\n /// instructions. After the initializing code is copied to the global's initializer, those access\n /// instructions must be stripped.\n func stripAccessInstructionFromInitializer(_ context: FunctionPassContext) {\n guard let initInsts = staticInitializerInstructions else {\n return\n }\n for initInst in initInsts {\n switch initInst {\n case let beginAccess as BeginAccessInst:\n beginAccess.replace(with: beginAccess.address, context)\n case let endAccess as EndAccessInst:\n context.erase(instruction: endAccess)\n default:\n break\n }\n }\n }\n}\n\nextension InstructionRange {\n /// Adds the instruction range of a borrow-scope by transitively visiting all (potential) re-borrows.\n mutating func insert(borrowScopeOf borrow: BorrowIntroducingInstruction, _ context: some Context) {\n var worklist = ValueWorklist(context)\n defer { worklist.deinitialize() }\n\n worklist.pushIfNotVisited(borrow)\n while let value = worklist.pop() {\n for use in value.uses {\n switch use.instruction {\n case let endBorrow as EndBorrowInst:\n self.insert(endBorrow)\n case let branch as BranchInst:\n worklist.pushIfNotVisited(branch.getArgument(for: use).lookThroughBorrowedFromUser)\n default:\n break\n }\n }\n }\n }\n}\n\n/// Analyses the global initializer function and returns the `alloc_global` and `store`\n/// instructions which initialize the global.\n/// Returns nil if `function` has any side-effects beside initializing the global.\n///\n/// The function's single basic block must contain following code pattern:\n/// ```\n/// alloc_global @the_global\n/// %a = global_addr @the_global\n/// %i = some_const_initializer_insts\n/// store %i to %a\n/// ```\n/// \n/// For all other instructions `handleUnknownInstruction` is called and such an instruction\n/// is accepted if `handleUnknownInstruction` returns true.\nfunc getGlobalInitialization(\n of function: Function,\n _ context: some Context,\n handleUnknownInstruction: (Instruction) -> Bool\n) -> (allocInst: AllocGlobalInst, storeToGlobal: StoreInst)? {\n guard let block = function.blocks.singleElement else {\n return nil\n }\n\n var allocInst: AllocGlobalInst? = nil\n var globalAddr: GlobalAddrInst? = nil\n var store: StoreInst? = nil\n\n for inst in block.instructions {\n switch inst {\n case is ReturnInst,\n is DebugValueInst,\n is DebugStepInst,\n is BeginAccessInst,\n is EndAccessInst:\n continue\n case let agi as AllocGlobalInst:\n if allocInst == nil {\n allocInst = agi\n continue\n }\n case let ga as GlobalAddrInst:\n if let agi = allocInst, agi.global == ga.global {\n globalAddr = ga\n }\n continue\n case let si as StoreInst:\n if store == nil,\n let ga = globalAddr,\n si.destination == ga\n {\n store = si\n continue\n }\n // Note that the initializer must not contain a `global_value` because `global_value` needs to\n // initialize the class metadata at runtime.\n default:\n if inst.isValidInStaticInitializerOfGlobal(context) {\n continue\n }\n }\n if handleUnknownInstruction(inst) {\n continue\n }\n return nil\n }\n if let store = store {\n return (allocInst: allocInst!, storeToGlobal: store)\n }\n return nil\n}\n\nfunc canDynamicallyCast(from sourceType: CanonicalType, to destType: CanonicalType,\n in function: Function, sourceTypeIsExact: Bool\n) -> Bool? {\n switch classifyDynamicCastBridged(sourceType.bridged, destType.bridged, function.bridged, sourceTypeIsExact) {\n case .willSucceed: return true\n case .maySucceed: return nil\n case .willFail: return false\n default: fatalError("unknown result from classifyDynamicCastBridged")\n }\n}\n\nextension CheckedCastAddrBranchInst {\n var dynamicCastResult: Bool? {\n switch classifyDynamicCastBridged(bridged) {\n case .willSucceed: return true\n case .maySucceed: return nil\n case .willFail: return false\n default: fatalError("unknown result from classifyDynamicCastBridged")\n }\n }\n}\n\nextension CopyAddrInst {\n @discardableResult\n func trySplit(_ context: FunctionPassContext) -> Bool {\n let builder = Builder(before: self, context)\n if source.type.isStruct {\n if (source.type.nominal as! StructDecl).hasUnreferenceableStorage {\n return false\n }\n guard let fields = source.type.getNominalFields(in: parentFunction) else {\n return false\n }\n for idx in 0..<fields.count {\n let srcFieldAddr = builder.createStructElementAddr(structAddress: source, fieldIndex: idx)\n let destFieldAddr = builder.createStructElementAddr(structAddress: destination, fieldIndex: idx)\n builder.createCopyAddr(from: srcFieldAddr, to: destFieldAddr,\n takeSource: isTake(for: srcFieldAddr), initializeDest: isInitializationOfDest)\n }\n context.erase(instruction: self)\n return true\n } else if source.type.isTuple {\n let builder = Builder(before: self, context)\n for idx in 0..<source.type.tupleElements.count {\n let srcFieldAddr = builder.createTupleElementAddr(tupleAddress: source, elementIndex: idx)\n let destFieldAddr = builder.createTupleElementAddr(tupleAddress: destination, elementIndex: idx)\n builder.createCopyAddr(from: srcFieldAddr, to: destFieldAddr,\n takeSource: isTake(for: srcFieldAddr), initializeDest: isInitializationOfDest)\n }\n context.erase(instruction: self)\n return true\n }\n return false\n }\n\n private func isTake(for fieldValue: Value) -> Bool {\n return isTakeOfSrc && !fieldValue.type.objectType.isTrivial(in: parentFunction)\n }\n\n @discardableResult\n func replaceWithLoadAndStore(_ context: some MutatingContext) -> (load: LoadInst, store: StoreInst) {\n let builder = Builder(before: self, context)\n let load = builder.createLoad(fromAddress: source, ownership: loadOwnership)\n let store = builder.createStore(source: load, destination: destination, ownership: storeOwnership)\n context.erase(instruction: self)\n return (load, store)\n }\n\n var loadOwnership: LoadInst.LoadOwnership {\n if !parentFunction.hasOwnership {\n return .unqualified\n }\n if type.isTrivial(in: parentFunction) {\n return .trivial\n }\n if isTakeOfSrc {\n return .take\n }\n return .copy\n }\n\n var storeOwnership: StoreInst.StoreOwnership {\n if !parentFunction.hasOwnership {\n return .unqualified\n }\n if type.isTrivial(in: parentFunction) {\n return .trivial\n }\n if isInitializationOfDest {\n return .initialize\n }\n return .assign\n }\n}\n\nextension Type {\n /// True if a type can be expanded without a significant increase to code\n /// size.\n /// Expanding a type can mean expressing it as a SSA value (which ultimately\n /// is represented as multiple SSA values in LLVM IR) instead of indirectly\n /// via memory operations (copy_addr), or exploding an SSA value into its\n /// constituent projections.\n /// Once a value is represented as its projections we don't "reconstitute" the\n /// aggregate value anymore leading to register pressure and code size bloat.\n /// Therefore, we try to keep "larger" values indirect and not exploated\n /// throughout the pipeline.\n ///\n /// False if expanding a type is invalid. For example, expanding a\n /// struct-with-deinit drops the deinit.\n func shouldExpand(_ context: some Context) -> Bool {\n if !context.options.useAggressiveReg2MemForCodeSize {\n return true\n }\n return context._bridged.shouldExpand(self.bridged)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_OptUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_OptUtils.swift
Swift
36,603
0.95
0.177778
0.150728
python-kit
66
2023-08-31T14:58:48.270149
Apache-2.0
false
eac80087cf9e260bf38436189a8f5bf2
//===--- OwnershipLiveness.swift - Utilities for ownership liveness -------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Utilities that specify ownership SSA (OSSA) lifetimes.\n//\n// TODO: Implement ExtendedLinearLiveness. This requires\n// MultiDefPrunedLiveness, which is not supported by InstructionRange.\n//\n// TODO: Move this all into SIL, along with DominatorTree. OSSA\n// lifetimes and dominance are part of SIL semantics, and need to be\n// verified. Remove uses of FunctionPassContext.\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\n\nprivate let verbose = false\n\nprivate func log(_ message: @autoclosure () -> String) {\n if verbose {\n print("### \(message())")\n }\n}\n\n/// Compute liveness and return a range, which the caller must deinitialize.\n///\n/// `definingValue` must introduce an OSSA lifetime. It may be either\n/// an owned value or introduce a borrowed value (BeginBorrowValue),\n/// including:\n///\n/// 1. Owned non-phi values\n/// 2. Owned phi values\n/// 3. Borrow scope introducers: begin_borrow/load_borrow\n/// 4. Reborrows: guaranteed phi that ends its operand's borrow scope and\n/// requires post-dominating scope-ending uses (end_borrow or reborrow)\n///\n/// `definingValue`'s lifetime must already complete on all paths\n/// (a.k.a linear). Only lifetime-ending operations generate liveness.\n///\n/// `definingValue` dominates the range. Forwarding and phi uses do\n/// not extend the lifetime.\n///\n/// This is the simplest OSSA liveness analysis. It assumes that OSSA\n/// lifetime completion has already run on `definingValue`, and it\n/// cannot fix OSSA lifetimes after a transformation.\nfunc computeLinearLiveness(for definingValue: Value, _ context: Context)\n -> InstructionRange {\n\n assert(definingValue.ownership == .owned || BeginBorrowValue(definingValue) != nil,\n "value must define an OSSA lifetime")\n\n // InstructionRange cannot directly represent the beginning of the block\n // so we fake it with getRepresentativeInstruction().\n var range = InstructionRange(for: definingValue, context)\n\n // Compute liveness.\n for use in definingValue.lookThroughBorrowedFromUser.uses {\n let instruction = use.instruction\n if use.endsLifetime || instruction is ExtendLifetimeInst {\n range.insert(instruction)\n }\n }\n return range\n}\n\n/// Compute known liveness and return a range, which the caller must deinitialize.\n///\n/// This computes a minimal liveness, ignoring pointer escaping uses.\n///\n/// The caller must call deinitialize() on the result.\nfunc computeKnownLiveness(for definingValue: Value, visitInnerUses: Bool = false, _ context: FunctionPassContext)\n -> InstructionRange {\n // Ignore pointer escapes and other failures.\n return InteriorLivenessResult.compute(for: definingValue, ignoreEscape: true,\n visitInnerUses: visitInnerUses, context).acquireRange\n}\n\n/// If any interior pointer may escape, then record the first instance here. If 'ignoseEscape' is true, this\n/// immediately aborts the walk, so further instances are unavailable.\n///\n/// .escaping may either be a non-address operand with\n/// .pointerEscape ownership, or and address operand that escapes\n/// the address (address_to_pointer).\n///\n/// .unknown is an address operand whose user is unrecognized.\nenum InteriorPointerStatus: CustomDebugStringConvertible {\n case nonescaping\n case escaping(SingleInlineArray<Operand>)\n case unknown(Operand)\n\n mutating func setEscaping(operand: Operand) {\n switch self {\n case .nonescaping:\n self = .escaping(SingleInlineArray(element: operand))\n case let .escaping(oldOperands):\n var newOperands = SingleInlineArray<Operand>()\n newOperands.append(contentsOf: oldOperands)\n newOperands.append(operand)\n self = .escaping(newOperands)\n case .unknown:\n break\n }\n }\n\n var debugDescription: String {\n switch self {\n case .nonescaping:\n return "No pointer escape"\n case let .escaping(operands):\n return "Pointer escapes: " + operands.map({ "\($0)" }).joined(separator: "\n ")\n case let .unknown(operand):\n return "Unknown use: \(operand)"\n }\n }\n}\n\ntypealias InnerScopeHandler = (Value) -> WalkResult\n\n/// An OSSA lifetime begins with a single "defining" value, which must be owned, or must begin a borrow scope. A\n/// complete OSSA lifetime has a linear lifetime, meaning that it has a lifetime-ending use on all paths. Interior\n/// liveness computes liveness without assuming the lifetime is complete. To do this, it must find all "use points" and\n/// prove that the defining value is never propagated beyond those points. This is used to initially complete OSSA\n/// lifetimes and fix them after transformations that's don't preserve OSSA.\n///\n/// Invariants:\n///\n/// - The definition dominates all use points (hence the result is a single InstructionRange).\n///\n/// - Liveness does not extend beyond lifetime-ending operations (a.k.a. affine lifetimes).\n///\n/// - All inner scopes are complete. (Use `innerScopeHandler` to either complete them or to recursively compute their\n/// liveness and either bail-out on or propagate inner pointer escapes outward).\nstruct InteriorLivenessResult: CustomDebugStringConvertible {\n // 'success' may only be set to .abortWalk if pointerStatus != .nonescaping or visitInnerUses returned false.\n // The client can therefore ensure success if it has already checked for pointer escapes.\n let success: WalkResult\n var range: InstructionRange\n let pointerStatus: InteriorPointerStatus\n\n /// Compute liveness for a single OSSA value without assuming a complete lifetime.\n ///\n /// The caller must call acquireRange or deinitialize() on the result.\n static func compute(for definingValue: Value, ignoreEscape: Bool = false, visitInnerUses: Bool,\n _ context: FunctionPassContext,\n innerScopeHandler: InnerScopeHandler? = nil) -> InteriorLivenessResult {\n\n assert(definingValue.ownership == .owned || BeginBorrowValue(definingValue) != nil,\n "value must define an OSSA lifetime")\n\n var range = InstructionRange(for: definingValue, context)\n\n var visitor = InteriorUseWalker(definingValue: definingValue, ignoreEscape: ignoreEscape,\n visitInnerUses: visitInnerUses, context) {\n range.insert($0.instruction)\n return .continueWalk\n }\n defer { visitor.deinitialize() }\n visitor.innerScopeHandler = innerScopeHandler\n let success = visitor.visitUses()\n assert(visitor.unenclosedPhis.isEmpty, "missing adjacent phis")\n let result = InteriorLivenessResult(success: success, range: range, pointerStatus: visitor.pointerStatus)\n log("Interior liveness for: \(definingValue)\n\(result)")\n return result\n }\n\n /// Client must call deinitialize() on the result.\n var acquireRange: InstructionRange { consuming get { range } }\n\n mutating func deinitialize() {\n range.deinitialize()\n }\n\n var debugDescription: String {\n "\(success)\n\(range)\n\(pointerStatus)"\n }\n}\n\n/// Classify ownership uses. This reduces operand ownership to a\n/// visitor API that can be used by def-use walkers to ensure complete\n/// handling of all legal SIL patterns.\n///\n/// Code that relies on the ownership effect of a use should conform\n/// to this visitor. This facilitates correct handling of special cases\n/// involving borrow scopes and interior pointers.\n///\n/// The top-level entry points are:\n/// - `classify(operand:)`\n/// - `visitOwnershipUses(of:)`\n///\n/// The implementation may recursively call back to the top-level\n/// entry points. Additionally, the implementation may recurse into inner\n/// borrow scopes, skipping over the uses within inner scopes using:\n/// - `visitInnerBorrowUses(of: BorrowingInstruction, operand:)`\n/// - `visitOwnedDependentUses(of: Value)`\n///\n/// Visitors implement:\n///\n/// - ownershipLeafUse(of:isInnerlifetime:)\n/// - forwardingUse(of:isInnerlifetime:)\n/// - interiorPointerUse(of:into:)\n/// - pointerEscapingUse(of:)\n/// - dependentUse(of:dependentValue:)\n/// - dependentUse(of:dependentAddress:)\n/// - borrowingUse(of:by:)\n///\n/// This only visits the first level of uses. The implementation may transitively visit forwarded, borrowed, dependent,\n/// or address values in the overrides listed above.\n///\n/// `isInnerlifetime` indicates whether the value being used is\n/// defined by the "outer" OSSA lifetime or an inner borrow scope.\n/// When the OwnershipUseVisitor is invoked on an outer value\n/// (visitOwnershipUses(of:)), it visits all the uses of that value\n/// and also visits the lifetime-ending uses of any inner borrow\n/// scopes. This provides a complete set of liveness "use points":\n///\n/// %0 = begin_borrow %outerValue\n/// %1 = begin_borrow %0\n/// end_borrow %1 // inner "use point" of %0\n/// end_borrow %0 // outer use of %0\n///\n/// This becomes more complicated with reborrows and closures. The\n/// implementation can simply rely on isInnerLifetime to know whether\n/// the value being used is part of the outer lifetimes vs. its inner\n/// lifetimes. This is important, for example, if the implementation\n/// wants to know if the use ends the lifetime of the outer value.\n///\n/// Visitor implementations treat inner and outer uses differently. It\n/// may, for example, assume that inner lifetimes are complete\n/// and therefore only care about the lifetime-ending uses.\nprotocol OwnershipUseVisitor {\n var context: Context { get }\n\n /// A non-forwarding use.\n ///\n /// `isInnerLifetime` indicates whether `operand` uses the original\n /// OSSA lifetime. This use ends the original lifetime if\n /// (!isInnerLifetime && use.endsLifetime).\n mutating func ownershipLeafUse(of operand: Operand, isInnerLifetime: Bool) -> WalkResult\n\n /// A forwarding operand.\n ///\n /// Use ForwardingInstruction or ForwardingDefUseWalker to handle\n /// downstream uses.\n ///\n /// If `isInnerLifetime` is true, then the value depends on an inner borrow.\n mutating func forwardingUse(of operand: Operand, isInnerLifetime: Bool) -> WalkResult\n\n /// A use that projects an address.\n mutating func interiorPointerUse(of: Operand, into address: Value) -> WalkResult\n\n /// A use that escapes information from its operand's value.\n ///\n /// Note: this may not find all relevant pointer escapes, such as\n /// from owned forwarded values. Clients should generally check\n /// findPointerEscape() before relying on a liveness result and\n /// implement this as a fatalError.\n mutating func pointerEscapingUse(of operand: Operand) -> WalkResult\n\n /// A use that creates an implicit borrow scope over the lifetime of\n /// an owned dependent value. The operand ownership is .borrow, but\n /// there are no explicit scope-ending operations. Instead\n /// BorrowingInstruction.scopeEndingOperands will return the final\n /// consumes in the dependent value's forwarding chain.\n mutating func dependentUse(of operand: Operand, dependentValue value: Value) -> WalkResult\n\n /// A use that creates an implicit borrow scope over all reachable uses of a value stored in\n /// `dependentAddress`. This could conservatively be handled has `pointerEscapingUse`, but note that accessing the\n /// `dependentAddress` only keeps the original owner alive, it cannot modify the original (modifying a dependent\n /// address is still just a "read" of the dependence source.\n mutating func dependentUse(of operand: Operand, dependentAddress address: Value) -> WalkResult\n\n /// A use that is scoped to an inner borrow scope.\n mutating func borrowingUse(of operand: Operand, by borrowInst: BorrowingInstruction) -> WalkResult\n}\n\nextension OwnershipUseVisitor {\n /// Classify a non-address type operand, dispatching to one of the\n /// protocol methods below.\n mutating func classify(operand: Operand) -> WalkResult {\n switch operand.value.ownership {\n case .owned:\n return classifyOwned(operand: operand)\n case .guaranteed:\n return classifyGuaranteed(operand: operand)\n case .none, .unowned:\n return .continueWalk\n }\n }\n\n /// Visit all uses that contribute to the ownership live\n /// range of `value`. This does not assume that `value` has a\n /// complete lifetime, and non-lifetime-ending uses are visited.\n ///\n /// If `value` is a phi (owned or reborrowed), then find its inner\n /// adjacent phis and treat them like inner borrows.\n ///\n /// This is only called for uses in the outer lifetime.\n mutating func visitOwnershipUses(of value: Value) -> WalkResult {\n switch value.ownership {\n case .owned:\n return value.uses.ignoreTypeDependence.walk { classifyOwned(operand: $0) }\n case .guaranteed:\n return value.uses.ignoreTypeDependence.walk {\n classifyGuaranteed(operand: $0) }\n case .none, .unowned:\n return .continueWalk\n }\n }\n\n /// Handle an owned dependent value, such as a closure capture or owned mark_dependence.\n ///\n /// Called by walkDownUses(of:) for owned values.\n ///\n /// When a borrow introduces an owned value, each OSSA lifetime is effectively a separate borrow scope. A destroy or\n /// consumes ends that borrow scope, while a forwarding consume effectively "reborrows".\n /// \n /// %dependent = mark_dependence [nonescaping] %owned on %base // borrow 'owned'\n /// // visit uses of owned 'dependent' value\n /// %forwarded = move_value %dependent\n /// destroy_value %forwarded // ends the inner borrow scope\n ///\n /// Preconditions:\n /// - value.ownership == .owned\n /// - value.type.isEscapable\n mutating func visitOwnedDependentUses(of value: Value) -> WalkResult {\n assert(value.ownership == .owned, "inner value must be a reborrow or owned forward")\n assert(value.type.isEscapable(in: value.parentFunction), "cannot handle non-escapable dependent values")\n return value.uses.endingLifetime.walk {\n switch $0.ownership {\n case .forwardingConsume:\n return forwardingUse(of: $0, isInnerLifetime: true)\n case .destroyingConsume:\n return ownershipLeafUse(of: $0, isInnerLifetime: true)\n default:\n fatalError("invalid owned lifetime ending operand ownership")\n }\n }\n }\n\n /// Visit uses of borrowing instruction (operandOwnerhip == .borrow),\n /// skipping uses within the borrow scope.\n ///\n /// %borrow = begin_borrow %def // visitInnerBorrowUses is called on this BorrowingInstruction\n /// %address = ref_element_addr %borrow // ignored\n /// end_borrow %borrow // visited as a leaf use of as inner lifetime.\n ///\n mutating func visitInnerBorrowUses(of borrowInst: BorrowingInstruction, operand: Operand) -> WalkResult {\n if let dependent = borrowInst.dependentValue {\n if dependent.ownership == .guaranteed {\n return visitOwnershipUses(of: dependent)\n }\n return pointerEscapingUse(of: operand)\n }\n // Otherwise, directly visit the scope ending uses as leaf uses.\n //\n // TODO: remove this stack by changing visitScopeEndingOperands to take a non-escaping closure.\n var stack = Stack<Operand>(context)\n defer { stack.deinitialize() }\n let result = borrowInst.visitScopeEndingOperands(context) {\n stack.push($0)\n return .continueWalk\n }\n guard result == .continueWalk else {\n // If the dependent value is not scoped then consider it a pointer escape.\n return pointerEscapingUse(of: operand)\n }\n return stack.walk { ownershipLeafUse(of: $0, isInnerLifetime: true) }\n }\n}\n\nextension OwnershipUseVisitor {\n // This is only called for uses in the outer lifetime.\n private mutating func classifyOwned(operand: Operand) -> WalkResult {\n switch operand.ownership {\n case .nonUse:\n return .continueWalk\n\n case .destroyingConsume:\n return ownershipLeafUse(of: operand, isInnerLifetime: false)\n\n case .forwardingConsume:\n return forwardingUse(of: operand, isInnerLifetime: false)\n\n case .pointerEscape:\n if let mdai = operand.instruction as? MarkDependenceAddrInst, operand == mdai.baseOperand {\n return dependentUse(of: operand, dependentAddress: mdai.address)\n }\n return pointerEscapingUse(of: operand)\n\n case .instantaneousUse, .forwardingUnowned, .unownedInstantaneousUse, .bitwiseEscape:\n return ownershipLeafUse(of: operand, isInnerLifetime: false)\n\n case .borrow:\n return visitBorrowingUse(of: operand)\n\n case .anyInteriorPointer:\n return visitInteriorPointerUse(of: operand)\n\n // TODO: .interiorPointer should instead be handled like .anyInteriorPointer.\n case .interiorPointer, .trivialUse, .endBorrow, .reborrow, .guaranteedForwarding:\n fatalError("ownership incompatible with an owned value");\n }\n }\n\n // This is only called for uses in the outer lifetime.\n private mutating func classifyGuaranteed(operand: Operand)\n -> WalkResult {\n switch operand.ownership {\n case .nonUse:\n return .continueWalk\n\n case .pointerEscape:\n // TODO: Change ProjectBox ownership to InteriorPointer and allow them to take owned values.\n if operand.instruction is ProjectBoxInst {\n return visitInteriorPointerUse(of: operand)\n }\n if let mdai = operand.instruction as? MarkDependenceAddrInst, operand == mdai.baseOperand {\n return dependentUse(of: operand, dependentAddress: mdai.address)\n }\n return pointerEscapingUse(of: operand)\n\n case .instantaneousUse, .forwardingUnowned, .unownedInstantaneousUse, .bitwiseEscape, .endBorrow, .reborrow:\n return ownershipLeafUse(of: operand, isInnerLifetime: false)\n\n case .guaranteedForwarding:\n return forwardingUse(of: operand, isInnerLifetime: false)\n\n case .borrow:\n return visitBorrowingUse(of: operand)\n\n case .interiorPointer, .anyInteriorPointer:\n return visitInteriorPointerUse(of: operand)\n\n case .trivialUse, .forwardingConsume, .destroyingConsume:\n fatalError("ownership incompatible with a guaranteed value")\n }\n }\n\n private mutating func visitBorrowingUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case let pai as PartialApplyInst:\n assert(!pai.mayEscape)\n return dependentUse(of: operand, dependentValue: pai)\n case let mdi as MarkDependenceInst:\n // .borrow operand ownership only applies to the base operand of a non-escaping markdep that forwards a\n // non-address value.\n assert(operand == mdi.baseOperand && mdi.isNonEscaping)\n return dependentUse(of: operand, dependentValue: mdi)\n case let bfi as BorrowedFromInst where !bfi.borrowedPhi.isReborrow:\n return dependentUse(of: operand, dependentValue: bfi)\n default:\n return borrowingUse(of: operand,\n by: BorrowingInstruction(operand.instruction)!)\n }\n }\n\n private mutating func visitInteriorPointerUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case is RefTailAddrInst, is RefElementAddrInst, is ProjectBoxInst,\n is OpenExistentialBoxInst:\n let svi = operand.instruction as! SingleValueInstruction\n return interiorPointerUse(of: operand, into: svi)\n default:\n return pointerEscapingUse(of: operand)\n }\n }\n}\n\n/// Visit all interior uses of an OSSA lifetime.\n///\n/// - `definingValue` dominates all uses. Only dominated phis extend\n/// the lifetime. All other phis must have a lifetime-ending outer\n/// adjacent phi; otherwise they will be recorded as `unenclosedPhis`.\n///\n/// - Does not assume the current lifetime is linear. Transitively\n/// follows guaranteed forwarding and address uses within the current\n/// scope. Phis that are not dominated by definingValue or an outer\n/// adjacent phi are marked "unenclosed" to signal an incomplete\n/// lifetime.\n///\n/// - Assumes inner scopes *are* linear, including borrow and address\n/// scopes (e.g. begin_borrow, load_borrow, begin_apply, store_borrow,\n/// begin_access) A `innerScopeHandler` callback may be used to\n/// complete inner scopes before updating liveness.\n///\n/// InteriorUseWalker can be used to complete (linearize) an OSSA\n/// lifetime after transformation that invalidates OSSA.\n///\n/// Example:\n///\n/// %s = struct ...\n/// %f = struct_extract %s // defines a guaranteed value (%f)\n/// %b = begin_borrow %f\n/// %a = ref_element_addr %b\n/// _ = address_to_pointer %a\n/// end_borrow %b // the only interior use of %f\n///\n/// When computing interior liveness for %f, %b is an inner\n/// scope. Because inner scopes are complete, the only relevant use is\n/// end_borrow %b. Despite the address_to_pointer instruction, %f does\n/// not escape any dependent address. \n///\n/// TODO: Implement the hasPointerEscape flags on BeginBorrowInst,\n/// MoveValueInst, and Allocation. Then this visitor should assert\n/// that the forward-extended lifetime introducer has no pointer\n/// escaping uses.\nstruct InteriorUseWalker {\n let functionContext: FunctionPassContext\n var context: Context { functionContext }\n\n let definingValue: Value\n let ignoreEscape: Bool\n\n // If true, it's not assumed that inner scopes are linear. It forces to visit\n // all interior uses if inner scopes.\n let visitInnerUses: Bool\n\n let useVisitor: (Operand) -> WalkResult\n\n var innerScopeHandler: InnerScopeHandler? = nil\n\n private func handleInner(borrowed value: Value) -> WalkResult {\n guard let innerScopeHandler else {\n return .continueWalk\n }\n return innerScopeHandler(value)\n }\n\n var unenclosedPhis: [Phi] = []\n\n var function: Function { definingValue.parentFunction }\n\n var pointerStatus: InteriorPointerStatus = .nonescaping\n\n private var visited: ValueSet\n\n mutating func deinitialize() {\n visited.deinitialize()\n }\n\n init(definingValue: Value, ignoreEscape: Bool, visitInnerUses: Bool, _ context: FunctionPassContext,\n visitor: @escaping (Operand) -> WalkResult) {\n assert(!definingValue.type.isAddress, "address values have no ownership")\n self.functionContext = context\n self.definingValue = definingValue\n self.ignoreEscape = ignoreEscape\n self.visitInnerUses = visitInnerUses\n self.useVisitor = visitor\n self.visited = ValueSet(context)\n }\n\n mutating func visitUses() -> WalkResult {\n return visitOwnershipUses(of: definingValue)\n }\n}\n\nextension InteriorUseWalker: OwnershipUseVisitor {\n /// This is invoked for all non-address uses of the outer lifetime,\n /// even if the use forwards a value or produces an interior\n /// pointer. This is only invoked for uses of an inner lifetime\n /// if it ends the lifetime.\n mutating func ownershipLeafUse(of operand: Operand, isInnerLifetime: Bool)\n -> WalkResult {\n useVisitor(operand)\n }\n\n // Visit owned and guaranteed forwarding operands.\n //\n // Guaranteed forwarding operands extend the outer lifetime.\n //\n // Owned forwarding operands end the outer lifetime but extend the\n // inner lifetime (e.g. from a PartialApply or MarkDependence).\n mutating func forwardingUse(of operand: Operand, isInnerLifetime: Bool)\n -> WalkResult {\n switch operand.value.ownership {\n case .guaranteed:\n assert(!isInnerLifetime, "inner guaranteed forwards are not walked")\n return walkDown(operand: operand)\n case .owned:\n return isInnerLifetime ? walkDown(operand: operand) : useVisitor(operand)\n default:\n fatalError("forwarded values must have a lifetime")\n }\n }\n\n mutating func interiorPointerUse(of operand: Operand, into address: Value)\n -> WalkResult {\n if useVisitor(operand) == .abortWalk {\n return .abortWalk\n }\n return walkDownAddressUses(of: address)\n }\n\n // Handle partial_apply [on_stack] and mark_dependence [nonescaping].\n mutating func dependentUse(of operand: Operand, dependentValue value: Value) -> WalkResult {\n // OSSA lifetime ignores trivial types.\n if value.type.isTrivial(in: function) {\n return .continueWalk\n }\n guard value.type.isEscapable(in: function) else {\n // Non-escapable dependent values can be lifetime-extended by copying, which is not handled by\n // InteriorUseWalker. LifetimeDependenceDefUseWalker does this.\n return pointerEscapingUse(of: operand)\n }\n if useVisitor(operand) == .abortWalk {\n return .abortWalk\n }\n return walkDownUses(of: value)\n }\n\n mutating func dependentUse(of operand: Operand, dependentAddress address: Value) -> WalkResult {\n // An mutable local variable depends a value that depends on the original interior pointer. This would require data\n // flow to find local uses. InteriorUseWalker only walks the SSA uses.\n pointerEscapingUse(of: operand)\n }\n\n mutating func pointerEscapingUse(of operand: Operand) -> WalkResult {\n if useVisitor(operand) == .abortWalk {\n return .abortWalk\n }\n return setPointerEscape(of: operand)\n }\n\n mutating func setPointerEscape(of operand: Operand) -> WalkResult {\n pointerStatus.setEscaping(operand: operand)\n return ignoreEscape ? .continueWalk : .abortWalk\n }\n\n // Call the innerScopeHandler before visiting the scope-ending uses.\n mutating func borrowingUse(of operand: Operand, by borrowInst: BorrowingInstruction) -> WalkResult {\n if let beginBorrow = BeginBorrowValue(resultOf: borrowInst) {\n if handleInner(borrowed: beginBorrow.value) == .abortWalk {\n return .abortWalk\n }\n }\n if useVisitor(operand) == .abortWalk {\n return .abortWalk\n }\n if visitInnerBorrowUses(of: borrowInst, operand: operand) == .abortWalk {\n return .abortWalk\n }\n if !visitInnerUses {\n return .continueWalk\n }\n guard let innerValue = borrowInst.innerValue else {\n return setPointerEscape(of: operand)\n }\n // Call visitInnerBorrowUses before visitOwnershipUses because it will visit uses of tokens, such as\n // the begin_apply token, which don't have ownership.\n if innerValue.type.isAddress {\n return interiorPointerUse(of: operand, into: innerValue)\n }\n return visitOwnershipUses(of: innerValue)\n }\n}\n\nextension InteriorUseWalker: AddressUseVisitor {\n /// An address projection produces a single address result and does not\n /// escape its address operand in any other way.\n mutating func projectedAddressUse(of operand: Operand, into value: Value)\n -> WalkResult {\n return walkDownAddressUses(of: value)\n }\n\n mutating func appliedAddressUse(of operand: Operand, by apply: FullApplySite)\n -> WalkResult {\n if apply is BeginApplyInst {\n return scopedAddressUse(of: operand)\n }\n return leafAddressUse(of: operand)\n }\n\n mutating func scopedAddressUse(of operand: Operand) -> WalkResult {\n switch operand.instruction {\n case let ba as BeginAccessInst:\n if handleInner(borrowed: ba) == .abortWalk {\n return .abortWalk\n }\n return ba.endOperands.walk { useVisitor($0) }\n case let ba as BeginApplyInst:\n if handleInner(borrowed: ba.token) == .abortWalk {\n return .abortWalk\n }\n return ba.token.uses.walk {\n useVisitor($0)\n }\n case let sb as StoreBorrowInst:\n if handleInner(borrowed: sb) == .abortWalk {\n return .abortWalk\n }\n return sb.uses.filterUsers(ofType: EndBorrowInst.self).walk {\n useVisitor($0)\n }\n case let load as LoadBorrowInst:\n if handleInner(borrowed: load) == .abortWalk {\n return .abortWalk\n }\n return load.uses.endingLifetime.walk {\n useVisitor($0)\n }\n default:\n fatalError("Unrecognized scoped address use: \(operand.instruction)")\n }\n }\n\n mutating func scopeEndingAddressUse(of operand: Operand) -> WalkResult {\n return .continueWalk\n }\n\n mutating func leafAddressUse(of operand: Operand) -> WalkResult {\n return .continueWalk\n }\n\n mutating func loadedAddressUse(of operand: Operand, intoValue value: Value)\n -> WalkResult {\n return .continueWalk\n } \n\n mutating func loadedAddressUse(of operand: Operand, intoAddress address: Operand)\n -> WalkResult {\n return .continueWalk\n }\n \n mutating func yieldedAddressUse(of operand: Operand) -> WalkResult {\n return .continueWalk\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentValue value: Value)\n -> WalkResult {\n // For Escapable values, simply continue the walk.\n if value.mayEscape {\n return walkDownUses(of: value)\n }\n // TODO: Handle non-escapable values by walking through copies as done by LifetimeDependenceDefUseWalker or\n // NonEscapingClosureDefUseWalker. But this code path also handles non-escaping closures that have not been promoted\n // to [on_stack] (and still have an escapable function type). Such closures may be incorrectly destroyed after their\n // captures. To avoid this problem, either rewrite ClosureLifetimeFixup to produce correct OSSA lifetimes, or check\n // for that special case and continue to bailout here.\n return escapingAddressUse(of: operand)\n }\n\n mutating func dependentAddressUse(of operand: Operand, dependentAddress address: Value) -> WalkResult {\n // TODO: consider data flow that finds reachable uses of `dependentAddress`.\n return escapingAddressUse(of: operand)\n } \n\n mutating func escapingAddressUse(of operand: Operand) -> WalkResult {\n pointerStatus.setEscaping(operand: operand)\n return ignoreEscape ? .continueWalk : .abortWalk\n }\n\n mutating func unknownAddressUse(of operand: Operand) -> WalkResult {\n pointerStatus = .unknown(operand)\n return .abortWalk\n }\n\n private mutating func walkDownAddressUses(of address: Value) -> WalkResult {\n assert(address.type.isAddress)\n return address.uses.ignoreTypeDependence.walk {\n // Record all uses\n if useVisitor($0) == .abortWalk {\n return .abortWalk\n }\n return classifyAddress(operand: $0)\n }\n }\n}\n\n// Helpers to walk down forwarding operations.\nextension InteriorUseWalker {\n // Walk down forwarding operands\n private mutating func walkDown(operand: Operand) -> WalkResult {\n // Record all uses\n if useVisitor(operand) == .abortWalk {\n return .abortWalk\n }\n if let inst = operand.instruction as? ForwardingInstruction {\n return inst.forwardedResults.walk { walkDownUses(of: $0) }\n }\n // TODO: verify that ForwardInstruction handles all .forward operand ownership and assert that only phis can be\n // reached: assert(Phi(using: operand) != nil)\n return .continueWalk\n }\n\n private mutating func walkDownUses(of value: Value) -> WalkResult {\n guard value.ownership.hasLifetime else {\n return .continueWalk\n }\n guard visited.insert(value) else {\n return .continueWalk\n }\n switch value.ownership {\n case .owned:\n // Each owned lifetime is an inner scope.\n if handleInner(borrowed: value) == .abortWalk {\n return .abortWalk\n }\n return visitOwnedDependentUses(of: value)\n case .guaranteed:\n // Handle a forwarded guaranteed value exactly like the outer borrow.\n return visitOwnershipUses(of: value)\n default:\n fatalError("ownership requires a lifetime")\n }\n }\n}\n\n/// Cache the liveness boundary by taking a snapshot of its InstructionRange.\nstruct LivenessBoundary : CustomStringConvertible {\n var lastUsers : Stack<Instruction>\n var boundaryEdges : Stack<BasicBlock>\n var deadDefs : Stack<Value>\n\n // Compute the boundary of a singly-defined range.\n init(value: Value, range: InstructionRange, _ context: Context) {\n assert(range.blockRange.isValid)\n\n lastUsers = Stack<Instruction>(context)\n boundaryEdges = Stack<BasicBlock>(context)\n deadDefs = Stack<Value>(context)\n\n lastUsers.append(contentsOf: range.ends)\n boundaryEdges.append(contentsOf: range.exitBlocks)\n if lastUsers.isEmpty {\n deadDefs.push(value)\n assert(boundaryEdges.isEmpty)\n }\n }\n\n var description: String {\n (lastUsers.map { "last user: \($0.description)" }\n + boundaryEdges.map { "boundary edge: \($0.description)" }\n + deadDefs.map { "dead def: \($0.description)" }).joined(separator: "\n")\n }\n\n mutating func deinitialize() {\n lastUsers.deinitialize()\n boundaryEdges.deinitialize()\n deadDefs.deinitialize()\n }\n}\n\nlet linearLivenessTest = FunctionTest("linear_liveness_swift") {\n function, arguments, context in\n let value = arguments.takeValue()\n print("Linear liveness: \(value)")\n var range = computeLinearLiveness(for: value, context)\n defer { range.deinitialize() }\n print("Live blocks:")\n print(range)\n var boundary = LivenessBoundary(value: value, range: range, context)\n defer { boundary.deinitialize() }\n print(boundary)\n}\n\nlet interiorLivenessTest = FunctionTest("interior_liveness_swift") {\n function, arguments, context in\n let value = arguments.takeValue()\n let visitInnerUses = arguments.hasUntaken ? arguments.takeBool() : false\n\n print("Interior liveness\(visitInnerUses ? " with inner uses" : ""): \(value)")\n\n var range = InstructionRange(for: value, context)\n defer { range.deinitialize() }\n\n var visitor = InteriorUseWalker(definingValue: value, ignoreEscape: true, visitInnerUses: visitInnerUses, context) {\n range.insert($0.instruction)\n return .continueWalk\n }\n defer { visitor.deinitialize() }\n\n visitor.innerScopeHandler = {\n print("Inner scope: \($0)")\n return .continueWalk\n }\n\n let success = visitor.visitUses()\n\n switch visitor.pointerStatus {\n case .nonescaping:\n break\n case let .escaping(operands):\n for operand in operands {\n print("Pointer escape: \(operand.instruction)")\n }\n case let .unknown(operand):\n print("Unrecognized SIL address user \(operand.instruction)")\n }\n if success == .abortWalk {\n print("Incomplete liveness")\n }\n print(range)\n\n var boundary = LivenessBoundary(value: value, range: range, context)\n defer { boundary.deinitialize() }\n print(boundary)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_OwnershipLiveness.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_OwnershipLiveness.swift
Swift
34,284
0.95
0.094923
0.347395
node-utils
892
2024-01-25T04:00:02.924404
GPL-3.0
false
0475e45c8ffe734fd905f69bd8bcecc0
//===--- PhiUpdater.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport OptimizerBridging\n\n/// Updates the reborrow flags and the borrowed-from instructions for all guaranteed phis in `function`.\nfunc updateGuaranteedPhis(in function: Function, _ context: some MutatingContext) {\n updateReborrowFlags(in: function, context)\n updateBorrowedFrom(in: function, context)\n}\n\n/// Updates the reborrow flags and the borrowed-from instructions for all `phis`.\nfunc updateGuaranteedPhis(phis: some Sequence<Phi>, _ context: some MutatingContext) {\n updateReborrowFlags(for: phis, context)\n updateBorrowedFrom(for: phis, context)\n}\n\n/// Update all borrowed-from instructions in the `function`\nfunc updateBorrowedFrom(in function: Function, _ context: some MutatingContext) {\n if !function.hasOwnership {\n return\n }\n var guaranteedPhis = Stack<Phi>(context)\n defer { guaranteedPhis.deinitialize() }\n\n for block in function.blocks {\n for arg in block.arguments {\n if let phi = Phi(arg), phi.value.ownership == .guaranteed {\n guaranteedPhis.append(phi)\n }\n }\n }\n updateBorrowedFrom(for: guaranteedPhis, context)\n}\n\n/// Update borrowed-from instructions for a set of phi arguments.\nfunc updateBorrowedFrom(for phis: some Sequence<Phi>, _ context: some MutatingContext) {\n for phi in phis {\n if !phi.value.parentFunction.hasOwnership {\n return\n }\n if phi.value.ownership == .guaranteed {\n createEmptyBorrowedFrom(for: phi, context)\n }\n }\n\n var changed: Bool\n repeat {\n changed = false\n\n for phi in phis {\n if phi.value.ownership == .guaranteed {\n changed = updateBorrowedFrom(for: phi, context) || changed\n }\n }\n } while changed\n}\n\n/// Updates the reborrow flags for all guaranteed phis in `function`.\nfunc updateReborrowFlags(in function: Function, _ context: some MutatingContext) {\n if !function.hasOwnership {\n return\n }\n var guaranteedPhis = Stack<Phi>(context)\n defer { guaranteedPhis.deinitialize() }\n\n for block in function.blocks.reversed() {\n for arg in block.arguments {\n if let phi = Phi(arg), phi.value.ownership == .guaranteed {\n guaranteedPhis.append(phi)\n }\n }\n }\n updateReborrowFlags(for: guaranteedPhis, context)\n}\n\n/// Updates the reborrow flags for all `phis`.\n///\n/// Re-borrow flags are only set, but never cleared. If an optimization creates a dead-end block\n/// by cutting off the control flow before an `end_borrow`, the re-borrow flags still have to remain\n/// without the possibility to re-calculate them from the (now missing) `end_borrow`.\n///\nfunc updateReborrowFlags(for phis: some Sequence<Phi>, _ context: some MutatingContext) {\n if let phi = phis.first(where: { phi in true }), !phi.value.parentFunction.hasOwnership {\n return\n }\n\n var changed: Bool\n repeat {\n changed = false\n\n for phi in phis where phi.value.ownership == .guaranteed {\n if !phi.value.isReborrow && phi.hasBorrowEndingUse {\n phi.value.set(reborrow: true, context)\n changed = true\n }\n }\n } while changed\n}\n\nprivate func updateBorrowedFrom(for phi: Phi, _ context: some MutatingContext) -> Bool {\n var computedEVs = Stack<Value>(context)\n defer { computedEVs.deinitialize() }\n gatherEnclosingValuesFromPredecessors(for: phi, in: &computedEVs, context)\n\n let borrowedFrom = phi.borrowedFrom!\n var existingEVs = ValueSet(insertContentsOf: borrowedFrom.enclosingValues, context)\n defer { existingEVs.deinitialize() }\n\n if computedEVs.allSatisfy({ existingEVs.contains($0) }) {\n return false\n }\n var evs = Array<Value>(borrowedFrom.enclosingValues)\n evs.append(contentsOf: computedEVs.lazy.filter { !existingEVs.contains($0) })\n\n let builder = Builder(before: borrowedFrom, context)\n let newBfi = builder.createBorrowedFrom(borrowedValue: borrowedFrom.borrowedValue, enclosingValues: evs)\n borrowedFrom.replace(with: newBfi, context)\n return true\n}\n\nprivate func createEmptyBorrowedFrom(for phi: Phi, _ context: some MutatingContext) {\n if let existingBfi = phi.borrowedFrom {\n if existingBfi.enclosingValues.isEmpty {\n return\n }\n existingBfi.replace(with: phi.value, context)\n }\n let builder = Builder(atBeginOf: phi.value.parentBlock, context)\n let bfi = builder.createBorrowedFrom(borrowedValue: phi.value, enclosingValues: [])\n phi.value.uses.ignoreUsers(ofType: BorrowedFromInst.self).replaceAll(with: bfi, context)\n}\n\n/// Replaces a phi with the unique incoming value if all incoming values are the same:\n/// ```\n/// bb1:\n/// br bb3(%1)\n/// bb2:\n/// br bb3(%1)\n/// bb3(%2 : $T): // Predecessors: bb1, bb2\n/// use(%2)\n/// ```\n/// ->\n/// ```\n/// bb1:\n/// br bb3\n/// bb2:\n/// br bb3\n/// bb3:\n/// use(%1)\n/// ```\n///\nfunc replacePhiWithIncomingValue(phi: Phi, _ context: some MutatingContext) -> Bool {\n if phi.predecessors.isEmpty {\n return false\n }\n let uniqueIncomingValue = phi.incomingValues.first!\n if !uniqueIncomingValue.parentFunction.hasOwnership {\n // For the SSAUpdater it's only required to simplify phis in OSSA.\n // This avoids that we need to handle cond_br instructions below.\n return false\n }\n if phi.incomingValues.contains(where: { $0 != uniqueIncomingValue }) {\n return false\n }\n if let borrowedFrom = phi.borrowedFrom {\n borrowedFrom.replace(with: uniqueIncomingValue, context)\n } else {\n phi.value.uses.replaceAll(with: uniqueIncomingValue, context)\n }\n\n let block = phi.value.parentBlock\n for incomingOp in phi.incomingOperands {\n let existingBranch = incomingOp.instruction as! BranchInst\n let argsWithRemovedPhiOp = existingBranch.operands.filter{ $0 != incomingOp }.map{ $0.value }\n Builder(before: existingBranch, context).createBranch(to: block, arguments: argsWithRemovedPhiOp)\n context.erase(instruction: existingBranch)\n }\n block.eraseArgument(at: phi.value.index, context)\n return true\n}\n\n/// Replaces phis with the unique incoming values if all incoming values are the same.\n/// This is needed after running the SSAUpdater for an existing OSSA value, because the updater can\n/// insert unnecessary phis in the middle of the original liverange which breaks up the original\n/// liverange into smaller ones:\n/// ```\n/// %1 = def_of_owned_value\n/// %2 = begin_borrow %1\n/// ...\n/// br bb2(%1)\n/// bb2(%3 : @owned $T): // inserted by SSAUpdater\n/// ...\n/// end_borrow %2 // use after end-of-lifetime!\n/// destroy_value %3\n/// ```\n///\n/// It's not needed to run this utility if SSAUpdater is used to create a _new_ OSSA liverange.\n///\nfunc replacePhisWithIncomingValues(phis: [Phi], _ context: some MutatingContext) {\n var currentPhis = phis\n // Do this in a loop because replacing one phi might open up the opportunity for another phi\n // and the order of phis in the array can be arbitrary.\n while true {\n var newPhis = [Phi]()\n for phi in currentPhis {\n if !replacePhiWithIncomingValue(phi: phi, context) {\n newPhis.append(phi)\n }\n }\n if newPhis.count == currentPhis.count {\n return\n }\n currentPhis = newPhis\n }\n}\n\nfunc registerPhiUpdater() {\n BridgedUtilities.registerPhiUpdater(\n // updateAllGuaranteedPhis\n { (bridgedCtxt: BridgedPassContext, bridgedFunction: BridgedFunction) in\n let context = FunctionPassContext(_bridged: bridgedCtxt)\n let function = bridgedFunction.function;\n updateGuaranteedPhis(in: function, context)\n },\n // updateGuaranteedPhis\n { (bridgedCtxt: BridgedPassContext, bridgedPhiArray: BridgedArrayRef) in\n let context = FunctionPassContext(_bridged: bridgedCtxt)\n var guaranteedPhis = Stack<Phi>(context)\n defer { guaranteedPhis.deinitialize() }\n bridgedPhiArray.withElements(ofType: BridgedValue.self) {\n for bridgedVal in $0 {\n let phi = Phi(bridgedVal.value)!\n if phi.value.ownership == .guaranteed {\n guaranteedPhis.append(phi)\n }\n }\n }\n updateGuaranteedPhis(phis: guaranteedPhis, context)\n },\n // replacePhisWithIncomingValues\n { (bridgedCtxt: BridgedPassContext, bridgedPhiArray: BridgedArrayRef) in\n let context = FunctionPassContext(_bridged: bridgedCtxt)\n var phis = [Phi]()\n bridgedPhiArray.withElements(ofType: BridgedValue.self) {\n phis = $0.map { Phi($0.value)! }\n }\n replacePhisWithIncomingValues(phis: phis, context)\n }\n )\n}\n\n/// This pass is only used for testing.\n/// In the regular pipeline it's not needed because optimization passes must make sure that borrowed-from\n/// instructions are updated once the pass finishes.\nlet updateBorrowedFromPass = FunctionPass(name: "update-borrowed-from") {\n (function: Function, context: FunctionPassContext) in\n\n updateBorrowedFrom(in: function, context)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_PhiUpdater.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_PhiUpdater.swift
Swift
9,240
0.95
0.27037
0.276423
vue-tools
801
2023-09-11T16:41:32.470141
BSD-3-Clause
false
4cee3f2bc1afab0b6f14f68fcde2ad1c
//===--- SpecializationCloner.swift --------------------------------------------==//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport OptimizerBridging\nimport SIL\n\n/// Utility cloner type that can be used by optimizations that generate new functions or specialized versions of\n/// existing functions. \nstruct SpecializationCloner {\n private let bridged: BridgedSpecializationCloner\n let context: FunctionPassContext\n\n init(emptySpecializedFunction: Function, _ context: FunctionPassContext) {\n self.bridged = BridgedSpecializationCloner(emptySpecializedFunction.bridged)\n self.context = context\n }\n \n var cloned: Function {\n bridged.getCloned().function\n }\n\n var entryBlock: BasicBlock {\n if cloned.blocks.isEmpty {\n return cloned.appendNewBlock(context)\n } else {\n return cloned.entryBlock\n }\n }\n\n func getClonedBlock(for originalBlock: BasicBlock) -> BasicBlock {\n bridged.getClonedBasicBlock(originalBlock.bridged).block\n }\n\n func cloneFunctionBody(from originalFunction: Function, entryBlockArguments: [Value]) {\n entryBlockArguments.withBridgedValues { bridgedEntryBlockArgs in\n bridged.cloneFunctionBody(originalFunction.bridged, self.entryBlock.bridged, bridgedEntryBlockArgs)\n }\n }\n\n}
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_SpecializationCloner.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_SpecializationCloner.swift
Swift
1,644
0.95
0.104167
0.317073
python-kit
212
2025-06-02T04:32:57.791784
GPL-3.0
false
ce6e5924f15f92b2d19e982f4d5801f4
//===--- SSAUpdater.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport OptimizerBridging\n\n/// Utility for updating SSA for a set of SIL instructions defined in multiple blocks.\nstruct SSAUpdater<Context: MutatingContext> {\n let context: Context\n\n init(function: Function, type: Type, ownership: Ownership,\n _ context: Context) {\n self.context = context\n context._bridged.SSAUpdater_initialize(function.bridged, type.bridged,\n ownership._bridged)\n }\n\n mutating func addAvailableValue(_ value: Value, in block: BasicBlock) {\n context._bridged.SSAUpdater_addAvailableValue(block.bridged, value.bridged)\n }\n\n /// Construct SSA for a value that is live at the *end* of a basic block.\n mutating func getValue(atEndOf block: BasicBlock) -> Value {\n context.notifyInstructionsChanged()\n return context._bridged.SSAUpdater_getValueAtEndOfBlock(block.bridged).value\n }\n\n /// Construct SSA for a value that is live in the *middle* of a block.\n /// This handles the case where the use is before a definition of the value in the same block.\n ///\n /// bb1:\n /// %1 = def\n /// br bb2\n /// bb2:\n /// = use(?)\n /// %2 = def\n /// cond_br bb2, bb3\n ///\n /// In this case we need to insert a phi argument in bb2, merging %1 and %2.\n mutating func getValue(inMiddleOf block: BasicBlock) -> Value {\n context.notifyInstructionsChanged()\n return context._bridged.SSAUpdater_getValueInMiddleOfBlock(block.bridged).value\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_SSAUpdater.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_SSAUpdater.swift
Swift
1,982
0.95
0.188679
0.531915
awesome-app
81
2024-07-25T10:39:34.985993
MIT
false
88f3a7a21923d6fb7875c1b63bd64e5e
//===--- StaticInitCloner.swift --------------------------------------------==//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport OptimizerBridging\n\n/// Clones the initializer value of a GlobalVariable.\n///\n/// Used to transitively clone "constant" instructions, including their operands,\n/// from or to the static initializer value of a GlobalVariable.\n///\nstruct StaticInitCloner<Context: MutatingContext> {\n private var bridged: BridgedCloner\n private let context: Context\n private let cloningIntoFunction: Bool\n\n init(cloneTo global: GlobalVariable, _ context: Context) {\n self.bridged = BridgedCloner(global.bridged, context._bridged)\n self.context = context\n self.cloningIntoFunction = false\n }\n\n init(cloneBefore inst: Instruction, _ context: Context) {\n self.bridged = BridgedCloner(inst.bridged, context._bridged)\n self.context = context\n self.cloningIntoFunction = true\n }\n\n mutating func deinitialize() {\n bridged.destroy(context._bridged)\n }\n\n /// Transitively clones `value` including its defining instruction's operands.\n mutating func clone(_ value: Value) -> Value {\n\n if isCloned(value: value) {\n return getClonedValue(of: value)\n }\n\n if let beginAccess = value as? BeginAccessInst {\n // Skip access instructions, which might be generated for UnsafePointer globals which point to other globals.\n let clonedOperand = clone(beginAccess.address)\n bridged.recordFoldedValue(beginAccess.bridged, clonedOperand.bridged)\n return clonedOperand\n }\n\n let inst = value.definingInstruction!\n assert(!(inst is ScopedInstruction), "global init value must not contain a scoped instruction")\n\n for op in inst.operands {\n _ = clone(op.value)\n }\n\n bridged.clone(inst.bridged)\n let clonedValue = getClonedValue(of: value)\n if cloningIntoFunction {\n context.notifyInstructionChanged(clonedValue.definingInstruction!)\n }\n return clonedValue\n }\n\n mutating func getClonedValue(of value: Value) -> Value {\n bridged.getClonedValue(value.bridged).value\n }\n\n func isCloned(value: Value) -> Bool {\n bridged.isValueCloned(value.bridged)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_StaticInitCloner.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_StaticInitCloner.swift
Swift
2,555
0.95
0.089744
0.276923
python-kit
798
2025-03-06T09:24:48.473410
MIT
false
566be107da3f86ce4c86f96a1bd8a6e6
//===--- Verifier.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SIL\nimport OptimizerBridging\n\nprivate protocol VerifiableInstruction : Instruction {\n func verify(_ context: FunctionPassContext)\n}\n\nprivate func require(_ condition: Bool, _ message: @autoclosure () -> String, atInstruction: Instruction? = nil) {\n if !condition {\n let msg = message()\n msg._withBridgedStringRef { stringRef in\n verifierError(stringRef, atInstruction.bridged, Optional<Argument>.none.bridged)\n }\n }\n}\n\nextension Function {\n func verify(_ context: FunctionPassContext) {\n for block in blocks {\n for arg in block.arguments {\n arg.verify(context)\n }\n for inst in block.instructions {\n\n inst.checkForwardingConformance()\n inst.checkGuaranteedResults()\n\n if let verifiableInst = inst as? VerifiableInstruction {\n verifiableInst.verify(context)\n }\n }\n }\n }\n}\n\nprivate extension Instruction {\n func checkForwardingConformance() {\n if bridged.shouldBeForwarding() {\n require(self is ForwardingInstruction, "instruction \(self)\nshould conform to ForwardingInstruction")\n } else {\n require(!(self is ForwardingInstruction), "instruction \(self)\nshould not conform to ForwardingInstruction")\n }\n }\n\n func checkGuaranteedResults() {\n for result in results where result.ownership == .guaranteed {\n require(BeginBorrowValue(result) != nil || self is ForwardingInstruction,\n "\(result) must either be a BeginBorrowValue or a ForwardingInstruction")\n }\n }\n}\n\nprivate extension Argument {\n func verify(_ context: FunctionPassContext) {\n if let phi = Phi(self), phi.value.ownership == .guaranteed {\n\n phi.verifyBorrowedFromUse()\n\n require(phi.isReborrow == phi.hasBorrowEndingUse ||\n // In a dead-end block an end_borrow might have been deleted.\n // TODO: this check is not needed anymore once we have complete OSSA lifetimes.\n (isReborrow && context.deadEndBlocks.isDeadEnd(parentBlock)),\n "\(self) has stale reborrow flag");\n }\n }\n\n}\n\nprivate extension Phi {\n func verifyBorrowedFromUse() {\n var forwardingBorrowedFromFound = false\n for use in value.uses {\n require(use.instruction is BorrowedFromInst,\n "guaranteed phi: \(self)\n has non borrowed-from use: \(use)")\n if use.index == 0 {\n require(!forwardingBorrowedFromFound, "phi \(self) has multiple forwarding borrowed-from uses")\n forwardingBorrowedFromFound = true\n }\n }\n require(forwardingBorrowedFromFound,\n "missing forwarding borrowed-from user of guaranteed phi \(self)")\n }\n}\n\nextension BorrowedFromInst : VerifiableInstruction {\n func verify(_ context: FunctionPassContext) {\n\n for ev in enclosingValues {\n require(ev.isValidEnclosingValueInBorrowedFrom, "invalid enclosing value in borrowed-from: \(ev)")\n }\n\n var computedEVs = Stack<Value>(context)\n defer { computedEVs.deinitialize() }\n\n guard let phi = Phi(borrowedValue) else {\n fatalError("borrowed value of borrowed-from must be a phi: \(self)")\n }\n gatherEnclosingValuesFromPredecessors(for: phi, in: &computedEVs, context)\n\n var existingEVs = ValueSet(insertContentsOf: enclosingValues, context)\n defer { existingEVs.deinitialize() }\n\n for computedEV in computedEVs {\n require(existingEVs.contains(computedEV),\n "\(computedEV)\n missing in enclosing values of \(self)")\n }\n }\n}\n\nprivate extension Value {\n var isValidEnclosingValueInBorrowedFrom: Bool {\n switch ownership {\n case .owned:\n return true\n case .guaranteed:\n return BeginBorrowValue(self) != nil ||\n self is BorrowedFromInst ||\n forwardingInstruction != nil\n case .none, .unowned:\n return false\n }\n }\n}\n\nextension LoadBorrowInst : VerifiableInstruction {\n func verify(_ context: FunctionPassContext) {\n if isUnchecked {\n return\n }\n\n var mutatingInstructions = MutatingUsesWalker(context)\n defer { mutatingInstructions.deinitialize() }\n\n mutatingInstructions.findMutatingUses(of: self.address)\n mutatingInstructions.verifyNoMutatingUsesInLiverange(of: self)\n }\n}\n\n// Used to check if any instruction is mutating the memory location within the liverange of a `load_borrow`.\n// Note that it is not checking if an instruction _may_ mutate the memory, but it's checking if any instruction\n// _definitely_ will mutate the memory.\n// Otherwise the risk would be too big for false alarms. It also means that this verification is not perfect and\n// might miss some subtle violations.\nprivate struct MutatingUsesWalker : AddressDefUseWalker {\n let context: FunctionPassContext\n var mutatingInstructions: InstructionSet\n\n init(_ context: FunctionPassContext) {\n self.context = context\n self.mutatingInstructions = InstructionSet(context)\n }\n\n mutating func deinitialize() {\n self.mutatingInstructions.deinitialize()\n }\n\n mutating func findMutatingUses(of address: Value) {\n _ = walkDownUses(ofAddress: address, path: UnusedWalkingPath())\n }\n\n mutating func verifyNoMutatingUsesInLiverange(of load: LoadBorrowInst) {\n // The liverange of a `load_borrow` can end in a branch instruction. In such cases we handle the re-borrow liveranges\n // (starting at the `borrowed_from` in the successor block) separately.\n // This worklist contains the starts of the individual linear liveranges,\n // i.e. `load_borrow` and `borrowed_from` instructions.\n var linearLiveranges = SpecificInstructionWorklist<SingleValueInstruction>(context)\n defer { linearLiveranges.deinitialize() }\n\n linearLiveranges.pushIfNotVisited(load)\n while let startInst = linearLiveranges.pop() {\n verifyNoMutatingUsesInLinearLiverange(of: startInst)\n\n for use in startInst.uses {\n if let phi = Phi(using: use) {\n if let bf = phi.borrowedFrom {\n linearLiveranges.pushIfNotVisited(bf)\n } else {\n require(false, "missing borrowed-from for \(phi.value)")\n }\n }\n }\n }\n }\n\n private mutating func verifyNoMutatingUsesInLinearLiverange(of startInst: SingleValueInstruction) {\n assert(startInst is LoadBorrowInst || startInst is BorrowedFromInst)\n\n var instWorklist = InstructionWorklist(context)\n defer { instWorklist.deinitialize() }\n\n // It would be good enough to only consider `end_borrow`s (and branches), but adding all users doesn't harm.\n for use in startInst.uses {\n instWorklist.pushPredecessors(of: use.instruction, ignoring: startInst)\n }\n\n while let inst = instWorklist.pop() {\n require(!mutatingInstructions.contains(inst),\n "Load borrow invalidated by a local write", atInstruction: inst)\n instWorklist.pushPredecessors(of: inst, ignoring: startInst)\n }\n }\n\n mutating func leafUse(address: Operand, path: UnusedWalkingPath) -> WalkResult {\n if address.isMutatedAddress {\n mutatingInstructions.insert(address.instruction)\n }\n return .continueWalk\n }\n}\n\nprivate extension Operand {\n // Returns true if the operand's instruction is definitely writing to the operand's address value.\n var isMutatedAddress: Bool {\n assert(value.type.isAddress)\n switch instruction {\n case let store as StoringInstruction:\n return self == store.destinationOperand\n case let copy as SourceDestAddrInstruction:\n if self == copy.destinationOperand {\n return true\n } else if self == copy.sourceOperand && copy.isTakeOfSrc {\n return true\n }\n return false\n case let load as LoadInst:\n return load.loadOwnership == .take\n case let partialApply as PartialApplyInst:\n if !partialApply.isOnStack,\n let convention = partialApply.convention(of: self)\n {\n switch convention {\n case .indirectIn, .indirectInGuaranteed:\n // Such operands are consumed by the `partial_apply` and therefore cound as "written".\n return true\n default:\n return false\n }\n }\n return false\n case is DestroyAddrInst, is IsUniqueInst:\n return true\n default:\n return false\n }\n }\n}\n\nfunc registerVerifier() {\n BridgedUtilities.registerVerifier(\n { (bridgedCtxt: BridgedPassContext, bridgedFunction: BridgedFunction) in\n let context = FunctionPassContext(_bridged: bridgedCtxt)\n bridgedFunction.function.verify(context)\n }\n )\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_Verifier.swift
cpp_apple_swift_SwiftCompilerSources_Sources_Optimizer_Utilities_Verifier.swift
Swift
8,938
0.95
0.134831
0.108696
awesome-app
637
2024-01-12T23:57:31.547314
GPL-3.0
false
f369a429dcff31ed08bb15c7c41b99a3
//===--- ApplySite.swift - Defines the ApplySite protocols ----------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\n/// Argument conventions indexed on an apply's operand.\n///\n/// `partial_apply` operands correspond to a suffix of the callee\n/// arguments.\n///\n/// Example:\n/// ```\n/// func callee(a, b, c, d, e) { }\n///\n/// %pa = partial_apply @callee(c, d, e)\n/// // operand indices: 1, 2, 3\n/// // callee indices: 2, 3, 4\n///\n/// %a = apply %pa (a, b)\n/// // operand indices: 1, 2\n/// // callee indices: 0, 1\n/// ```\npublic struct ApplyOperandConventions : Collection {\n public static let calleeIndex: Int = 0\n public static let firstArgumentIndex = 1\n\n /// Callee's argument conventions indexed on the function's arguments.\n public let calleeArgumentConventions: ArgumentConventions\n\n public let unappliedArgumentCount: Int\n\n public var appliedArgumentCount: Int {\n calleeArgumentConventions.count - unappliedArgumentCount\n }\n\n public var startIndex: Int { ApplyOperandConventions.firstArgumentIndex }\n\n public var endIndex: Int { ApplyOperandConventions.firstArgumentIndex + appliedArgumentCount }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ operandIndex: Int) -> ArgumentConvention {\n return calleeArgumentConventions[\n calleeArgumentIndex(ofOperandIndex: operandIndex)!]\n }\n\n public subscript(result operandIndex: Int) -> ResultInfo? {\n return calleeArgumentConventions[result:\n calleeArgumentIndex(ofOperandIndex: operandIndex)!]\n }\n\n public subscript(parameter operandIndex: Int) -> ParameterInfo? {\n return calleeArgumentConventions[parameter:\n calleeArgumentIndex(ofOperandIndex: operandIndex)!]\n }\n\n public subscript(resultDependsOn operandIndex: Int)\n -> LifetimeDependenceConvention? {\n return calleeArgumentConventions[resultDependsOn:\n calleeArgumentIndex(ofOperandIndex: operandIndex)!]\n }\n\n public subscript(parameterDependencies operandIndex: Int)\n -> FunctionConvention.LifetimeDependencies? {\n return calleeArgumentConventions[parameterDependencies:\n calleeArgumentIndex(ofOperandIndex: operandIndex)!]\n }\n\n public var firstParameterOperandIndex: Int {\n return ApplyOperandConventions.firstArgumentIndex +\n calleeArgumentConventions.firstParameterIndex\n }\n\n // TODO: rewrite uses of this API to avoid manipulating integer\n // indices, and make this private. No client should have multiple\n // integer indices, some of which are caller indices, and some of\n // which are callee indices.\n public func calleeArgumentIndex(ofOperandIndex index: Int) -> Int? {\n let callerArgIdx = index - startIndex\n if callerArgIdx < 0 {\n return nil\n }\n let calleeArgIdx = callerArgIdx + unappliedArgumentCount\n assert(calleeArgIdx < calleeArgumentConventions.count,\n "invalid operand index")\n return calleeArgIdx\n }\n\n // TODO: this should be private.\n public func calleeArgumentIndex(of operand: Operand) -> Int? {\n calleeArgumentIndex(ofOperandIndex: operand.index)\n }\n}\n\npublic protocol ApplySite : Instruction {\n var operands: OperandArray { get }\n var numArguments: Int { get }\n var substitutionMap: SubstitutionMap { get }\n\n var unappliedArgumentCount: Int { get }\n}\n\nextension ApplySite {\n public var callee: Value { operands[ApplyOperandConventions.calleeIndex].value }\n\n public var hasSubstitutions: Bool {\n return substitutionMap.hasAnySubstitutableParams\n }\n\n public var isAsync: Bool {\n return callee.type.isAsyncFunction\n }\n\n public var referencedFunction: Function? {\n if let fri = callee as? FunctionRefInst {\n return fri.referencedFunction\n }\n return nil\n }\n\n public func hasSemanticsAttribute(_ attr: StaticString) -> Bool {\n if let callee = referencedFunction {\n return callee.hasSemanticsAttribute(attr)\n }\n return false\n }\n\n public var isCalleeNoReturn: Bool {\n bridged.ApplySite_isCalleeNoReturn() \n }\n\n public var isCalleeTrapNoReturn: Bool {\n referencedFunction?.isTrapNoReturn ?? false\n }\n\n /// Returns the subset of operands which are argument operands.\n ///\n /// This does not include the callee function operand.\n public var argumentOperands: OperandArray {\n let numArgs = bridged.ApplySite_getNumArguments()\n let offset = ApplyOperandConventions.firstArgumentIndex\n return operands[offset..<(numArgs + offset)]\n }\n\n /// Returns the subset of operands that are parameters. This does\n /// not include indirect results. This does include 'self'.\n public var parameterOperands: OperandArray {\n let firstParamIdx =\n operandConventions.calleeArgumentConventions.firstParameterIndex\n let argOpers = argumentOperands // bridged call\n return argOpers[firstParamIdx..<argOpers.count]\n }\n\n /// Returns the subset of operand values which are arguments.\n ///\n /// This does not include the callee function operand.\n public var arguments: LazyMapSequence<OperandArray, Value> {\n argumentOperands.values\n }\n\n /// Indirect results including the error result.\n public var indirectResultOperands: OperandArray {\n let ops = operandConventions\n return operands[ops.startIndex..<ops.firstParameterOperandIndex]\n }\n\n public func isIndirectResult(operand: Operand) -> Bool {\n let idx = operand.index\n let ops = operandConventions\n return idx >= ops.startIndex && idx < ops.firstParameterOperandIndex\n }\n\n public var substitutionMap: SubstitutionMap {\n SubstitutionMap(bridged: bridged.ApplySite_getSubstitutionMap())\n }\n\n public var calleeArgumentConventions: ArgumentConventions {\n ArgumentConventions(convention: functionConvention)\n }\n\n public var operandConventions: ApplyOperandConventions {\n ApplyOperandConventions(\n calleeArgumentConventions: calleeArgumentConventions,\n unappliedArgumentCount: bridged.PartialApply_getCalleeArgIndexOfFirstAppliedArg())\n }\n\n /// Returns true if `operand` is the callee function operand and not am argument operand.\n public func isCallee(operand: Operand) -> Bool {\n operand.index == ApplyOperandConventions.calleeIndex\n }\n\n public func convention(of operand: Operand) -> ArgumentConvention? {\n let idx = operand.index\n return idx < operandConventions.startIndex ? nil : operandConventions[idx]\n }\n\n public func result(for operand: Operand) -> ResultInfo? {\n let idx = operand.index\n return idx < operandConventions.startIndex ? nil\n : operandConventions[result: idx]\n }\n\n public func parameter(for operand: Operand) -> ParameterInfo? {\n let idx = operand.index\n return idx < operandConventions.startIndex ? nil\n : operandConventions[parameter: idx]\n }\n\n public func resultDependence(on operand: Operand)\n -> LifetimeDependenceConvention? {\n let idx = operand.index\n return idx < operandConventions.startIndex ? nil\n : operandConventions[resultDependsOn: idx]\n }\n\n public var hasResultDependence: Bool {\n functionConvention.resultDependencies != nil\n }\n\n public func isAddressable(operand: Operand) -> Bool {\n if let dep = resultDependence(on: operand) {\n return dep.isAddressable(for: operand.value)\n }\n return false\n }\n\n public var hasLifetimeDependence: Bool {\n functionConvention.hasLifetimeDependencies()\n }\n\n public func parameterDependencies(target operand: Operand) -> FunctionConvention.LifetimeDependencies? {\n let idx = operand.index\n return idx < operandConventions.startIndex ? nil\n : operandConventions[parameterDependencies: idx]\n }\n\n public var yieldConventions: YieldConventions {\n YieldConventions(convention: functionConvention)\n }\n\n public func convention(of yield: MultipleValueInstructionResult)\n -> ArgumentConvention {\n assert(yield.definingInstruction == self)\n return yieldConventions[yield.index]\n }\n\n /// Converts an argument index of a callee to the corresponding apply operand.\n ///\n /// If the apply does not actually apply that argument, it returns nil.\n ///\n /// Example:\n /// ```\n /// func callee(v, w, x, y, z) { }\n /// // caller operands in %pa: -, -, c, d, e ("-" == nil)\n /// // caller operands in %a: a, b, -, -, -\n ///\n /// %pa = partial_apply @callee(c, d, e)\n /// %a = apply %pa (a, b)\n /// ```\n ///\n /// TODO: delete this API and rewrite the users. \n public func operand(forCalleeArgumentIndex calleeArgIdx: Int) -> Operand? {\n let callerArgIdx = calleeArgIdx - operandConventions.unappliedArgumentCount\n guard callerArgIdx >= 0 && callerArgIdx < numArguments else { return nil }\n return argumentOperands[callerArgIdx]\n }\n\n /// Returns the argument index of an operand.\n ///\n /// Returns nil if 'operand' is not an argument operand. This is the case if\n /// it's the callee function operand.\n ///\n /// Warning: the returned integer can be misused as an index into\n /// the wrong collection. Replace uses of this API with safer APIs.\n ///\n /// TODO: delete this API and rewrite the users. \n public func calleeArgumentIndex(of operand: Operand) -> Int? {\n operandConventions.calleeArgumentIndex(of: operand)\n }\n}\n\nextension ApplySite {\n public var functionConvention: FunctionConvention {\n FunctionConvention(for: substitutedCalleeType, in: parentFunction)\n }\n\n public var substitutedCalleeType: CanonicalType {\n CanonicalType(bridged: bridged.ApplySite_getSubstitutedCalleeType())\n }\n}\n\npublic protocol FullApplySite : ApplySite {\n var singleDirectResult: Value? { get }\n var singleDirectErrorResult: Value? { get }\n}\n\nextension FullApplySite {\n public var unappliedArgumentCount: Int { 0 }\n\n /// The number of indirect out arguments.\n ///\n /// 0 if the callee has a direct or no return value and 1, if it has an indirect return value.\n ///\n /// FIXME: This is incorrect in two cases: it does not include the\n /// indirect error result, and, prior to address lowering, does not\n /// include pack results.\n public var numIndirectResultArguments: Int {\n return bridged.FullApplySite_numIndirectResultArguments()\n }\n\n /// The direct result or yields produced by this apply. This does\n /// not include any potential results returned by a coroutine\n /// (end_apply results).\n public var resultOrYields: SingleInlineArray<Value> {\n var values = SingleInlineArray<Value>()\n if let beginApply = self as? BeginApplyInst {\n beginApply.yieldedValues.forEach { values.push($0) }\n } else {\n let result = singleDirectResult!\n if !result.type.isVoid {\n values.push(result)\n }\n }\n return values\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ApplySite.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ApplySite.swift
Swift
11,028
0.95
0.065089
0.272727
awesome-app
258
2023-11-04T15:32:51.493827
BSD-3-Clause
false
5f0eba7161e81f38cf7f797214def0e5
//===--- Argument.swift - Defines the Argument classes --------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\n/// A basic block argument.\n///\n/// Maps to both, SILPhiArgument and SILFunctionArgument.\npublic class Argument : Value, Hashable {\n public var definingInstruction: Instruction? { nil }\n\n public var parentBlock: BasicBlock {\n return bridged.getParent().block\n }\n\n public var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) }\n\n public var index: Int {\n return parentBlock.arguments.firstIndex(of: self)!\n }\n\n public var isReborrow: Bool { bridged.isReborrow() }\n\n public var isLexical: Bool { false }\n\n public var varDecl: VarDecl? { bridged.getVarDecl().getAs(VarDecl.self) }\n\n public var sourceLoc: SourceLoc? { varDecl?.nameLoc }\n\n public static func ==(lhs: Argument, rhs: Argument) -> Bool {\n lhs === rhs\n }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfinal public class FunctionArgument : Argument {\n public var convention: ArgumentConvention {\n parentFunction.argumentConventions[index]\n }\n\n public override var isLexical: Bool {\n bridged.FunctionArgument_isLexical()\n }\n\n public var isSelf: Bool {\n parentFunction.argumentConventions.selfIndex == index\n }\n\n // FIXME: This is incorrect in two cases: it does not include the\n // indirect error result, and, prior to address lowering, does not\n // include pack results.\n public var isIndirectResult: Bool {\n return index < parentFunction.numIndirectResultArguments\n }\n\n /// If the function's result depends on this argument, return the\n /// kind of dependence.\n public var resultDependence: LifetimeDependenceConvention? {\n parentFunction.argumentConventions[resultDependsOn: index]\n }\n\n /// Copies the following flags from `arg`:\n /// 1. noImplicitCopy\n /// 2. lifetimeAnnotation\n /// 3. closureCapture\n /// 4. parameterPack\n public func copyFlags(from arg: FunctionArgument) {\n bridged.copyFlags(arg.bridged)\n }\n}\n\npublic struct Phi {\n public let value: Argument\n\n // TODO: Remove the CondBr case. All passes avoid critical edges. It\n // is only included here for compatibility with .sil tests that have\n // not been migrated.\n public init?(_ value: Value) {\n guard let argument = value as? Argument else {\n return nil\n }\n var preds = argument.parentBlock.predecessors\n if let pred = preds.next() {\n let term = pred.terminator\n guard term is BranchInst || term is CondBranchInst else {\n return nil\n }\n } else {\n // No predecessors indicates an unreachable block (except for function arguments).\n // Treat this like a degenerate phi so we don't consider it a terminator result.\n if argument is FunctionArgument {\n return nil\n }\n }\n self.value = argument\n }\n\n public init?(using operand: Operand) {\n switch operand.instruction {\n case let br as BranchInst:\n self.init(br.getArgument(for: operand))\n case let condBr as CondBranchInst:\n guard let arg = condBr.getArgument(for: operand) else { return nil }\n self.init(arg)\n default:\n return nil\n }\n }\n\n public var predecessors: PredecessorList {\n return value.parentBlock.predecessors\n }\n\n public var successor: BasicBlock {\n return value.parentBlock\n }\n\n public func incomingOperand(inPredecessor predecessor: BasicBlock)\n -> Operand {\n let blockArgIdx = value.index\n switch predecessor.terminator {\n case let br as BranchInst:\n return br.operands[blockArgIdx]\n case let condBr as CondBranchInst:\n if condBr.trueBlock == successor {\n assert(condBr.falseBlock != successor)\n return condBr.trueOperands[blockArgIdx]\n } else {\n assert(condBr.falseBlock == successor)\n return condBr.falseOperands[blockArgIdx]\n }\n default:\n fatalError("wrong terminator for phi-argument")\n }\n }\n\n public var incomingOperands: LazyMapSequence<PredecessorList, Operand> {\n predecessors.lazy.map { incomingOperand(inPredecessor: $0) }\n }\n\n public var incomingValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> {\n incomingOperands.lazy.map { $0.value }\n }\n\n public var isReborrow: Bool { value.isReborrow }\n\n public var endsLifetime: Bool {\n value.ownership == .owned || value.isReborrow\n }\n\n public var borrowedFrom: BorrowedFromInst? {\n for use in value.uses {\n if let bfi = use.forwardingBorrowedFromUser {\n return bfi\n }\n }\n return nil\n }\n\n // Returns true if the phi has an end_borrow or a re-borrowing branch as user.\n // This should be consistent with the `isReborrow` flag.\n public var hasBorrowEndingUse: Bool {\n let phiValue: Value = borrowedFrom ?? value\n return phiValue.uses.contains {\n switch $0.ownership {\n case .endBorrow, .reborrow: return true\n default: return false\n }\n }\n }\n\n public static func ==(lhs: Phi, rhs: Phi) -> Bool {\n lhs.value === rhs.value\n }\n\n public func hash(into hasher: inout Hasher) {\n value.hash(into: &hasher)\n }\n}\n\nextension Phi {\n /// Return true of this phi is directly returned with no side effects between the phi and the return.\n public var isReturnValue: Bool {\n if let singleUse = value.uses.singleUse, let ret = singleUse.instruction as? ReturnInst,\n ret.parentBlock == successor {\n for inst in successor.instructions {\n if inst.mayHaveSideEffects {\n return false\n }\n }\n return true\n }\n return false\n }\n}\n\nextension Operand {\n public var forwardingBorrowedFromUser: BorrowedFromInst? {\n if let bfi = instruction as? BorrowedFromInst, index == 0 {\n return bfi\n }\n return nil\n }\n}\n\npublic struct TerminatorResult {\n public let value: Argument\n\n public init?(_ value: Value) {\n guard let argument = value as? Argument else { return nil }\n var preds = argument.parentBlock.predecessors\n guard let pred = preds.next() else { return nil }\n let term = pred.terminator\n if term is BranchInst || term is CondBranchInst { return nil }\n self.value = argument\n }\n\n public var terminator: TermInst {\n var preds = value.parentBlock.predecessors\n return preds.next()!.terminator\n }\n \n public var predecessor: BasicBlock {\n return terminator.parentBlock\n }\n\n public var successor: BasicBlock {\n return value.parentBlock\n }\n\n public static func ==(lhs: TerminatorResult, rhs: TerminatorResult) -> Bool {\n lhs.value == rhs.value\n }\n\n public func hash(into hasher: inout Hasher) {\n value.hash(into: &hasher)\n }\n}\n\n/// ArgumentConventions indexed on a SIL function's argument index.\n/// When derived from an ApplySite, this corresponds to the callee\n/// function's argument index.\n///\n/// When derived from an ApplySite, `convention` is the substituted\n/// convention. Substitution only affects the type inside ResultInfo\n/// and ParameterInfo. It does not change the resulting\n/// ArgumentConvention, ResultConvention, or LifetimeDependenceInfo.\npublic struct ArgumentConventions : Collection, CustomStringConvertible {\n public let convention: FunctionConvention\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int {\n firstParameterIndex + convention.parameters.count\n }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ argumentIndex: Int) -> ArgumentConvention {\n if let paramIdx = parameterIndex(for: argumentIndex) {\n return convention.parameters[paramIdx].convention\n }\n let resultInfo = convention.indirectSILResults[argumentIndex]\n return ArgumentConvention(result: resultInfo.convention)\n }\n\n public subscript(result argumentIndex: Int) -> ResultInfo? {\n if parameterIndex(for: argumentIndex) != nil {\n return nil\n }\n return convention.indirectSILResults[argumentIndex]\n }\n\n public subscript(parameter argumentIndex: Int) -> ParameterInfo? {\n guard let paramIdx = parameterIndex(for: argumentIndex) else {\n return nil\n }\n return convention.parameters[paramIdx]\n }\n\n public subscript(parameterDependencies targetArgumentIndex: Int) -> FunctionConvention.LifetimeDependencies? {\n guard let targetParamIdx = parameterIndex(for: targetArgumentIndex) else {\n return nil\n }\n return convention.parameterDependencies(for: targetParamIdx)\n }\n\n /// Return a dependence of the function results on the indexed parameter.\n public subscript(resultDependsOn argumentIndex: Int) -> LifetimeDependenceConvention? {\n findDependence(source: argumentIndex, in: convention.resultDependencies)\n }\n\n /// Return a dependence of the target argument on the source argument.\n public func getDependence(target targetArgumentIndex: Int, source sourceArgumentIndex: Int)\n -> LifetimeDependenceConvention? {\n findDependence(source: sourceArgumentIndex, in: self[parameterDependencies: targetArgumentIndex])\n }\n\n /// Number of SIL arguments for the function type's results\n /// including the error result. Use this to avoid lazy iteration\n /// over indirectSILResults to find the count.\n var indirectSILResultCount: Int {\n convention.indirectSILResultCount\n }\n\n /// The SIL argument index of the function type's first parameter.\n public var firstParameterIndex: Int { indirectSILResultCount }\n\n /// The SIL argument index of the 'self' parameter.\n var selfIndex: Int? {\n guard convention.hasSelfParameter else { return nil }\n // self is the last parameter\n return endIndex - 1\n }\n\n public var description: String {\n var str = convention.functionType.description\n for idx in startIndex..<indirectSILResultCount {\n str += "\n[\(idx)] indirect result: " + self[idx].description\n }\n for idx in indirectSILResultCount..<endIndex {\n str += "\n[\(idx)] parameter: " + self[idx].description\n if let deps = self[parameterDependencies: idx] {\n str += "\n lifetime: \(deps)"\n }\n if let dep = self[resultDependsOn: idx] {\n str += "\n result dependence: " + dep.description\n }\n }\n return str\n }\n}\n\nextension ArgumentConventions {\n private func parameterIndex(for argIdx: Int) -> Int? {\n let firstParamIdx = firstParameterIndex // bridging call\n return argIdx < firstParamIdx ? nil : argIdx - firstParamIdx\n }\n\n private func findDependence(source argumentIndex: Int, in dependencies: FunctionConvention.LifetimeDependencies?)\n -> LifetimeDependenceConvention? {\n guard let paramIdx = parameterIndex(for: argumentIndex) else {\n return nil\n }\n return dependencies?[paramIdx]\n }\n}\n\npublic struct YieldConventions : Collection, CustomStringConvertible {\n public let convention: FunctionConvention\n\n public var yields: FunctionConvention.Yields {\n return convention.yields\n }\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int { yields.count }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ index: Int) -> ArgumentConvention {\n return yields[index].convention\n }\n\n public var description: String {\n var str = convention.functionType.description\n yields.forEach {\n str += "\n yield: " + $0.description\n }\n return str\n }\n}\n\npublic enum ArgumentConvention : CustomStringConvertible {\n /// This argument is passed indirectly, i.e. by directly passing the address\n /// of an object in memory. The callee is responsible for destroying the\n /// object. The callee may assume that the address does not alias any valid\n /// object.\n case indirectIn\n\n /// This argument is passed indirectly, i.e. by directly passing the address\n /// of an object in memory. The callee may not modify and does not destroy\n /// the object.\n case indirectInGuaranteed\n\n /// This argument is passed indirectly, i.e. by directly passing the address\n /// of an object in memory. The object is always valid, but the callee may\n /// assume that the address does not alias any valid object and reorder loads\n /// stores to the parameter as long as the whole object remains valid. Invalid\n /// single-threaded aliasing may produce inconsistent results, but should\n /// remain memory safe.\n case indirectInout\n\n /// This argument is passed indirectly, i.e. by directly passing the address\n /// of an object in memory. The object is allowed to be aliased by other\n /// well-typed references, but is not allowed to be escaped. This is the\n /// convention used by mutable captures in @noescape closures.\n case indirectInoutAliasable\n\n /// This argument is passed indirectly, i.e. by directly passing the address\n /// of an object in memory. The callee may modify, but does not destroy the\n /// object. This corresponds to the parameter-passing convention of the\n /// Itanium C++ ABI, which is used ubiquitously on non-Windows targets.\n case indirectInCXX\n\n /// This argument represents an indirect return value address. The callee stores\n /// the returned value to this argument. At the time when the function is called,\n /// the memory location referenced by the argument is uninitialized.\n case indirectOut\n\n /// This argument is passed directly. Its type is non-trivial, and the callee\n /// is responsible for destroying it.\n case directOwned\n\n /// This argument is passed directly. Its type may be trivial, or it may\n /// simply be that the callee is not responsible for destroying it. Its\n /// validity is guaranteed only at the instant the call begins.\n case directUnowned\n\n /// This argument is passed directly. Its type is non-trivial, and the caller\n /// guarantees its validity for the entirety of the call.\n case directGuaranteed\n\n /// This argument is a value pack of mutable references to storage,\n /// which the function is being given exclusive access to. The elements\n /// must be passed indirectly.\n case packInout\n\n /// This argument is a value pack, and ownership of the elements is being\n /// transferred into this function. Whether the elements are passed\n /// indirectly is recorded in the pack type.\n case packOwned\n\n /// This argument is a value pack, and ownership of the elements is not\n /// being transferred into this function. Whether the elements are passed\n /// indirectly is recorded in the pack type.\n case packGuaranteed\n\n /// This argument is a pack of indirect return value addresses. The\n /// addresses are stored in the pack by the caller and read out by the\n /// callee; within the callee, they are individually treated like\n /// indirectOut arguments.\n case packOut\n\n public init(result: ResultConvention) {\n switch result {\n case .indirect:\n self = .indirectOut\n case .owned:\n self = .directOwned\n case .unowned, .unownedInnerPointer, .autoreleased:\n self = .directUnowned\n case .pack:\n self = .packOut\n }\n }\n\n public var isIndirect: Bool {\n switch self {\n case .indirectIn, .indirectInGuaranteed,\n .indirectInout, .indirectInoutAliasable, .indirectInCXX,\n .indirectOut, .packOut, .packInout, .packOwned,\n .packGuaranteed:\n return true\n case .directOwned, .directUnowned, .directGuaranteed:\n return false\n }\n }\n\n public var isIndirectIn: Bool {\n switch self {\n case .indirectIn, .indirectInGuaranteed, .indirectInCXX,\n .packOwned, .packGuaranteed:\n return true\n case .directOwned, .directUnowned, .directGuaranteed,\n .indirectInout, .indirectInoutAliasable,\n .indirectOut,\n .packOut, .packInout:\n return false\n }\n }\n\n public var isIndirectOut: Bool {\n switch self {\n case .indirectOut, .packOut:\n return true\n case .indirectInGuaranteed, .directGuaranteed, .packGuaranteed,\n .indirectIn, .directOwned, .directUnowned,\n .indirectInout, .indirectInoutAliasable, .indirectInCXX,\n .packInout, .packOwned:\n return false\n }\n }\n\n public var isGuaranteed: Bool {\n switch self {\n case .indirectInGuaranteed, .directGuaranteed, .packGuaranteed:\n return true\n case .indirectIn, .directOwned, .directUnowned,\n .indirectInout, .indirectInoutAliasable, .indirectInCXX,\n .indirectOut, .packOut, .packInout, .packOwned:\n return false\n }\n }\n\n public var isConsumed: Bool {\n switch self {\n case .indirectIn, .indirectInCXX, .directOwned, .packOwned:\n return true\n case .indirectInGuaranteed, .directGuaranteed, .packGuaranteed,\n .indirectInout, .indirectInoutAliasable, .indirectOut,\n .packOut, .packInout, .directUnowned:\n return false\n }\n }\n\n public var isExclusiveIndirect: Bool {\n switch self {\n case .indirectIn,\n .indirectOut,\n .indirectInGuaranteed,\n .indirectInout,\n .indirectInCXX,\n .packOut,\n .packInout,\n .packOwned,\n .packGuaranteed:\n return true\n\n case .indirectInoutAliasable,\n .directUnowned,\n .directGuaranteed,\n .directOwned:\n return false\n }\n }\n\n public var isInout: Bool {\n switch self {\n case .indirectInout,\n .indirectInoutAliasable,\n .packInout:\n return true\n\n case .indirectIn,\n .indirectOut,\n .indirectInGuaranteed,\n .indirectInCXX,\n .directUnowned,\n .directGuaranteed,\n .directOwned,\n .packOut,\n .packOwned,\n .packGuaranteed:\n return false\n }\n }\n\n public var description: String {\n switch self {\n case .indirectIn:\n return "indirectIn"\n case .indirectInGuaranteed:\n return "indirectInGuaranteed"\n case .indirectInout:\n return "indirectInout"\n case .indirectInoutAliasable:\n return "indirectInoutAliasable"\n case .indirectInCXX:\n return "indirectInCXX"\n case .indirectOut:\n return "indirectOut"\n case .directOwned:\n return "directOwned"\n case .directUnowned:\n return "directUnowned"\n case .directGuaranteed:\n return "directGuaranteed"\n case .packInout:\n return "packInout"\n case .packOwned:\n return "packOwned"\n case .packGuaranteed:\n return "packGuaranteed"\n case .packOut:\n return "packOut"\n }\n }\n}\n\n// Bridging utilities\n\nextension BridgedArgument {\n public var argument: Argument { obj.getAs(Argument.self) }\n public var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) }\n}\n\nextension Optional where Wrapped == Argument {\n public var bridged: OptionalBridgedArgument {\n OptionalBridgedArgument(obj: self?.bridged.obj)\n }\n}\n\nextension BridgedArgumentConvention {\n var convention: ArgumentConvention {\n switch self {\n case .Indirect_In: return .indirectIn\n case .Indirect_In_Guaranteed: return .indirectInGuaranteed\n case .Indirect_Inout: return .indirectInout\n case .Indirect_InoutAliasable: return .indirectInoutAliasable\n case .Indirect_In_CXX: return .indirectInCXX\n case .Indirect_Out: return .indirectOut\n case .Direct_Owned: return .directOwned\n case .Direct_Unowned: return .directUnowned\n case .Direct_Guaranteed: return .directGuaranteed\n case .Pack_Out: return .packOut\n case .Pack_Inout: return .packInout\n case .Pack_Owned: return .packOwned\n case .Pack_Guaranteed: return .packGuaranteed\n default:\n fatalError("unsupported argument convention")\n }\n }\n}\n\nextension ArgumentConvention {\n var bridged: BridgedArgumentConvention {\n switch self {\n case .indirectIn: return .Indirect_In\n case .indirectInGuaranteed: return .Indirect_In_Guaranteed\n case .indirectInout: return .Indirect_Inout\n case .indirectInoutAliasable: return .Indirect_InoutAliasable\n case .indirectInCXX: return .Indirect_In_CXX\n case .indirectOut: return .Indirect_Out\n case .directOwned: return .Direct_Owned\n case .directUnowned: return .Direct_Unowned\n case .directGuaranteed: return .Direct_Guaranteed\n case .packOut: return .Pack_Out\n case .packInout: return .Pack_Inout\n case .packOwned: return .Pack_Owned\n case .packGuaranteed: return .Pack_Guaranteed\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Argument.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Argument.swift
Swift
20,844
0.95
0.095023
0.162872
vue-tools
753
2024-11-16T21:01:39.795720
MIT
false
3e3cec8c76fb2d6ffab49627dcb0cbab
//===--- ASTExtensions.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\nextension TypeProperties {\n // Lowers the AST type to a SIL type - in a specific function.\n // In contrast to `silType` this always succeeds. Still, it's not allowed to do this for certain AST types\n // which are not present in SIL, like an `InOut` or LValue types.\n //\n // If `maximallyAbstracted` is true, the lowering is done with a completely opaque abstraction pattern\n // (see AbstractionPattern for details).\n public func loweredType(in function: Function, maximallyAbstracted: Bool = false) -> Type {\n function.bridged.getLoweredType(rawType.bridged, maximallyAbstracted).type.objectType\n }\n}\n\nextension CanonicalType {\n // This can yield nil if the AST type is not a lowered type.\n // For example, if the AST type is a `AnyFunctionType` for which the lowered type would be a `SILFunctionType`.\n public var silType: Type? {\n BridgedType.createSILType(bridged).typeOrNil\n }\n}\n\nextension Decl {\n public var location: Location { Location(bridged: BridgedLocation.fromNominalTypeDecl(bridged)) }\n}\n\nextension NominalTypeDecl {\n public func isResilient(in function: Function) -> Bool {\n function.bridged.isResilientNominalDecl(bridged)\n }\n}\n\nextension ClassDecl {\n public var superClassType: Type? {\n self.superClass?.canonical.silType!\n }\n}\n\nextension SubstitutionMap {\n /// Returns the substitutions to specialize a method.\n ///\n /// If this is a default witness methods (`selfType` != nil) it has generic self type. In this case\n /// the generic self parameter is at depth 0 and the actual generic parameters of the substitution map\n /// are at depth + 1, e.g:\n /// ```\n /// @convention(witness_method: P) <τ_0_0><τ_1_0 where τ_0_0 : GenClass<τ_1_0>.T>\n /// ^ ^\n /// self params of substitution map at depth + 1\n /// ```\n public func getMethodSubstitutions(for method: Function, selfType: CanonicalType? = nil) -> SubstitutionMap {\n return SubstitutionMap(bridged: method.bridged.getMethodSubstitutions(bridged,\n selfType?.bridged ?? BridgedCanType()))\n }\n}\n\nextension Conformance {\n /// Returns true if the conformance is not isolated or if its isolation matches\n /// the isolation in `function`.\n public func matchesActorIsolation(in function: Function) -> Bool {\n return function.bridged.conformanceMatchesActorIsolation(bridged)\n }\n}\n\nextension DiagnosticEngine {\n public func diagnose(_ id: DiagID, _ args: DiagnosticArgument..., at location: Location) {\n diagnose(id, args, at: location.sourceLoc)\n }\n\n public func diagnose(_ id: DiagID, _ args: [DiagnosticArgument], at location: Location) {\n diagnose(id, args, at: location.sourceLoc)\n }\n}\n\nextension Diagnostic {\n public init(_ id: DiagID, _ arguments: DiagnosticArgument..., at location: Location) {\n self.init(id, arguments, at: location.sourceLoc)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ASTExtensions.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ASTExtensions.swift
Swift
3,502
0.95
0.197802
0.3875
python-kit
440
2024-02-07T20:55:53.245655
GPL-3.0
false
492fc101a6d867a79ab80453fd559c57
//===--- BasicBlock.swift - Defines the BasicBlock class ------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport SILBridging\n\n@_semantics("arc.immortal")\nfinal public class BasicBlock : CustomStringConvertible, HasShortDescription, Hashable {\n public var next: BasicBlock? { bridged.getNext().block }\n public var previous: BasicBlock? { bridged.getPrevious().block }\n\n public var parentFunction: Function { bridged.getFunction().function }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n public var shortDescription: String { name }\n\n public var arguments: ArgumentArray { ArgumentArray(block: self) }\n\n public var instructions: InstructionList {\n InstructionList(first: bridged.getFirstInst().instruction)\n }\n\n public var terminator: TermInst {\n bridged.getLastInst().instruction as! TermInst\n }\n\n public var successors: SuccessorArray { terminator.successors }\n\n public var predecessors: PredecessorList {\n PredecessorList(startAt: bridged.getFirstPred())\n }\n\n public var singlePredecessor: BasicBlock? {\n var preds = predecessors\n if let p = preds.next() {\n if preds.next() == nil {\n return p\n }\n }\n return nil\n }\n \n public var hasSinglePredecessor: Bool { singlePredecessor != nil }\n\n public var singleSuccessor: BasicBlock? {\n successors.count == 1 ? successors[0] : nil\n }\n\n /// All function exiting blocks except for ones with an `unreachable` terminator,\n /// not immediately preceded by an apply of a no-return function.\n public var isReachableExitBlock: Bool {\n switch terminator {\n case let termInst where termInst.isFunctionExiting:\n return true\n case is UnreachableInst:\n if let instBeforeUnreachable = terminator.previous,\n let ai = instBeforeUnreachable as? ApplyInst,\n ai.isCalleeNoReturn && !ai.isCalleeTrapNoReturn\n {\n return true\n }\n\n return false\n default:\n return false\n }\n }\n\n /// The index of the basic block in its function.\n /// This has O(n) complexity. Only use it for debugging\n public var index: Int {\n for (idx, block) in parentFunction.blocks.enumerated() {\n if block == self { return idx }\n }\n fatalError()\n }\n \n public var name: String { "bb\(index)" }\n\n public static func == (lhs: BasicBlock, rhs: BasicBlock) -> Bool { lhs === rhs }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n\n public var bridged: BridgedBasicBlock { BridgedBasicBlock(SwiftObject(self)) }\n}\n\n/// The list of instructions in a BasicBlock.\n///\n/// It's allowed to delete the current, next or any other instructions while\n/// iterating over the instruction list.\npublic struct InstructionList : CollectionLikeSequence, IteratorProtocol {\n private var currentInstruction: Instruction?\n\n public init(first: Instruction?) { currentInstruction = first }\n\n public mutating func next() -> Instruction? {\n if var inst = currentInstruction {\n while inst.isDeleted {\n guard let nextInst = inst.next else {\n return nil\n }\n inst = nextInst\n }\n currentInstruction = inst.next\n return inst\n }\n return nil\n }\n\n public var first: Instruction? { currentInstruction }\n\n public var last: Instruction? { reversed().first }\n\n public func reversed() -> ReverseInstructionList {\n if let inst = currentInstruction {\n let lastInst = inst.bridged.getLastInstOfParent().instruction\n return ReverseInstructionList(first: lastInst)\n }\n return ReverseInstructionList(first: nil)\n }\n}\n\n/// The list of instructions in a BasicBlock in reverse order.\n///\n/// It's allowed to delete the current, next or any other instructions while\n/// iterating over the instruction list.\npublic struct ReverseInstructionList : CollectionLikeSequence, IteratorProtocol {\n private var currentInstruction: Instruction?\n\n public init(first: Instruction?) { currentInstruction = first }\n\n public mutating func next() -> Instruction? {\n if var inst = currentInstruction {\n while inst.isDeleted {\n guard let nextInst = inst.previous else {\n return nil\n }\n inst = nextInst\n }\n currentInstruction = inst.previous\n return inst\n }\n return nil\n }\n\n public var first: Instruction? { currentInstruction }\n}\n\npublic struct ArgumentArray : RandomAccessCollection {\n fileprivate let block: BasicBlock\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { block.bridged.getNumArguments() }\n\n public subscript(_ index: Int) -> Argument {\n block.bridged.getArgument(index).argument\n }\n}\n\npublic struct SuccessorArray : RandomAccessCollection, FormattedLikeArray {\n private let base: OptionalBridgedSuccessor\n public let count: Int\n\n init(base: OptionalBridgedSuccessor, count: Int) {\n self.base = base\n self.count = count\n }\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { return count }\n\n public subscript(_ index: Int) -> BasicBlock {\n assert(index >= startIndex && index < endIndex)\n return base.advancedBy(index).getTargetBlock().block\n }\n}\n\npublic struct PredecessorList : CollectionLikeSequence, IteratorProtocol {\n private var currentSucc: OptionalBridgedSuccessor\n\n public init(startAt: OptionalBridgedSuccessor) { currentSucc = startAt }\n\n public mutating func next() -> BasicBlock? {\n if let succ = currentSucc.successor {\n currentSucc = succ.getNext()\n return succ.getContainingInst().instruction.parentBlock\n }\n return nil\n }\n}\n\n\n// Bridging utilities\n\nextension BridgedBasicBlock {\n public var block: BasicBlock { obj.getAs(BasicBlock.self) }\n public var optional: OptionalBridgedBasicBlock {\n OptionalBridgedBasicBlock(obj: self.obj)\n }\n}\n\nextension OptionalBridgedBasicBlock {\n public var block: BasicBlock? { obj.getAs(BasicBlock.self) }\n public static var none: OptionalBridgedBasicBlock {\n OptionalBridgedBasicBlock(obj: nil)\n }\n}\n\nextension Optional where Wrapped == BasicBlock {\n public var bridged: OptionalBridgedBasicBlock {\n OptionalBridgedBasicBlock(obj: self?.bridged.obj)\n }\n}\n\nextension OptionalBridgedSuccessor {\n var successor: BridgedSuccessor? {\n if let succ = succ {\n return BridgedSuccessor(succ: succ)\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_BasicBlock.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_BasicBlock.swift
Swift
6,769
0.95
0.106383
0.126316
python-kit
571
2023-09-26T22:00:24.870437
BSD-3-Clause
false
cdbfc7c34173e9138b17911c8a781541
//===--- Builder.swift - Building and modifying SIL ----------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\n/// A utility to create new instructions at a given insertion point.\npublic struct Builder {\n\n public enum InsertionPoint {\n case before(Instruction)\n case atEndOf(BasicBlock)\n case atStartOf(Function)\n case staticInitializer(GlobalVariable)\n }\n\n public let insertionPoint: InsertionPoint\n let location: Location\n private let notificationHandler: BridgedChangeNotificationHandler\n private let notifyNewInstruction: (Instruction) -> ()\n\n /// Return 'nil' when inserting at the start of a function or in a global initializer.\n public var insertionBlock: BasicBlock? {\n switch insertionPoint {\n case let .before(inst):\n return inst.parentBlock\n case let .atEndOf(block):\n return block\n case .atStartOf, .staticInitializer:\n return nil\n }\n }\n\n public var bridged: BridgedBuilder {\n switch insertionPoint {\n case .before(let inst):\n return BridgedBuilder(insertAt: .beforeInst, insertionObj: inst.bridged.obj,\n loc: location.bridged)\n case .atEndOf(let block):\n return BridgedBuilder(insertAt: .endOfBlock, insertionObj: block.bridged.obj,\n loc: location.bridged)\n case .atStartOf(let function):\n return BridgedBuilder(insertAt: .startOfFunction, insertionObj: function.bridged.obj,\n loc: location.bridged)\n case .staticInitializer(let global):\n return BridgedBuilder(insertAt: .intoGlobal, insertionObj: global.bridged.obj,\n loc: location.bridged)\n }\n }\n\n private func notifyNew<I: Instruction>(_ instruction: I) -> I {\n notificationHandler.notifyChanges(.instructionsChanged)\n if instruction is FullApplySite {\n notificationHandler.notifyChanges(.callsChanged)\n }\n if instruction is TermInst {\n notificationHandler.notifyChanges(.branchesChanged)\n }\n notifyNewInstruction(instruction)\n return instruction\n }\n\n public init(insertAt: InsertionPoint, location: Location,\n _ notifyNewInstruction: @escaping (Instruction) -> (),\n _ notificationHandler: BridgedChangeNotificationHandler) {\n self.insertionPoint = insertAt\n self.location = location;\n self.notifyNewInstruction = notifyNewInstruction\n self.notificationHandler = notificationHandler\n }\n\n public func createBuiltin(name: StringRef,\n type: Type,\n substitutions: SubstitutionMap = SubstitutionMap(),\n arguments: [Value]) -> BuiltinInst {\n return arguments.withBridgedValues { valuesRef in\n let bi = bridged.createBuiltin(\n name._bridged, type.bridged, substitutions.bridged, valuesRef)\n return notifyNew(bi.getAs(BuiltinInst.self))\n }\n }\n\n public func createBuiltinBinaryFunction(name: String,\n operandType: Type, resultType: Type, arguments: [Value]) -> BuiltinInst {\n return arguments.withBridgedValues { valuesRef in\n return name._withBridgedStringRef { nameStr in\n let bi = bridged.createBuiltinBinaryFunction(\n nameStr, operandType.bridged, resultType.bridged, valuesRef)\n return notifyNew(bi.getAs(BuiltinInst.self))\n }\n }\n }\n\n @discardableResult\n public func createCondFail(condition: Value, message: String) -> CondFailInst {\n return message._withBridgedStringRef { messageStr in\n let cf = bridged.createCondFail(condition.bridged, messageStr)\n return notifyNew(cf.getAs(CondFailInst.self))\n }\n }\n\n public func createIntegerLiteral(_ value: Int, type: Type) -> IntegerLiteralInst {\n let literal = bridged.createIntegerLiteral(type.bridged, value)\n return notifyNew(literal.getAs(IntegerLiteralInst.self))\n }\n \n public func createAllocRef(_ type: Type, isObjC: Bool = false, canAllocOnStack: Bool = false, isBare: Bool = false,\n tailAllocatedTypes: TypeArray, tailAllocatedCounts: [Value]) -> AllocRefInst {\n return tailAllocatedCounts.withBridgedValues { countsRef in\n let dr = bridged.createAllocRef(type.bridged, isObjC, canAllocOnStack, isBare, tailAllocatedTypes.bridged, countsRef)\n return notifyNew(dr.getAs(AllocRefInst.self))\n }\n }\n\n public func createAllocStack(_ type: Type, hasDynamicLifetime: Bool = false,\n isLexical: Bool = false, isFromVarDecl: Bool = false,\n usesMoveableValueDebugInfo: Bool = false) -> AllocStackInst {\n let dr = bridged.createAllocStack(type.bridged, hasDynamicLifetime, isLexical,\n isFromVarDecl, usesMoveableValueDebugInfo)\n return notifyNew(dr.getAs(AllocStackInst.self))\n }\n\n @discardableResult\n public func createDeallocStack(_ operand: Value) -> DeallocStackInst {\n let dr = bridged.createDeallocStack(operand.bridged)\n return notifyNew(dr.getAs(DeallocStackInst.self))\n }\n\n @discardableResult\n public func createDeallocStackRef(_ operand: Value) -> DeallocStackRefInst {\n let dr = bridged.createDeallocStackRef(operand.bridged)\n return notifyNew(dr.getAs(DeallocStackRefInst.self))\n }\n\n public func createAddressToPointer(address: Value, pointerType: Type,\n needStackProtection: Bool) -> AddressToPointerInst {\n let dr = bridged.createAddressToPointer(address.bridged, pointerType.bridged, needStackProtection)\n return notifyNew(dr.getAs(AddressToPointerInst.self))\n }\n\n public func createPointerToAddress(pointer: Value, addressType: Type,\n isStrict: Bool, isInvariant: Bool,\n alignment: Int? = nil) -> PointerToAddressInst {\n let dr = bridged.createPointerToAddress(pointer.bridged, addressType.bridged, isStrict, isInvariant,\n UInt64(alignment ?? 0))\n return notifyNew(dr.getAs(PointerToAddressInst.self))\n }\n\n public func createIndexAddr(base: Value, index: Value, needStackProtection: Bool) -> IndexAddrInst {\n let dr = bridged.createIndexAddr(base.bridged, index.bridged, needStackProtection)\n return notifyNew(dr.getAs(IndexAddrInst.self))\n }\n\n public func createUncheckedRefCast(from value: Value, to type: Type) -> UncheckedRefCastInst {\n let cast = bridged.createUncheckedRefCast(value.bridged, type.bridged)\n return notifyNew(cast.getAs(UncheckedRefCastInst.self))\n }\n\n public func createUncheckedAddrCast(from value: Value, to type: Type) -> UncheckedAddrCastInst {\n let cast = bridged.createUncheckedAddrCast(value.bridged, type.bridged)\n return notifyNew(cast.getAs(UncheckedAddrCastInst.self))\n }\n\n public func createUpcast(from value: Value, to type: Type) -> UpcastInst {\n let cast = bridged.createUpcast(value.bridged, type.bridged)\n return notifyNew(cast.getAs(UpcastInst.self))\n }\n \n @discardableResult\n public func createCheckedCastAddrBranch(\n source: Value, sourceFormalType: CanonicalType,\n destination: Value, targetFormalType: CanonicalType,\n isolatedConformances: CastingIsolatedConformances,\n consumptionKind: CheckedCastAddrBranchInst.CastConsumptionKind,\n successBlock: BasicBlock,\n failureBlock: BasicBlock\n ) -> CheckedCastAddrBranchInst {\n \n let bridgedConsumption: BridgedInstruction.CastConsumptionKind\n switch consumptionKind {\n case .TakeAlways: bridgedConsumption = .TakeAlways\n case .TakeOnSuccess: bridgedConsumption = .TakeOnSuccess\n case .CopyOnSuccess: bridgedConsumption = .CopyOnSuccess \n }\n\n let cast = bridged.createCheckedCastAddrBranch(source.bridged, sourceFormalType.bridged,\n destination.bridged, targetFormalType.bridged,\n isolatedConformances.bridged,\n bridgedConsumption,\n successBlock.bridged, failureBlock.bridged)\n return notifyNew(cast.getAs(CheckedCastAddrBranchInst.self))\n }\n\n @discardableResult\n public func createUnconditionalCheckedCastAddr(\n isolatedConformances: CastingIsolatedConformances,\n source: Value, sourceFormalType: CanonicalType,\n destination: Value, targetFormalType: CanonicalType\n ) -> UnconditionalCheckedCastAddrInst {\n let cast = bridged.createUnconditionalCheckedCastAddr(\n isolatedConformances.bridged, source.bridged,\n sourceFormalType.bridged,\n destination.bridged, targetFormalType.bridged\n )\n return notifyNew(cast.getAs(UnconditionalCheckedCastAddrInst.self))\n }\n\n public func createLoad(fromAddress: Value, ownership: LoadInst.LoadOwnership) -> LoadInst {\n let load = bridged.createLoad(fromAddress.bridged, ownership.rawValue)\n return notifyNew(load.getAs(LoadInst.self))\n }\n\n public func createLoadBorrow(fromAddress: Value) -> LoadBorrowInst {\n let load = bridged.createLoadBorrow(fromAddress.bridged)\n return notifyNew(load.getAs(LoadBorrowInst.self))\n }\n\n public func createBeginDeallocRef(reference: Value, allocation: AllocRefInstBase) -> BeginDeallocRefInst {\n let beginDealloc = bridged.createBeginDeallocRef(reference.bridged, allocation.bridged)\n return notifyNew(beginDealloc.getAs(BeginDeallocRefInst.self))\n }\n\n public func createEndInitLetRef(operand: Value) -> EndInitLetRefInst {\n let endInit = bridged.createEndInitLetRef(operand.bridged)\n return notifyNew(endInit.getAs(EndInitLetRefInst.self))\n }\n\n @discardableResult\n public func createRetainValue(operand: Value) -> RetainValueInst {\n let retain = bridged.createRetainValue(operand.bridged)\n return notifyNew(retain.getAs(RetainValueInst.self))\n }\n\n @discardableResult\n public func createReleaseValue(operand: Value) -> ReleaseValueInst {\n let release = bridged.createReleaseValue(operand.bridged)\n return notifyNew(release.getAs(ReleaseValueInst.self))\n }\n\n @discardableResult\n public func createStrongRetain(operand: Value) -> StrongRetainInst {\n let retain = bridged.createStrongRetain(operand.bridged)\n return notifyNew(retain.getAs(StrongRetainInst.self))\n }\n\n @discardableResult\n public func createStrongRelease(operand: Value) -> StrongReleaseInst {\n let release = bridged.createStrongRelease(operand.bridged)\n return notifyNew(release.getAs(StrongReleaseInst.self))\n }\n\n @discardableResult\n public func createUnownedRetain(operand: Value) -> UnownedRetainInst {\n let retain = bridged.createUnownedRetain(operand.bridged)\n return notifyNew(retain.getAs(UnownedRetainInst.self))\n }\n\n @discardableResult\n public func createUnownedRelease(operand: Value) -> UnownedReleaseInst {\n let release = bridged.createUnownedRelease(operand.bridged)\n return notifyNew(release.getAs(UnownedReleaseInst.self))\n }\n\n public func createFunctionRef(_ function: Function) -> FunctionRefInst {\n let functionRef = bridged.createFunctionRef(function.bridged)\n return notifyNew(functionRef.getAs(FunctionRefInst.self))\n }\n\n public func createCopyValue(operand: Value) -> CopyValueInst {\n return notifyNew(bridged.createCopyValue(operand.bridged).getAs(CopyValueInst.self))\n }\n\n public func createBeginBorrow(\n of value: Value,\n isLexical: Bool = false,\n hasPointerEscape: Bool = false,\n isFromVarDecl: Bool = false\n ) -> BeginBorrowInst {\n return notifyNew(bridged.createBeginBorrow(value.bridged,\n isLexical, hasPointerEscape, isFromVarDecl).getAs(BeginBorrowInst.self))\n }\n\n public func createBorrowedFrom(borrowedValue: Value, enclosingValues: [Value]) -> BorrowedFromInst {\n let bfi = enclosingValues.withBridgedValues { valuesRef in\n return bridged.createBorrowedFrom(borrowedValue.bridged, valuesRef)\n }\n return notifyNew(bfi.getAs(BorrowedFromInst.self))\n }\n\n @discardableResult\n public func createEndBorrow(of beginBorrow: Value) -> EndBorrowInst {\n return notifyNew(bridged.createEndBorrow(beginBorrow.bridged).getAs(EndBorrowInst.self))\n }\n\n @discardableResult\n public func createCopyAddr(from fromAddr: Value, to toAddr: Value,\n takeSource: Bool = false, initializeDest: Bool = false) -> CopyAddrInst {\n return notifyNew(bridged.createCopyAddr(fromAddr.bridged, toAddr.bridged,\n takeSource, initializeDest).getAs(CopyAddrInst.self))\n }\n\n @discardableResult\n public func createDestroyValue(operand: Value) -> DestroyValueInst {\n return notifyNew(bridged.createDestroyValue(operand.bridged).getAs(DestroyValueInst.self))\n }\n\n @discardableResult\n public func createDestroyAddr(address: Value) -> DestroyAddrInst {\n return notifyNew(bridged.createDestroyAddr(address.bridged).getAs(DestroyAddrInst.self))\n }\n\n @discardableResult\n public func createEndLifetime(of value: Value) -> EndLifetimeInst {\n return notifyNew(bridged.createEndLifetime(value.bridged).getAs(EndLifetimeInst.self))\n }\n\n @discardableResult\n public func createDebugValue(value: Value, debugVariable: DebugVariableInstruction.DebugVariable) -> DebugValueInst {\n return notifyNew(bridged.createDebugValue(value.bridged, debugVariable).getAs(DebugValueInst.self))\n }\n\n @discardableResult\n public func createDebugStep() -> DebugStepInst {\n return notifyNew(bridged.createDebugStep().getAs(DebugStepInst.self))\n }\n\n @discardableResult\n public func createApply(\n function: Value,\n _ substitutionMap: SubstitutionMap,\n arguments: [Value],\n isNonThrowing: Bool = false,\n isNonAsync: Bool = false,\n specializationInfo: ApplyInst.SpecializationInfo = ApplyInst.SpecializationInfo()\n ) -> ApplyInst {\n let apply = arguments.withBridgedValues { valuesRef in\n bridged.createApply(function.bridged, substitutionMap.bridged, valuesRef,\n isNonThrowing, isNonAsync, specializationInfo)\n }\n return notifyNew(apply.getAs(ApplyInst.self))\n }\n \n @discardableResult\n public func createTryApply(\n function: Value,\n _ substitutionMap: SubstitutionMap,\n arguments: [Value],\n normalBlock: BasicBlock,\n errorBlock: BasicBlock,\n isNonAsync: Bool = false,\n specializationInfo: ApplyInst.SpecializationInfo = ApplyInst.SpecializationInfo()\n ) -> TryApplyInst {\n let apply = arguments.withBridgedValues { valuesRef in\n bridged.createTryApply(function.bridged, substitutionMap.bridged, valuesRef,\n normalBlock.bridged, errorBlock.bridged,\n isNonAsync, specializationInfo)\n }\n return notifyNew(apply.getAs(TryApplyInst.self))\n }\n \n public func createWitnessMethod(lookupType: CanonicalType,\n conformance: Conformance,\n member: DeclRef,\n methodType: Type) -> WitnessMethodInst {\n return notifyNew(bridged.createWitnessMethod(lookupType.bridged, conformance.bridged,\n member.bridged, methodType.bridged).getAs(WitnessMethodInst.self)) \n }\n \n @discardableResult\n public func createReturn(of value: Value) -> ReturnInst {\n return notifyNew(bridged.createReturn(value.bridged).getAs(ReturnInst.self))\n }\n\n @discardableResult\n public func createThrow(of value: Value) -> ThrowInst {\n return notifyNew(bridged.createThrow(value.bridged).getAs(ThrowInst.self))\n }\n\n public func createUncheckedEnumData(enum enumVal: Value,\n caseIndex: Int,\n resultType: Type) -> UncheckedEnumDataInst {\n let ued = bridged.createUncheckedEnumData(enumVal.bridged, caseIndex, resultType.bridged)\n return notifyNew(ued.getAs(UncheckedEnumDataInst.self))\n }\n\n public func createUncheckedTakeEnumDataAddr(enumAddress: Value,\n caseIndex: Int) -> UncheckedTakeEnumDataAddrInst {\n let uteda = bridged.createUncheckedTakeEnumDataAddr(enumAddress.bridged, caseIndex)\n return notifyNew(uteda.getAs(UncheckedTakeEnumDataAddrInst.self))\n }\n\n public func createInitEnumDataAddr(enumAddress: Value, caseIndex: Int, type: Type) -> InitEnumDataAddrInst {\n let uteda = bridged.createInitEnumDataAddr(enumAddress.bridged, caseIndex, type.bridged)\n return notifyNew(uteda.getAs(InitEnumDataAddrInst.self))\n }\n\n public func createEnum(caseIndex: Int, payload: Value?, enumType: Type) -> EnumInst {\n let enumInst = bridged.createEnum(caseIndex, payload.bridged, enumType.bridged)\n return notifyNew(enumInst.getAs(EnumInst.self))\n }\n\n public func createThinToThickFunction(thinFunction: Value, resultType: Type) -> ThinToThickFunctionInst {\n let tttf = bridged.createThinToThickFunction(thinFunction.bridged, resultType.bridged)\n return notifyNew(tttf.getAs(ThinToThickFunctionInst.self))\n }\n\n public func createPartialApply(\n function: Value,\n substitutionMap: SubstitutionMap, \n capturedArguments: [Value], \n calleeConvention: ArgumentConvention, \n hasUnknownResultIsolation: Bool, \n isOnStack: Bool\n ) -> PartialApplyInst {\n return capturedArguments.withBridgedValues { capturedArgsRef in\n let pai = bridged.createPartialApply(function.bridged, capturedArgsRef, calleeConvention.bridged, substitutionMap.bridged, hasUnknownResultIsolation, isOnStack)\n return notifyNew(pai.getAs(PartialApplyInst.self))\n }\n }\n\n @discardableResult\n public func createSwitchEnum(enum enumVal: Value,\n cases: [(Int, BasicBlock)],\n defaultBlock: BasicBlock? = nil) -> SwitchEnumInst {\n let se = cases.withUnsafeBufferPointer { caseBuffer in\n bridged.createSwitchEnumInst(enumVal.bridged, defaultBlock.bridged,\n caseBuffer.baseAddress, caseBuffer.count)\n }\n return notifyNew(se.getAs(SwitchEnumInst.self))\n }\n \n @discardableResult\n public func createSwitchEnumAddr(enumAddress: Value,\n cases: [(Int, BasicBlock)],\n defaultBlock: BasicBlock? = nil) -> SwitchEnumAddrInst {\n let se = cases.withUnsafeBufferPointer { caseBuffer in\n bridged.createSwitchEnumAddrInst(enumAddress.bridged, defaultBlock.bridged,\n caseBuffer.baseAddress, caseBuffer.count)\n }\n return notifyNew(se.getAs(SwitchEnumAddrInst.self))\n }\n\n @discardableResult\n public func createBranch(to destBlock: BasicBlock, arguments: [Value] = []) -> BranchInst {\n return arguments.withBridgedValues { valuesRef in\n let bi = bridged.createBranch(destBlock.bridged, valuesRef)\n return notifyNew(bi.getAs(BranchInst.self))\n }\n }\n\n @discardableResult\n public func createUnreachable() -> UnreachableInst {\n let ui = bridged.createUnreachable()\n return notifyNew(ui.getAs(UnreachableInst.self))\n }\n\n @discardableResult\n public func createObject(type: Type, arguments: [Value], numBaseElements: Int) -> ObjectInst {\n let objectInst = arguments.withBridgedValues { valuesRef in\n return bridged.createObject(type.bridged, valuesRef, numBaseElements)\n }\n return notifyNew(objectInst.getAs(ObjectInst.self))\n }\n\n @discardableResult\n public func createVector(type: Type, arguments: [Value]) -> VectorInst {\n let vectorInst = arguments.withBridgedValues { valuesRef in\n return bridged.createVector(valuesRef)\n }\n return notifyNew(vectorInst.getAs(VectorInst.self))\n }\n\n public func createGlobalAddr(global: GlobalVariable, dependencyToken: Value?) -> GlobalAddrInst {\n return notifyNew(bridged.createGlobalAddr(global.bridged, dependencyToken.bridged).getAs(GlobalAddrInst.self))\n }\n\n public func createGlobalValue(global: GlobalVariable, isBare: Bool) -> GlobalValueInst {\n return notifyNew(bridged.createGlobalValue(global.bridged, isBare).getAs(GlobalValueInst.self))\n }\n\n public func createStruct(type: Type, elements: [Value]) -> StructInst {\n let structInst = elements.withBridgedValues { valuesRef in\n return bridged.createStruct(type.bridged, valuesRef)\n }\n return notifyNew(structInst.getAs(StructInst.self))\n }\n\n public func createStructExtract(struct: Value, fieldIndex: Int) -> StructExtractInst {\n return notifyNew(bridged.createStructExtract(`struct`.bridged, fieldIndex).getAs(StructExtractInst.self))\n }\n\n public func createStructElementAddr(structAddress: Value, fieldIndex: Int) -> StructElementAddrInst {\n return notifyNew(bridged.createStructElementAddr(structAddress.bridged, fieldIndex).getAs(StructElementAddrInst.self))\n }\n\n public func createDestructureStruct(struct: Value) -> DestructureStructInst {\n return notifyNew(bridged.createDestructureStruct(`struct`.bridged).getAs(DestructureStructInst.self))\n }\n\n public func createTuple(type: Type, elements: [Value]) -> TupleInst {\n let tuple = elements.withBridgedValues { valuesRef in\n return bridged.createTuple(type.bridged, valuesRef)\n }\n return notifyNew(tuple.getAs(TupleInst.self))\n }\n\n public func createTupleExtract(tuple: Value, elementIndex: Int) -> TupleExtractInst {\n return notifyNew(bridged.createTupleExtract(tuple.bridged, elementIndex).getAs(TupleExtractInst.self))\n }\n\n public func createTupleElementAddr(tupleAddress: Value, elementIndex: Int) -> TupleElementAddrInst {\n return notifyNew(bridged.createTupleElementAddr(tupleAddress.bridged, elementIndex).getAs(TupleElementAddrInst.self))\n }\n\n public func createDestructureTuple(tuple: Value) -> DestructureTupleInst {\n return notifyNew(bridged.createDestructureTuple(tuple.bridged).getAs(DestructureTupleInst.self))\n }\n\n @discardableResult\n public func createStore(source: Value, destination: Value, ownership: StoreInst.StoreOwnership) -> StoreInst {\n let store = bridged.createStore(source.bridged, destination.bridged, ownership.rawValue)\n return notifyNew(store.getAs(StoreInst.self))\n }\n\n public func createInitExistentialRef(instance: Value,\n existentialType: Type,\n formalConcreteType: CanonicalType,\n conformances: ConformanceArray) -> InitExistentialRefInst {\n let initExistential = bridged.createInitExistentialRef(instance.bridged,\n existentialType.bridged,\n formalConcreteType.bridged,\n conformances.bridged)\n return notifyNew(initExistential.getAs(InitExistentialRefInst.self))\n }\n\n public func createInitExistentialMetatype(\n metatype: Value,\n existentialType: Type,\n conformances: [Conformance]\n ) -> InitExistentialMetatypeInst {\n let initExistential = conformances.map{ $0.bridged }.withBridgedArrayRef {\n return bridged.createInitExistentialMetatype(metatype.bridged,\n existentialType.bridged,\n BridgedConformanceArray(pcArray: $0))\n }\n return notifyNew(initExistential.getAs(InitExistentialMetatypeInst.self))\n }\n\n public func createMetatype(\n ofInstanceType instanceType: CanonicalType,\n representation: AST.`Type`.MetatypeRepresentation\n ) -> MetatypeInst {\n let bridgedRep: BridgedASTType.MetatypeRepresentation\n switch representation {\n case .thin: bridgedRep = .Thin\n case .thick: bridgedRep = .Thick\n case .objC: bridgedRep = .ObjC\n }\n let metatype = bridged.createMetatype(instanceType.bridged, bridgedRep)\n return notifyNew(metatype.getAs(MetatypeInst.self))\n }\n\n public func createEndCOWMutation(instance: Value, keepUnique: Bool) -> EndCOWMutationInst {\n let endMutation = bridged.createEndCOWMutation(instance.bridged, keepUnique)\n return notifyNew(endMutation.getAs(EndCOWMutationInst.self))\n }\n\n public func createMarkDependence(value: Value, base: Value, kind: MarkDependenceKind) -> MarkDependenceInst {\n let markDependence = bridged.createMarkDependence(value.bridged, base.bridged,\n BridgedInstruction.MarkDependenceKind(rawValue: kind.rawValue)!)\n return notifyNew(markDependence.getAs(MarkDependenceInst.self))\n }\n\n public func createMarkDependenceAddr(value: Value, base: Value, kind: MarkDependenceKind) -> MarkDependenceAddrInst {\n let markDependence = bridged.createMarkDependenceAddr(\n value.bridged, base.bridged, BridgedInstruction.MarkDependenceKind(rawValue: kind.rawValue)!)\n return notifyNew(markDependence.getAs(MarkDependenceAddrInst.self))\n }\n \n @discardableResult\n public func createEndAccess(beginAccess: BeginAccessInst) -> EndAccessInst {\n let endAccess = bridged.createEndAccess(beginAccess.bridged)\n return notifyNew(endAccess.getAs(EndAccessInst.self))\n }\n\n @discardableResult\n public func createEndApply(beginApply: BeginApplyInst) -> EndApplyInst {\n let endApply = bridged.createEndApply(beginApply.token.bridged)\n return notifyNew(endApply.getAs(EndApplyInst.self))\n }\n\n @discardableResult\n public func createAbortApply(beginApply: BeginApplyInst) -> AbortApplyInst {\n let endApply = bridged.createAbortApply(beginApply.token.bridged)\n return notifyNew(endApply.getAs(AbortApplyInst.self))\n }\n\n public func createConvertFunction(originalFunction: Value, resultType: Type, withoutActuallyEscaping: Bool) -> ConvertFunctionInst {\n let convertFunction = bridged.createConvertFunction(originalFunction.bridged, resultType.bridged, withoutActuallyEscaping)\n return notifyNew(convertFunction.getAs(ConvertFunctionInst.self))\n }\n\n public func createConvertEscapeToNoEscape(originalFunction: Value, resultType: Type, isLifetimeGuaranteed: Bool) -> ConvertEscapeToNoEscapeInst {\n let convertFunction = bridged.createConvertEscapeToNoEscape(originalFunction.bridged, resultType.bridged, isLifetimeGuaranteed)\n return notifyNew(convertFunction.getAs(ConvertEscapeToNoEscapeInst.self))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Builder.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Builder.swift
Swift
26,594
0.95
0.030794
0.024482
node-utils
1,000
2024-01-19T02:58:18.697139
MIT
false
80887937d84e190dbc64e66123bae262
//===--- ConstExpressionEvaluator.swift - ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\npublic struct ConstExpressionEvaluator {\n var bridged: BridgedConstExprFunctionState\n\n public init(bridged: BridgedConstExprFunctionState) { self.bridged = bridged }\n public init() {\n self.bridged = BridgedConstExprFunctionState.create()\n }\n \n mutating public func isConstantValue(_ value: Value) -> Bool {\n return bridged.isConstantValue(value.bridged)\n }\n \n /// TODO: once we have move-only types, make this a real deinit.\n mutating public func deinitialize() {\n bridged.deinitialize()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ConstExpressionEvaluator.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ConstExpressionEvaluator.swift
Swift
1,064
0.95
0.0625
0.444444
react-lib
807
2025-03-31T22:38:07.918580
Apache-2.0
false
e5e6143ec42cc347a52cee4fa0166e31
//===--- DeclRef.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SILBridging\nimport AST\n\n/// A key for referencing an AST declaration in SIL.\n///\n/// In addition to the AST reference, there are discriminators for referencing different\n/// implementation-level entities associated with a single language-level declaration,\n/// such as the allocating and initializing entry points of a constructor, etc.\npublic struct DeclRef: CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedDeclRef\n\n public var location: Location { Location(bridged: bridged.getLocation()) }\n\n public var description: String { String(taking: bridged.getDebugDescription()) }\n\n public var decl: Decl { bridged.getDecl().decl }\n\n public static func ==(lhs: DeclRef, rhs: DeclRef) -> Bool {\n lhs.bridged.isEqualTo(rhs.bridged)\n }\n}\n\nextension DeclRef: DiagnosticArgument {\n public func _withBridgedDiagnosticArgument(_ fn: (BridgedDiagnosticArgument) -> Void) {\n fn(bridged.asDiagnosticArgument())\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_DeclRef.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_DeclRef.swift
Swift
1,470
0.95
0.102564
0.5
awesome-app
193
2024-09-20T21:43:03.471894
GPL-3.0
false
1fe04250e16308bea04e213713553020
//===--- Effects.swift - Defines function effects -------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// All effects for a function.\n///\n/// It consists of escape and side effects.\npublic struct FunctionEffects : CustomStringConvertible, NoReflectionChildren {\n\n public var escapeEffects = EscapeEffects(arguments: [])\n\n // If nil, the side effects are not computed yet and clients need to assume\n // the worst effects (using `Function.getDefinedSideEffects()`).\n public var sideEffects: SideEffects?\n\n public init() {}\n\n public init(copiedFrom src: FunctionEffects, resultArgDelta: Int) {\n self.escapeEffects = EscapeEffects(arguments: src.escapeEffects.arguments.compactMap {\n EscapeEffects.ArgumentEffect(copiedFrom: $0, resultArgDelta: resultArgDelta)\n })\n // Cannot copy side effects\n self.sideEffects = nil\n }\n\n public var description: String {\n var numArgEffects = escapeEffects.arguments.reduce(0, { max($0, $1.argumentIndex) }) + 1\n if let sideEffects = sideEffects {\n numArgEffects = max(numArgEffects, sideEffects.arguments.count)\n }\n var result = ""\n for argIdx in 0..<numArgEffects {\n var argStrings: [String] = []\n for escEffect in escapeEffects.arguments where escEffect.argumentIndex == argIdx {\n argStrings.append(escEffect.bodyDescription)\n }\n if let sideEffects = sideEffects, argIdx < sideEffects.arguments.count {\n let argDescription = sideEffects.arguments[argIdx].bodyDescription\n if !argDescription.isEmpty {\n argStrings.append(argDescription)\n }\n }\n if !argStrings.isEmpty {\n result += "[%\(argIdx): " + argStrings.joined(separator: ", ") + "]\n"\n }\n }\n if let sideEffects = sideEffects {\n result += "[global: \(sideEffects.global)]\n"\n }\n return result\n }\n}\n\nextension Function {\n \n /// Returns the global side effects of the function.\n public func getSideEffects() -> SideEffects.GlobalEffects {\n if let sideEffects = effects.sideEffects {\n /// There are computed side effects.\n return sideEffects.accumulatedEffects\n } else {\n \n var effects = definedGlobalEffects\n\n // Even a `[readnone]` function can read from indirect arguments.\n if (0..<numArguments).contains(where: {argumentConventions[$0].isIndirectIn}) {\n effects.memory.read = true\n }\n // Even `[readnone]` and `[readonly]` functions write to indirect results.\n if numIndirectResultArguments > 0 {\n effects.memory.write = true\n }\n return effects\n }\n }\n\n /// Returns the side effects for a function argument.\n ///\n /// The `argument` can be a function argument in this function or an apply argument in a caller.\n public func getSideEffects(forArgument argument: ProjectedValue,\n atIndex argumentIndex: Int,\n withConvention convention: ArgumentConvention) -> SideEffects.GlobalEffects {\n var result = SideEffects.GlobalEffects()\n\n // Effects are only defined for operations which don't involve a load.\n // In case the argument's path involves a load we need to return the global effects.\n if argument.value.type.isAddress {\n // Indirect arguments:\n if argument.path.mayHaveClassProjection {\n // For example:\n // bb0(%0: $*C):\n // %1 = load %0 // the involved load\n // %2 = ref_element_addr %1 // class projection\n return getSideEffects()\n }\n } else {\n // Direct arguments:\n if argument.path.mayHaveTwoClassProjections {\n // For example:\n // bb0(%0: $C):\n // %1 = ref_element_addr %1 // first class projection\n // %2 = load %1 // the involved load\n // %3 = ref_element_addr %2 // second class projection\n return getSideEffects()\n\n } else if argument.path.mayHaveClassProjection {\n // For example:\n // bb0(%0: $C):\n // %1 = ref_element_addr %1 // class projection\n // %2 = load [take] %1 // the involved load\n // destroy_value %2\n result.ownership = getSideEffects().ownership\n }\n }\n\n if let sideEffects = effects.sideEffects {\n /// There are computed side effects.\n let argEffect = sideEffects.getArgumentEffects(for: argumentIndex)\n if let effectPath = argEffect.read, effectPath.mayOverlap(with: argument.path) {\n result.memory.read = true\n }\n if let effectPath = argEffect.write, effectPath.mayOverlap(with: argument.path) {\n result.memory.write = true\n }\n if let effectPath = argEffect.copy, effectPath.mayOverlap(with: argument.path) {\n result.ownership.copy = true\n }\n if let effectPath = argEffect.destroy, effectPath.mayOverlap(with: argument.path) {\n result.ownership.destroy = true\n }\n return result\n } else {\n /// Even for defined effects, there might be additional effects due to the argument conventions.\n var result = definedGlobalEffects\n if convention.isIndirectIn {\n // Even a `[readnone]` function can read from an indirect argument.\n result.memory.read = true\n } else if convention.isIndirectOut {\n // Even `[readnone]` and `[readonly]` functions write to indirect results.\n result.memory.write = true\n }\n return result.restrictedTo(argument: argument, withConvention: convention)\n }\n }\n\n /// Global effect of the function, defined by effect attributes.\n public var definedGlobalEffects: SideEffects.GlobalEffects {\n switch name {\n case "_swift_stdlib_malloc_size", "_swift_stdlib_has_malloc_size":\n // These C runtime functions, which are used in the array implementation, have defined effects.\n return SideEffects.GlobalEffects(memory: SideEffects.Memory(read: true))\n default:\n break\n }\n if isProgramTerminationPoint {\n // We can ignore any memory writes in a program termination point, because it's not relevant\n // for the caller. But we need to consider memory reads, otherwise preceding memory writes\n // would be eliminated by dead-store-elimination in the caller. E.g. String initialization\n // for error strings which are printed by the program termination point.\n // Regarding ownership: a program termination point must not touch any reference counted objects.\n return SideEffects.GlobalEffects(memory: SideEffects.Memory(read: true))\n }\n var result = SideEffects.GlobalEffects.worstEffects\n switch effectAttribute {\n case .none:\n // The common case: there is no effect attribute, so we have to assume the worst effects.\n break\n case .readNone:\n result.memory.read = false\n result.memory.write = false\n result.ownership.destroy = false\n result.allocates = false\n case .readOnly:\n result.memory.write = false\n result.ownership.destroy = false\n result.allocates = false\n case .releaseNone:\n result.ownership.destroy = false\n }\n return result\n }\n}\n\n/// Escape effects.\n///\n/// The escape effects describe which arguments are not escaping or escaping to\n/// the return value or other arguments.\npublic struct EscapeEffects : CustomStringConvertible, NoReflectionChildren {\n public var arguments: [ArgumentEffect]\n\n public func canEscape(argumentIndex: Int, path: SmallProjectionPath) -> Bool {\n return !arguments.contains(where: {\n if case .notEscaping = $0.kind, $0.argumentIndex == argumentIndex {\n if path.matches(pattern: $0.pathPattern) {\n return true\n }\n }\n return false\n })\n }\n\n public var description: String {\n let maxArgIdx = arguments.reduce(0) { max($0, $1.argumentIndex) }\n var result = ""\n for argIdx in 0...maxArgIdx {\n var argStrings: [String] = []\n for escEffect in arguments where escEffect.argumentIndex == argIdx {\n argStrings.append(escEffect.bodyDescription)\n }\n if !argStrings.isEmpty {\n result += "[%\(argIdx): " + argStrings.joined(separator: ", ") + "]\n"\n }\n }\n return result\n }\n\n /// An escape effect on a function argument.\n public struct ArgumentEffect : Equatable, CustomStringConvertible, NoReflectionChildren {\n\n public enum Kind : Equatable {\n /// The argument value does not escape.\n ///\n /// Syntax examples:\n /// [%0: noescape] // argument 0 does not escape\n /// [%0: noescape **] // argument 0 and all transitively contained values do not escape\n ///\n case notEscaping\n \n /// The argument value escapes to the function return value.\n ///\n /// Syntax examples:\n /// [%0: escape s1 => %r] // field 2 of argument 0 exclusively escapes via return.\n /// [%0: escape s1 -> %r] // field 2 of argument 0 - and other values - escape via return\n ///\n /// The `isExclusive` flag is true if only the argument escapes, but nothing else escapes to\n /// the return value.\n /// For example, `isExclusive` is true for the following function:\n ///\n /// @_effect(escaping c => return)\n /// func exclusiveEscape(_ c: Class) -> Class { return c }\n ///\n /// but not in this case:\n ///\n /// var global: Class\n ///\n /// @_effect(escaping c -> return)\n /// func notExclusiveEscape(_ c: Class) -> Class { return cond ? c : global }\n ///\n /// Also, if `isExclusive` is true, there must not be a store in the chain from the argument to\n /// the return, e.g.\n ///\n /// @_effect(escaping x -> return)\n /// func notExclusiveEscape(_ s: String) -> Class {\n /// c = new Class()\n /// c.s = s // Store, which prevents the effect to be `isExclusive`\n /// return s\n /// }\n case escapingToReturn(toPath: SmallProjectionPath, isExclusive: Bool)\n\n /// Like `escapingToReturn`, but the argument escapes to another argument.\n ///\n /// Example: The argument effects of\n ///\n /// func argToArgEscape(_ r: inout Class, _ c: Class) { r = c }\n ///\n /// would be\n /// [%1: escape => %0] // Argument 1 escapes to argument 0\n ///\n /// It's not allowed that the argument (or a derived value) is _stored_ to an object which is loaded from somewhere.\n /// In the following example `c` is loaded from the indirect inout argument and `s` is stored to a field of `c`:\n ///\n /// func noEscapeEffect(_ c: inout Class, s: String) {\n /// c.s = s\n /// }\n ///\n /// In this case there is no escaping effect from `s` to `c`.\n /// Note that theoretically this rule also applies to the `escapingToReturn` effect, but it's impossible\n /// to construct such a situation for an argument which is only escaping to the function return.\n ///\n /// The `escapingToArgument` doesn't have an `isExclusive` flag, because an argument-to-argument escape\n /// always involves a store, which makes an exclusive escape impossible.\n case escapingToArgument(toArgumentIndex: Int, toPath: SmallProjectionPath)\n }\n\n /// To which argument does this effect apply to?\n public let argumentIndex: Int\n \n /// To which projection(s) of the argument does this effect apply to?\n public let pathPattern: SmallProjectionPath\n \n /// The kind of effect.\n public let kind: Kind\n \n /// True, if this effect is derived in an optimization pass.\n /// False, if this effect is defined in the Swift source code.\n public let isDerived: Bool\n\n public init(_ kind: Kind, argumentIndex: Int, pathPattern: SmallProjectionPath, isDerived: Bool = true) {\n self.argumentIndex = argumentIndex\n self.pathPattern = pathPattern\n self.kind = kind\n self.isDerived = isDerived\n }\n\n /// Copy the ArgumentEffect by applying a delta on the argument index.\n ///\n /// This is used when copying argument effects for specialized functions where\n /// the indirect result is converted to a direct return value (in this case the\n /// `resultArgDelta` is -1).\n init?(copiedFrom srcEffect: ArgumentEffect, resultArgDelta: Int) {\n if srcEffect.argumentIndex + resultArgDelta < 0 {\n return nil\n }\n self.argumentIndex = srcEffect.argumentIndex + resultArgDelta\n self.pathPattern = srcEffect.pathPattern\n self.isDerived = srcEffect.isDerived\n\n switch srcEffect.kind {\n case .notEscaping:\n self.kind = .notEscaping\n\n case .escapingToReturn(let toPath, let exclusive):\n if resultArgDelta > 0 {\n if resultArgDelta != 1 {\n return nil\n }\n self.kind = .escapingToArgument(toArgumentIndex: 0, toPath: toPath)\n } else {\n self.kind = .escapingToReturn(toPath: toPath, isExclusive: exclusive)\n }\n case .escapingToArgument(let toArgIdx, let toPath):\n let resultingToArgIdx = toArgIdx + resultArgDelta\n if resultingToArgIdx < 0 {\n if resultingToArgIdx != -1 {\n return nil\n }\n self.kind = .escapingToReturn(toPath: toPath, isExclusive: false)\n } else {\n self.kind = .escapingToArgument(toArgumentIndex: resultingToArgIdx, toPath: toPath)\n }\n }\n }\n\n public func matches(_ rhsArgIdx: Int, _ rhsPath: SmallProjectionPath) -> Bool {\n return argumentIndex == rhsArgIdx && rhsPath.matches(pattern: pathPattern)\n }\n\n public var bodyDescription: String {\n let patternStr = (isDerived ? "" : "!") + (pathPattern.isEmpty ? "" : " \(pathPattern)")\n switch kind {\n case .notEscaping:\n return "noescape\(patternStr)"\n case .escapingToReturn(let toPath, let exclusive):\n let toPathStr = (toPath.isEmpty ? "" : ".\(toPath)")\n return "escape\(patternStr) \(exclusive ? "=>" : "->") %r\(toPathStr)"\n case .escapingToArgument(let toArgIdx, let toPath):\n let toPathStr = (toPath.isEmpty ? "" : ".\(toPath)")\n return "escape\(patternStr) -> %\(toArgIdx)\(toPathStr)"\n }\n }\n\n public var description: String {\n "\(argumentIndex): \(bodyDescription)"\n }\n }\n}\n\n/// Side effects.\n///\n/// Side effects describe the memory (read, write) and ownership (copy, destroy)\n/// of the function arguments and the function as a whole.\npublic struct SideEffects : CustomStringConvertible, NoReflectionChildren {\n /// Effects, which can be attributed to a specific argument.\n ///\n /// This array is indexed by the argument index. Arguments which indices, which\n /// are not included in this array, are defined to have no effects.\n public let arguments: [ArgumentEffects]\n \n /// Effects, which cannot be attributed to a specific argument.\n public let global: GlobalEffects\n \n public init(arguments: [ArgumentEffects], global: GlobalEffects) {\n self.arguments = arguments\n self.global = global\n }\n\n /// Returns the effects of an argument.\n ///\n /// In contrast to using `arguments` directly, it's valid to have an `argumentIndex`\n /// which is larger than the number of elements in `arguments`.\n public func getArgumentEffects(for argumentIndex: Int) -> ArgumentEffects {\n if argumentIndex < arguments.count {\n return arguments[argumentIndex]\n }\n return ArgumentEffects()\n }\n\n /// The "accumulated" effects of the function, which includes the `global` effects and\n /// all argument effects.\n public var accumulatedEffects: GlobalEffects {\n var result = global\n for argEffect in arguments {\n if argEffect.read != nil { result.memory.read = true }\n if argEffect.write != nil { result.memory.write = true }\n if argEffect.copy != nil { result.ownership.copy = true }\n if argEffect.destroy != nil { result.ownership.destroy = true }\n }\n return result\n }\n\n public var description: String {\n var result = ""\n for (argIdx, argument) in arguments.enumerated() {\n let argDescription = argument.bodyDescription\n if !argDescription.isEmpty {\n result += "[%\(argIdx): \(argDescription)]\n"\n }\n }\n result += "[global: \(global)]\n"\n return result\n }\n \n /// Side-effects of a specific function argument.\n ///\n /// The paths describe what (projected) values of an argument are affected.\n /// If a path is nil, than there is no such effect on the argument.\n ///\n /// A path can contain any projection or wildcards, as long as there is no load involved.\n /// In other words, an effect path can refer to the argument value directly or to anything the\n /// argument "points to", but does not cover anything which is loaded from memory.\n /// For example, if the `write` path for an inout argument is nil, there is no write to the inout address.\n /// But there might very well be a write to a class field of a reference which is loaded from the inout.\n /// ```\n /// bb0(%0 : $*X): // inout\n /// %1 = load %0 // read path = v**\n /// %2 = ref_element_addr %1, #f\n /// store %x to %2 // not covered by argument effects! -> goes to global effects\n /// ```\n ///\n /// For direct argument it's different, because a direct argument (which contains a class reference) can point\n /// to a class field.\n /// ```\n /// bb0(%0 : $X): // direct argument\n /// %1 = ref_element_addr %0, #f\n /// store %x to %1 // write path = c*.v**\n /// %2 = load %1 // read path = c*.v**\n /// %3 = ref_element_addr %2, #f\n /// store %x to %3 // not covered by argument effects! -> goes to global effects\n /// ```\n public struct ArgumentEffects : Equatable, CustomStringConvertible, NoReflectionChildren {\n\n /// If not nil, the function may read from the argument at the path.\n public var read: SmallProjectionPath?\n\n /// If not nil, the function may write to the argument at the path.\n public var write: SmallProjectionPath?\n \n /// If not nil, the function may copy/retain the argument at the path (only non-trivial values).\n public var copy: SmallProjectionPath?\n \n /// If not nil, the function may destroy/release the argument at the path (only non-trivial values).\n public var destroy: SmallProjectionPath?\n\n public init() {}\n\n var isEmpty: Bool { self == ArgumentEffects() }\n\n /// The `description` without the square brackets\n public var bodyDescription: String {\n var results: [String] = []\n if let path = read { results.append("read \(path)") }\n if let path = write { results.append("write \(path)") }\n if let path = copy { results.append("copy \(path)") }\n if let path = destroy { results.append("destroy \(path)") }\n return results.joined(separator: ", ")\n }\n\n public var description: String { "[\(bodyDescription)]" }\n }\n\n /// "Global" effects of the function.\n ///\n /// Global effects are effects which cannot be associated with function arguments,\n /// for example reading from a global variable or reading from loaded value from an argument.\n public struct GlobalEffects : Equatable, CustomStringConvertible, NoReflectionChildren {\n\n /// Memory reads and writes.\n public var memory: Memory\n \n /// Copies and destroys.\n public var ownership: Ownership\n\n /// If true, the function may allocate an object.\n ///\n /// This only includes allocations, which escape the function. Local allocations\n /// are not observable form the outside and are therefore not considered.\n public var allocates: Bool\n\n /// If true, destroys of lexical values may not be hoisted over applies of\n /// the function.\n ///\n /// This is true when the function (or a callee, transitively) contains a\n /// deinit barrier instruction.\n public var isDeinitBarrier: Bool\n\n /// When called with default arguments, it creates an "effect-free" GlobalEffects.\n public init(memory: Memory = Memory(read: false, write: false),\n ownership: Ownership = Ownership(copy: false, destroy: false),\n allocates: Bool = false,\n isDeinitBarrier: Bool = false) {\n self.memory = memory\n self.ownership = ownership\n self.allocates = allocates\n self.isDeinitBarrier = isDeinitBarrier\n }\n\n public mutating func merge(with other: GlobalEffects) {\n memory.merge(with: other.memory)\n ownership.merge(with: other.ownership)\n allocates = allocates || other.allocates\n isDeinitBarrier = isDeinitBarrier || other.isDeinitBarrier\n }\n\n /// Removes effects, which cannot occur for an `argument` value with a given `convention`.\n public func restrictedTo(argument: ProjectedValue, withConvention convention: ArgumentConvention) -> GlobalEffects {\n var result = self\n let isTrivial = argument.value.hasTrivialNonPointerType\n if isTrivial {\n // There cannot be any ownership effects on trivial arguments.\n result.ownership = SideEffects.Ownership()\n }\n switch convention {\n case .indirectIn, .packOwned:\n // indirect-in arguments are consumed by the caller and that not only counts as read but also as a write.\n break\n case .indirectInGuaranteed, .packGuaranteed:\n result.memory.write = false\n result.ownership.destroy = false\n case .indirectOut, .packOut, .packInout:\n result.memory.read = false\n result.ownership.copy = false\n result.ownership.destroy = false\n\n case .directGuaranteed:\n // Note that `directGuaranteed` still has a "destroy" effect, because an object stored in\n // a class property could be destroyed.\n if !argument.path.mayHaveClassProjection {\n result.ownership.destroy = false\n }\n fallthrough\n case .directOwned, .directUnowned:\n if isTrivial {\n // Trivial direct arguments cannot have class properties which could be loaded from/stored to.\n result.memory = SideEffects.Memory()\n }\n\n case .indirectInout, .indirectInoutAliasable, .indirectInCXX:\n break\n }\n return result\n }\n\n public static var worstEffects: GlobalEffects {\n GlobalEffects(memory: .worstEffects, ownership: .worstEffects, allocates: true, isDeinitBarrier: true)\n }\n\n public var description: String {\n var res: [String] = [memory.description, ownership.description].filter { !$0.isEmpty }\n if allocates { res += ["allocate"] }\n if isDeinitBarrier { res += ["deinit_barrier"] }\n return res.joined(separator: ",")\n }\n }\n\n /// Memory read and write effects.\n public struct Memory : Equatable, CustomStringConvertible, NoReflectionChildren {\n public var read: Bool\n public var write: Bool\n\n public init(read: Bool = false, write: Bool = false) {\n self.read = read\n self.write = write\n }\n\n public var description: String {\n switch (read, write) {\n case (false, false): return ""\n case (false, true): return "write"\n case (true, false): return "read"\n case (true, true): return "read,write"\n }\n }\n\n public mutating func merge(with other: Memory) {\n read = read || other.read\n write = write || other.write\n }\n\n public static var noEffects: Memory {\n Memory(read: false, write: false)\n }\n\n public static var worstEffects: Memory {\n Memory(read: true, write: true)\n }\n }\n\n /// Copy and destroy effects.\n public struct Ownership : Equatable, CustomStringConvertible, NoReflectionChildren {\n public var copy: Bool\n public var destroy: Bool\n\n public init(copy: Bool = false, destroy: Bool = false) {\n self.copy = copy\n self.destroy = destroy\n }\n\n public var description: String {\n switch (copy, destroy) {\n case (false, false): return ""\n case (false, true): return "destroy"\n case (true, false): return "copy"\n case (true, true): return "copy,destroy"\n }\n }\n\n public mutating func merge(with other: Ownership) {\n copy = copy || other.copy\n destroy = destroy || other.destroy\n }\n\n public static var worstEffects: Ownership {\n Ownership(copy: true, destroy: true)\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Parsing\n//===----------------------------------------------------------------------===//\n\nextension StringParser {\n\n mutating func parseEffectFromSource(for function: Function,\n params: Dictionary<String, Int>) throws -> EscapeEffects.ArgumentEffect {\n if consume("notEscaping") {\n let argIdx = try parseArgumentIndexFromSource(for: function, params: params)\n let path = try parsePathPatternFromSource(for: function, type: function.argumentTypes[argIdx])\n return EscapeEffects.ArgumentEffect(.notEscaping, argumentIndex: argIdx, pathPattern: path, isDerived: false)\n }\n if consume("escaping") {\n let fromArgIdx = try parseArgumentIndexFromSource(for: function, params: params)\n let fromPath = try parsePathPatternFromSource(for: function, type: function.argumentTypes[fromArgIdx])\n let exclusive = try parseEscapingArrow()\n \n if consume("return") {\n if function.numIndirectResultArguments > 0 {\n if function.numIndirectResultArguments != 1 {\n try throwError("multi-value returns not supported yet")\n }\n let toPath = try parsePathPatternFromSource(for: function, type: function.argumentTypes[0])\n\n // Exclusive escapes are ignored for indirect return values.\n return EscapeEffects.ArgumentEffect(.escapingToArgument(toArgumentIndex: 0, toPath: toPath),\n argumentIndex: fromArgIdx, pathPattern: fromPath, isDerived: false)\n }\n let toPath = try parsePathPatternFromSource(for: function, type: function.resultType)\n return EscapeEffects.ArgumentEffect(.escapingToReturn(toPath: toPath, isExclusive: exclusive),\n argumentIndex: fromArgIdx, pathPattern: fromPath, isDerived: false)\n }\n if exclusive {\n try throwError("exclusive escapes to arguments are not supported")\n }\n let toArgIdx = try parseArgumentIndexFromSource(for: function, params: params)\n let toPath = try parsePathPatternFromSource(for: function, type: function.argumentTypes[toArgIdx])\n return EscapeEffects.ArgumentEffect(.escapingToArgument(toArgumentIndex: toArgIdx, toPath: toPath),\n argumentIndex: fromArgIdx, pathPattern: fromPath, isDerived: false)\n }\n try throwError("unknown effect")\n }\n\n private mutating func parseArgumentIndexFromSource(for function: Function,\n params: Dictionary<String, Int>) throws -> Int {\n if consume("self") {\n guard let selfArgIdx = function.selfArgumentIndex else {\n try throwError("function does not have a self argument")\n }\n return selfArgIdx\n }\n if let name = consumeIdentifier() {\n guard let idx = params[name] else {\n try throwError("parameter not found")\n }\n return idx + function.numIndirectResultArguments\n }\n try throwError("parameter name expected")\n }\n \n private mutating func parsePathPatternFromSource(for function: Function, type: Type) throws -> SmallProjectionPath {\n if consume(".") {\n return try parseProjectionPathFromSource(for: function, type: type)\n }\n if !type.isClass {\n try throwError("the value is not a class - add 'anyValueFields'")\n }\n return SmallProjectionPath()\n }\n\n mutating func parseEffectsFromSIL(to effects: inout FunctionEffects) throws {\n if consume("global") {\n if !consume(":") {\n try throwError("expected ':'")\n }\n try parseGlobalSideEffectsFromSIL(to: &effects)\n return\n }\n let argumentIndex = try parseArgumentIndexFromSIL()\n if !consume(":") {\n try throwError("expected ':'")\n }\n try parseEffectsFromSIL(argumentIndex: argumentIndex, to: &effects)\n }\n \n mutating func parseEffectsFromSIL(argumentIndex: Int, to effects: inout FunctionEffects) throws {\n repeat {\n if consume("noescape") {\n let isDerived = !consume("!")\n let path = try parseProjectionPathFromSIL()\n let effect = EscapeEffects.ArgumentEffect(.notEscaping, argumentIndex: argumentIndex,\n pathPattern: path, isDerived: isDerived)\n effects.escapeEffects.arguments.append(effect)\n\n } else if consume("escape") {\n let isDerived = !consume("!")\n let fromPath = try parseProjectionPathFromSIL()\n let exclusive = try parseEscapingArrow()\n let effect: EscapeEffects.ArgumentEffect\n if consume("%r") {\n let toPath = consume(".") ? try parseProjectionPathFromSIL() : SmallProjectionPath()\n effect = EscapeEffects.ArgumentEffect(.escapingToReturn(toPath: toPath, isExclusive: exclusive),\n argumentIndex: argumentIndex, pathPattern: fromPath, isDerived: isDerived)\n } else {\n if exclusive {\n try throwError("exclusive escapes to arguments are not supported")\n }\n let toArgIdx = try parseArgumentIndexFromSIL()\n let toPath = consume(".") ? try parseProjectionPathFromSIL() : SmallProjectionPath()\n effect = EscapeEffects.ArgumentEffect(.escapingToArgument(toArgumentIndex: toArgIdx, toPath: toPath),\n argumentIndex: argumentIndex, pathPattern: fromPath, isDerived: isDerived)\n }\n effects.escapeEffects.arguments.append(effect)\n\n } else if consume("read") {\n try parseSideEffectPath(\.read, for: argumentIndex)\n } else if consume("write") {\n try parseSideEffectPath(\.write, for: argumentIndex)\n } else if consume("copy") {\n try parseSideEffectPath(\.copy, for: argumentIndex)\n } else if consume("destroy") {\n try parseSideEffectPath(\.destroy, for: argumentIndex)\n } else {\n try throwError("unknown effect")\n }\n } while consume(",")\n\n func parseSideEffectPath(_ e: WritableKeyPath<SideEffects.ArgumentEffects, SmallProjectionPath?>, for argumentIndex: Int) throws {\n var arguments = effects.sideEffects?.arguments ?? []\n while arguments.count <= argumentIndex {\n arguments.append(SideEffects.ArgumentEffects())\n }\n arguments[argumentIndex][keyPath: e] = try parseProjectionPathFromSIL()\n let global = effects.sideEffects?.global ?? SideEffects.GlobalEffects()\n effects.sideEffects = SideEffects(arguments: arguments, global: global)\n }\n }\n\n mutating func parseGlobalSideEffectsFromSIL(to effects: inout FunctionEffects) throws {\n var globalEffects = SideEffects.GlobalEffects()\n repeat {\n if consume("read") { globalEffects.memory.read = true }\n else if consume("write") { globalEffects.memory.write = true }\n else if consume("copy") { globalEffects.ownership.copy = true }\n else if consume("destroy") { globalEffects.ownership.destroy = true }\n else if consume("allocate") { globalEffects.allocates = true }\n else if consume("deinit_barrier") { globalEffects.isDeinitBarrier = true }\n else {\n break\n }\n } while consume(",")\n let arguments = effects.sideEffects?.arguments ?? []\n effects.sideEffects = SideEffects(arguments: arguments, global: globalEffects)\n return\n }\n\n private mutating func parseArgumentIndexFromSIL() throws -> Int {\n if consume("%") {\n if let argIdx = consumeInt() {\n return argIdx\n }\n try throwError("expected argument index")\n }\n try throwError("expected parameter")\n }\n\n private mutating func parseEscapingArrow() throws -> Bool {\n if consume("=>") { return true }\n if consume("->") { return false }\n try throwError("expected '=>' or '->'")\n }\n}\n\npublic extension Optional where Wrapped == SmallProjectionPath {\n mutating func merge(with path: SmallProjectionPath) {\n if let existingPath = self {\n self = existingPath.merge(with: path)\n } else {\n self = path\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Effects.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Effects.swift
Swift
32,826
0.95
0.274155
0.271255
awesome-app
824
2025-04-13T13:52:06.532473
GPL-3.0
false
2301b2fb3a07e1d1218292a3a700257f
//===--- ForwardingInstruction.swift - forwarding instruction protocols ---===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SILBridging\n\n/// An instruction that forwards ownership from operands to results.\n///\n/// Forwarding instructions are not allowed to store the value or\n/// propagate its bits in any way that isn't tracked by its\n/// results. Passes assume that a forwarding value is nonescaping as\n/// long as its results are nonescaping.\npublic protocol ForwardingInstruction : Instruction {\n var singleForwardedOperand: Operand? { get }\n\n /// Return true if the result has the same object identify, and therefore the same reference counting semantics as the\n /// source. This is true for most forwarding operations unless they extract or aggregate components.\n var preservesIdentity: Bool { get }\n\n /// Return true if the forwarded value has the same representation. If true, then the result can be mapped to the same storage without a move or copy.\n var preservesRepresentation: Bool { get }\n\n var canForwardGuaranteedValues: Bool { get }\n\n var canForwardOwnedValues: Bool { get }\n}\n\nextension ForwardingInstruction {\n public var forwardedOperands: OperandArray {\n // Some instructions have multiple real operands but only forward one.\n if let singleForwardingOp = singleForwardedOperand {\n return OperandArray(base: singleForwardingOp, count: 1)\n }\n // All others forward all operands (for enum, this may be zero operands).\n return operands\n }\n\n public var forwardedResults: ForwardedResults {\n ForwardedResults(inst: self)\n }\n\n /// If forwarding ownership is owned, then the instruction moves an owned operand to its result, ending its lifetime. If forwarding ownership is guaranteed, then the instruction propagates the lifetime of its borrows operand through its result.\n ///\n /// The resulting forwarded value's ownership (Value.ownership) is not identical to the instruction's forwarding ownership property. It differs when the result is trivial type. e.g. an owned or guaranteed value can be cast to a trivial type using owned or guaranteed forwarding.\n public var forwardingOwnership: Ownership {\n Ownership(bridged: bridged.ForwardingInst_forwardingOwnership())\n }\n \n /// A forwarding instruction preserves reference counts if it has a dynamically non-trivial result in which all references are forwarded from the operand.\n ///\n /// A cast can only forward guaranteed values if it preserves reference counts. Such casts cannot release any references within their operand's value and cannot retain any references owned by their result.\n public var preservesReferenceCounts: Bool {\n bridged.ForwardingInst_preservesOwnership()\n }\n}\n\nextension Value {\n // If this value is produced by a ForwardingInstruction, return that instruction. This is convenient for following the forwarded value chain.\n // Unlike definingInstruction, a value's forwardingInstruction is not necessarily a valid insertion point. \n public var forwardingInstruction: ForwardingInstruction? {\n if let inst = definingInstructionOrTerminator {\n return inst as? ForwardingInstruction\n }\n return nil\n }\n}\n\nextension Value {\n public func isForwarded(from: Value) -> Bool {\n if self == from {\n return true\n }\n if let forward = self.forwardingInstruction,\n let singleOp = forward.singleForwardedOperand {\n return singleOp.value.isForwarded(from: from)\n }\n return false\n }\n}\n\n//===----------------------------------------------------------------------===//\n// singleForwardedOperand\n//===----------------------------------------------------------------------===//\n\nextension ForwardingInstruction {\n // See ForwardingOperation::getSingleForwardingOperand().\n public var singleForwardedOperand: Operand? {\n let definedOps = self.definedOperands\n assert(definedOps.count == 1, "expected single operand for forwarding")\n return definedOps[0]\n }\n}\n\nextension ConversionInstruction {\n public var singleForwardedOperand: Operand? { operand }\n}\n\n//===----------------------------------------------------------------------===//\n// forwardedResults\n//===----------------------------------------------------------------------===//\n\npublic struct ForwardedResults : Collection {\n private let inst: Instruction\n private let maxResults: Int\n\n fileprivate init(inst: ForwardingInstruction) {\n self.inst = inst\n if let ti = inst as? TermInst {\n self.maxResults = ti.successors.count\n } else {\n self.maxResults = inst.results.count\n }\n }\n\n public var startIndex: Int { skipEmptyResults(at: 0) }\n\n public var endIndex: Int { maxResults }\n\n public func index(after index: Int) -> Int {\n return skipEmptyResults(at: index + 1)\n }\n\n public subscript(_ index: Int) -> Value {\n if let ti = inst as? TermInst {\n return getTerminatorResult(termInst: ti, index: index)!\n }\n return inst.results[index]\n }\n\n private func skipEmptyResults(at index: Int) -> Int {\n guard let ti = inst as? TermInst else { return index }\n var next = index\n while next != endIndex {\n if getTerminatorResult(termInst: ti, index: next) != nil { break }\n next += 1\n }\n return next\n }\n\n // Forwarding terminators have a zero or one result per successor.\n private func getTerminatorResult(termInst: TermInst,\n index: Int) -> Argument? {\n let succ = termInst.successors[index]\n guard succ.arguments.count == 1 else {\n // The default enum payload may be empty.\n assert(succ.arguments.count == 0, "terminator must forward a single value")\n return nil\n }\n return succ.arguments[0]\n }\n}\n\n//===----------------------------------------------------------------------===//\n// conforming instructions\n//===----------------------------------------------------------------------===//\n\n// -----------------------------------------------------------------------------\n// Instructions with multiple forwarded operands have nil singleForwardedOperand.\n\nextension StructInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? { nil }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension TupleInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? { nil }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension LinearFunctionInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? { nil }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension DifferentiableFunctionInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? { nil }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\n// -----------------------------------------------------------------------------\n// Instructions with a singleForwardedOperand and additional operands.\n\nextension MarkDependenceInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? {\n return valueOperand\n }\n\n public var preservesIdentity: Bool { true }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension RefToBridgeObjectInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? {\n return convertedOperand\n }\n\n public var preservesIdentity: Bool { true }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension TuplePackExtractInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? { return tupleOperand }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\n// -----------------------------------------------------------------------------\n// conversion instructions\n\n/// An instruction that forwards a single value to a single result.\n///\n/// For legacy reasons, some ForwardingInstructions that fit the\n/// SingleValueInstruction and UnaryInstruction requirements are not\n/// considered ConversionInstructions because certain routines do not\n/// want to see through them (InitExistentialValueInst,\n/// DeinitExistentialValueInst, OpenExistentialValueInst,\n/// OpenExistentialValueInst). This most likely has to do with\n/// type-dependent operands, although any ConversionInstruction should\n/// support type-dependent operands.\npublic protocol ConversionInstruction : SingleValueInstruction, UnaryInstruction, ForwardingInstruction {}\n\nextension ConversionInstruction {\n /// Conversion instructions naturally preserve identity as long as they preserve reference counts because they do not\n /// aggregate or disaggregate values. They can only lose identity by destroying the source object and instantiating a\n /// new object, like certain bridging casts do.\n public var preservesIdentity: Bool { preservesReferenceCounts }\n}\n\nextension MarkUnresolvedNonCopyableValueInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension MarkUninitializedInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { false }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension ConvertFunctionInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension ThinToThickFunctionInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension CopyableToMoveOnlyWrapperValueInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension MoveOnlyWrapperToCopyableValueInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension MoveOnlyWrapperToCopyableBoxInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension UpcastInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension UncheckedRefCastInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension UnconditionalCheckedCastInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension BridgeObjectToRefInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension UncheckedValueCastInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension DropDeinitInst : ConversionInstruction {\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { false }\n public var canForwardOwnedValues: Bool { true }\n}\n\n// -----------------------------------------------------------------------------\n// other forwarding instructions\n\nextension EnumInst : ForwardingInstruction {\n public var singleForwardedOperand: Operand? {\n return operand // nil for an enum with no payload\n }\n\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension DestructureTupleInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension DestructureStructInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension FunctionExtractIsolationInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\nextension InitExistentialRefInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension OpenExistentialRefInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension OpenExistentialValueInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension OpenExistentialBoxValueInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension StructExtractInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\nextension TupleExtractInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\nextension DifferentiableFunctionExtractInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\nextension CheckedCastBranchInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension UncheckedEnumDataInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension SwitchEnumInst : ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension MarkUnresolvedReferenceBindingInst : ForwardingInstruction {\n public var preservesIdentity: Bool { true }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension LinearFunctionExtractInst: ForwardingInstruction {\n public var preservesIdentity: Bool { false }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { true }\n}\n\nextension BorrowedFromInst: ForwardingInstruction {\n public var singleForwardedOperand: Operand? { operands[0] }\n public var preservesIdentity: Bool { true }\n public var preservesRepresentation: Bool { true }\n public var canForwardGuaranteedValues: Bool { true }\n public var canForwardOwnedValues: Bool { false }\n}\n\n// -----------------------------------------------------------------------------\n// ownership transition instructions\n\n/// An instruction that transfers lifetime dependence from a single operand to a single result. The operand and result\n/// have the same identity, but they are not part of the same forwarded lifetime:\n/// copy_value, move_value, begin_borrow.\n///\n/// OwnershipTransitionInstructions always preserve the identity of the source. See swift::isIdentityPreservingRefCast.\npublic protocol OwnershipTransitionInstruction: UnaryInstruction {\n var ownershipResult: Value { get }\n}\n\nextension OwnershipTransitionInstruction where Self: SingleValueInstruction {\n public var ownershipResult: Value { self }\n}\n\n// CopyingInstruction implies OwnershipTransitionInstruction\n\nextension MoveValueInst: OwnershipTransitionInstruction {}\n\nextension BeginBorrowInst: OwnershipTransitionInstruction {}\n\nextension BeginCOWMutationInst: OwnershipTransitionInstruction {\n public var ownershipResult: Value { instanceResult }\n}\n\nextension EndCOWMutationInst: OwnershipTransitionInstruction {}\n\nextension EndInitLetRefInst: OwnershipTransitionInstruction {}\n\nextension BeginDeallocRefInst: OwnershipTransitionInstruction {}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ForwardingInstruction.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_ForwardingInstruction.swift
Swift
18,959
0.95
0.038384
0.173594
vue-tools
991
2025-03-17T04:34:20.394712
Apache-2.0
false
61d0e488bb101285e30b22e13254d297
//===--- Function.swift - Defines the Function class ----------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\n@_semantics("arc.immortal")\nfinal public class Function : CustomStringConvertible, HasShortDescription, Hashable {\n public private(set) var effects = FunctionEffects()\n\n public var name: StringRef {\n return StringRef(bridged: bridged.getName())\n }\n\n public var location: Location {\n return Location(bridged: bridged.getLocation())\n }\n\n final public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n\n public var shortDescription: String { name.string }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n\n public var wasDeserializedCanonical: Bool { bridged.wasDeserializedCanonical() }\n\n public var isTrapNoReturn: Bool { bridged.isTrapNoReturn() }\n\n public var isAutodiffVJP: Bool { bridged.isAutodiffVJP() }\n\n public var isConvertPointerToPointerArgument: Bool { bridged.isConvertPointerToPointerArgument() }\n\n public var specializationLevel: Int { bridged.specializationLevel() }\n\n public var isSpecialization: Bool { bridged.isSpecialization() }\n\n public var hasOwnership: Bool { bridged.hasOwnership() }\n\n public var hasLoweredAddresses: Bool { bridged.hasLoweredAddresses() }\n\n /// The lowered function type in the expansion context of self.\n ///\n /// Always expanding a function type means that the opaque result types\n /// have the correct generic signature. For example:\n /// @substituted <τ_0_0> () -> @out τ_0_0 for <some P>\n /// is lowered to this inside its module:\n /// @substituted <τ_0_0> () -> @out τ_0_0 for <ActualResultType>\n /// and this outside its module\n /// @substituted <τ_0_0> () -> @out τ_0_0 for <some P>\n public var loweredFunctionType: CanonicalType {\n CanonicalType(bridged: bridged.getLoweredFunctionTypeInContext())\n }\n\n public var genericSignature: GenericSignature {\n GenericSignature(bridged: bridged.getGenericSignature())\n }\n\n public var forwardingSubstitutionMap: SubstitutionMap {\n SubstitutionMap(bridged: bridged.getForwardingSubstitutionMap())\n }\n\n public func mapTypeIntoContext(_ type: AST.`Type`) -> AST.`Type` {\n return AST.`Type`(bridged: bridged.mapTypeIntoContext(type.bridged))\n }\n\n /// Returns true if the function is a definition and not only an external declaration.\n ///\n /// This is the case if the functioun contains a body, i.e. some basic blocks.\n public var isDefinition: Bool { blocks.first != nil }\n\n public var blocks : BasicBlockList { BasicBlockList(first: bridged.getFirstBlock().block) }\n\n public var entryBlock: BasicBlock { blocks.first! }\n\n public var arguments: LazyMapSequence<ArgumentArray, FunctionArgument> {\n entryBlock.arguments.lazy.map { $0 as! FunctionArgument }\n }\n\n public func argument(at index: Int) -> FunctionArgument {\n entryBlock.arguments[index] as! FunctionArgument\n }\n\n /// All instructions of all blocks.\n public var instructions: LazySequence<FlattenSequence<LazyMapSequence<BasicBlockList, InstructionList>>> {\n blocks.lazy.flatMap { $0.instructions }\n }\n\n public var reversedInstructions: LazySequence<FlattenSequence<LazyMapSequence<ReverseBasicBlockList, ReverseInstructionList>>> {\n blocks.reversed().lazy.flatMap { $0.instructions.reversed() }\n }\n \n public var returnInstruction: ReturnInst? {\n for block in blocks.reversed() {\n if let retInst = block.terminator as? ReturnInst { return retInst }\n }\n return nil\n }\n\n /// True if the callee function is annotated with @_semantics("programtermination_point").\n /// This means that the function terminates the program.\n public var isProgramTerminationPoint: Bool { hasSemanticsAttribute("programtermination_point") }\n\n public var isTransparent: Bool { bridged.isTransparent() }\n\n public var isAsync: Bool { bridged.isAsync() }\n\n /// True if this is a `[global_init]` function.\n ///\n /// Such a function is typically a global addressor which calls the global's\n /// initializer (`[global_init_once_fn]`) via a `builtin "once"`.\n public var isGlobalInitFunction: Bool { bridged.isGlobalInitFunction() }\n\n /// True if this is a `[global_init_once_fn]` function.\n ///\n /// Such a function allocates a global and stores the global's init value.\n /// It's called from a `[global_init]` function via a `builtin "once"`.\n public var isGlobalInitOnceFunction: Bool { bridged.isGlobalInitOnceFunction() }\n\n public var isDestructor: Bool { bridged.isDestructor() }\n\n public var isGeneric: Bool { bridged.isGeneric() }\n\n public var linkage: Linkage { bridged.getLinkage().linkage }\n\n /// True, if the linkage of the function indicates that it is visible outside the current\n /// compilation unit and therefore not all of its uses are known.\n ///\n /// For example, `public` linkage.\n public var isPossiblyUsedExternally: Bool {\n return bridged.isPossiblyUsedExternally()\n }\n\n /// True, if the linkage of the function indicates that it has a definition outside the\n /// current compilation unit.\n ///\n /// For example, `public_external` linkage.\n public var isDefinedExternally: Bool { linkage.isExternal }\n\n public func hasSemanticsAttribute(_ attr: StaticString) -> Bool {\n attr.withUTF8Buffer { (buffer: UnsafeBufferPointer<UInt8>) in\n bridged.hasSemanticsAttr(BridgedStringRef(data: buffer.baseAddress!, count: buffer.count))\n }\n }\n public var isSerialized: Bool { bridged.isSerialized() }\n\n public var isAnySerialized: Bool { bridged.isAnySerialized() }\n\n public enum SerializedKind {\n case notSerialized, serialized, serializedForPackage\n }\n\n public var serializedKind: SerializedKind {\n switch bridged.getSerializedKind() {\n case .IsNotSerialized: return .notSerialized\n case .IsSerialized: return .serialized\n case .IsSerializedForPackage: return .serializedForPackage\n @unknown default: fatalError()\n }\n }\n\n private func serializedKindBridged(_ arg: SerializedKind) -> BridgedFunction.SerializedKind {\n switch arg {\n case .notSerialized: return .IsNotSerialized\n case .serialized: return .IsSerialized\n case .serializedForPackage: return .IsSerializedForPackage\n }\n }\n\n public func canBeInlinedIntoCaller(withSerializedKind callerSerializedKind: SerializedKind) -> Bool {\n switch serializedKind {\n // If both callee and caller are not_serialized, the callee can be inlined into the caller\n // during SIL inlining passes even if it (and the caller) might contain private symbols.\n case .notSerialized:\n return callerSerializedKind == .notSerialized;\n\n // If Package-CMO is enabled, we serialize package, public, and @usableFromInline decls as\n // [serialized_for_package].\n // Their bodies must not, however, leak into @inlinable functons (that are [serialized])\n // since they are inlined outside of their defining module.\n //\n // If this callee is [serialized_for_package], the caller must be either non-serialized\n // or [serialized_for_package] for this callee's body to be inlined into the caller.\n // It can however be referenced by [serialized] caller.\n case .serializedForPackage:\n return callerSerializedKind != .serialized;\n case .serialized:\n return true;\n }\n }\n\n public func hasValidLinkageForFragileRef(_ kind: SerializedKind) -> Bool {\n bridged.hasValidLinkageForFragileRef(serializedKindBridged(kind))\n }\n\n public enum ThunkKind {\n case noThunk, thunk, reabstractionThunk, signatureOptimizedThunk\n }\n\n public var thunkKind: ThunkKind {\n switch bridged.isThunk() {\n case .IsNotThunk: return .noThunk\n case .IsThunk: return .thunk\n case .IsReabstractionThunk: return .reabstractionThunk\n case .IsSignatureOptimizedThunk: return .signatureOptimizedThunk\n default:\n fatalError()\n }\n }\n\n /// True, if the function runs with a swift 5.1 runtime.\n /// Note that this is function specific, because inlinable functions are de-serialized\n /// in a client module, which might be compiled with a different deployment target.\n public var isSwift51RuntimeAvailable: Bool {\n bridged.isSwift51RuntimeAvailable()\n }\n\n public var needsStackProtection: Bool {\n bridged.needsStackProtection()\n }\n\n public var isDeinitBarrier: Bool {\n effects.sideEffects?.global.isDeinitBarrier ?? true\n }\n\n public enum PerformanceConstraints {\n case none\n case noAllocations\n case noLocks\n case noRuntime\n case noExistentials\n case noObjCRuntime\n }\n\n public var performanceConstraints: PerformanceConstraints {\n switch bridged.getPerformanceConstraints() {\n case .None: return .none\n case .NoAllocation: return .noAllocations\n case .NoLocks: return .noLocks\n case .NoRuntime: return .noRuntime\n case .NoExistentials: return .noExistentials\n case .NoObjCBridging: return .noObjCRuntime\n default: fatalError("unknown performance constraint")\n }\n }\n\n public enum InlineStrategy {\n case automatic\n case never\n case always\n }\n\n public var inlineStrategy: InlineStrategy {\n switch bridged.getInlineStrategy() {\n case .InlineDefault: return .automatic\n case .NoInline: return .never\n case .AlwaysInline: return .always\n default:\n fatalError()\n }\n }\n\n public enum SourceFileKind {\n case library /// A normal .swift file.\n case main /// A .swift file that can have top-level code.\n case sil /// Came from a .sil file.\n case interface /// Came from a .swiftinterface file, representing another module.\n case macroExpansion /// Came from a macro expansion.\n case defaultArgument /// Came from default argument at caller side\n };\n\n public var sourceFileKind: SourceFileKind? {\n switch bridged.getSourceFileKind() {\n case .Library: return .library\n case .Main: return .main\n case .SIL: return .sil\n case .Interface: return .interface\n case .MacroExpansion: return .macroExpansion\n case .DefaultArgument: return .defaultArgument\n case .None: return nil\n @unknown default:\n fatalError("unknown enum case")\n }\n }\n}\n\npublic func == (lhs: Function, rhs: Function) -> Bool { lhs === rhs }\npublic func != (lhs: Function, rhs: Function) -> Bool { lhs !== rhs }\n\n// Function conventions.\nextension Function {\n public var convention: FunctionConvention {\n FunctionConvention(for: loweredFunctionType, in: self)\n }\n\n public var argumentConventions: ArgumentConventions {\n ArgumentConventions(convention: convention)\n }\n\n // FIXME: Change this to argumentConventions.indirectSILResultCount.\n // This is incorrect in two cases: it does not include the indirect\n // error result, and, prior to address lowering, does not include\n // pack results.\n public var numIndirectResultArguments: Int { bridged.getNumIndirectFormalResults() }\n\n public var hasIndirectErrorArgument: Bool { bridged.hasIndirectErrorResult() }\n\n /// The number of arguments which correspond to parameters (and not to indirect results).\n public var numParameterArguments: Int { convention.parameters.count }\n\n /// The slice of arguments starting at argumentConventions.firstParameterIndex.\n public var parameters: LazyMapSequence<Slice<ArgumentArray>, FunctionArgument> {\n let args = arguments\n return args[argumentConventions.firstParameterIndex..<args.count]\n }\n\n /// The total number of arguments.\n ///\n /// This is the sum of indirect result arguments and parameter arguments.\n /// If the function is a definition (i.e. it has at least an entry block), this is the\n /// number of arguments of the function's entry block.\n public var numArguments: Int { argumentConventions.count }\n\n public var hasSelfArgument: Bool { argumentConventions.selfIndex != nil }\n\n public var selfArgumentIndex: Int? { argumentConventions.selfIndex }\n\n public var selfArgument: FunctionArgument? {\n if let selfArgIdx = selfArgumentIndex {\n return arguments[selfArgIdx]\n }\n return nil\n }\n\n public var dynamicSelfMetadata: FunctionArgument? {\n if bridged.hasDynamicSelfMetadata() {\n return arguments.last!\n }\n return nil\n }\n\n public var argumentTypes: ArgumentTypeArray { ArgumentTypeArray(function: self) }\n\n public var resultType: Type { bridged.getSILResultType().type }\n\n public var hasUnsafeNonEscapableResult: Bool {\n return bridged.hasUnsafeNonEscapableResult()\n }\n\n public var hasResultDependence: Bool {\n convention.resultDependencies != nil\n }\n}\n\npublic struct ArgumentTypeArray : RandomAccessCollection, FormattedLikeArray {\n fileprivate let function: Function\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { function.bridged.getNumSILArguments() }\n\n public subscript(_ index: Int) -> Type {\n function.bridged.getSILArgumentType(index).type\n }\n}\n\n// Function effects.\nextension Function {\n /// Kinds of effect attributes which can be defined for a Swift function.\n public enum EffectAttribute {\n /// No effect attribute is specified.\n case none\n \n /// `[readnone]`\n ///\n /// A readnone function does not have any observable memory read or write operations.\n /// This does not mean that the function cannot read or write at all. For example,\n /// it’s allowed to allocate and write to local objects inside the function.\n ///\n /// A function can be marked as readnone if two calls of the same function with the\n /// same parameters can be simplified to one call (e.g. by the CSE optimization).\n /// Some conclusions:\n /// * A readnone function must not return a newly allocated class instance.\n /// * A readnone function can return a newly allocated copy-on-write object,\n /// like an Array, because COW data types conceptually behave like value types.\n /// * A readnone function must not release any parameter or any object indirectly\n /// referenced from a parameter.\n /// * Any kind of observable side-effects are not allowed, like `print`, file IO, etc.\n case readNone\n \n /// `[readonly]`\n ///\n /// A readonly function does not have any observable memory write operations.\n /// Similar to readnone, a readonly function is allowed to contain writes to e.g. local objects, etc.\n ///\n /// A function can be marked as readonly if it’s save to eliminate a call to such\n /// a function if its return value is not used.\n /// The same conclusions as for readnone also apply to readonly.\n case readOnly\n \n /// `[releasenone]`\n ///\n /// A releasenone function must not perform any observable release-operation on an object.\n /// This means, it must not do anything which might let the caller observe any decrement of\n /// a reference count or any deallocations.\n /// Note that it's allowed to release an object if the release is balancing a retain in the\n /// same function. Also, it's allowed to release (and deallocate) local objects which were\n /// allocated in the same function.\n case releaseNone\n }\n\n /// The effect attribute which is specified in the source code (if any).\n public var effectAttribute: EffectAttribute {\n switch bridged.getEffectAttribute() {\n case .ReadNone: return .readNone\n case .ReadOnly: return .readOnly\n case .ReleaseNone: return .releaseNone\n default: return .none\n }\n }\n\n // Only to be called by PassContext\n public func _modifyEffects(_ body: (inout FunctionEffects) -> ()) {\n body(&effects)\n }\n}\n\n// Bridging utilities\n\nextension Function {\n public var bridged: BridgedFunction {\n BridgedFunction(obj: SwiftObject(self))\n }\n\n static func register() {\n func checkLayout(_ p: UnsafeMutablePointer<FunctionEffects>,\n data: UnsafeMutableRawPointer, size: Int) {\n assert(MemoryLayout<FunctionEffects>.size <= size, "wrong FunctionInfo size")\n assert(UnsafeMutableRawPointer(p) == data, "wrong FunctionInfo layout")\n }\n\n let metatype = unsafeBitCast(Function.self, to: SwiftMetatype.self)\n BridgedFunction.registerBridging(metatype,\n // initFn\n { (f: BridgedFunction, data: UnsafeMutableRawPointer, size: Int) in\n checkLayout(&f.function.effects, data: data, size: size)\n data.initializeMemory(as: FunctionEffects.self, repeating: FunctionEffects(), count: 1)\n },\n // destroyFn\n { (f: BridgedFunction, data: UnsafeMutableRawPointer, size: Int) in\n checkLayout(&f.function.effects, data: data, size: size)\n data.assumingMemoryBound(to: FunctionEffects.self).deinitialize(count: 1)\n },\n // writeFn\n { (f: BridgedFunction, os: BridgedOStream, idx: Int) in\n let s: String\n let effects = f.function.effects\n if idx >= 0 {\n if idx < effects.escapeEffects.arguments.count {\n s = effects.escapeEffects.arguments[idx].bodyDescription\n } else {\n let globalIdx = idx - effects.escapeEffects.arguments.count\n if globalIdx == 0 {\n s = effects.sideEffects!.global.description\n } else {\n let seIdx = globalIdx - 1\n s = effects.sideEffects!.getArgumentEffects(for: seIdx).bodyDescription\n }\n }\n } else {\n s = effects.description\n }\n s._withBridgedStringRef { $0.write(os) }\n },\n // parseFn:\n { (f: BridgedFunction, str: BridgedStringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in\n do {\n var parser = StringParser(String(str))\n let function = f.function\n\n switch mode {\n case .argumentEffectsFromSource:\n let paramToIdx = paramNames.withElements(ofType: BridgedStringRef.self) {\n (buffer: UnsafeBufferPointer<BridgedStringRef>) -> Dictionary<String, Int> in\n let keyValPairs = buffer.enumerated().lazy.map { (String($0.1), $0.0) }\n return Dictionary(uniqueKeysWithValues: keyValPairs)\n }\n let effect = try parser.parseEffectFromSource(for: function, params: paramToIdx)\n function.effects.escapeEffects.arguments.append(effect)\n case .argumentEffectsFromSIL:\n try parser.parseEffectsFromSIL(argumentIndex: argumentIndex, to: &function.effects)\n case .globalEffectsFromSIL:\n try parser.parseGlobalSideEffectsFromSIL(to: &function.effects)\n case .multipleEffectsFromSIL:\n try parser.parseEffectsFromSIL(to: &function.effects)\n default:\n fatalError("invalid ParseEffectsMode")\n }\n if !parser.isEmpty() { try parser.throwError("syntax error") }\n } catch let error as ParsingError {\n return BridgedFunction.ParsingError(message: error.message.utf8Start, position: error.position)\n } catch {\n fatalError()\n }\n return BridgedFunction.ParsingError(message: nil, position: 0)\n },\n // copyEffectsFn\n { (toFunc: BridgedFunction, fromFunc: BridgedFunction) -> Int in\n let srcFunc = fromFunc.function\n let destFunc = toFunc.function\n let srcResultArgs = srcFunc.numIndirectResultArguments\n let destResultArgs = destFunc.numIndirectResultArguments\n \n // We only support reabstraction (indirect -> direct) of a single\n // return value.\n if srcResultArgs != destResultArgs &&\n (srcResultArgs > 1 || destResultArgs > 1) {\n return 0\n }\n destFunc.effects =\n FunctionEffects(copiedFrom: srcFunc.effects,\n resultArgDelta: destResultArgs - srcResultArgs)\n return 1\n },\n // getEffectInfo\n { (f: BridgedFunction, idx: Int) -> BridgedFunction.EffectInfo in\n let effects = f.function.effects\n if idx < effects.escapeEffects.arguments.count {\n let effect = effects.escapeEffects.arguments[idx]\n return BridgedFunction.EffectInfo(argumentIndex: effect.argumentIndex,\n isDerived: effect.isDerived, isEmpty: false, isValid: true)\n }\n if let sideEffects = effects.sideEffects {\n let globalIdx = idx - effects.escapeEffects.arguments.count\n if globalIdx == 0 {\n return BridgedFunction.EffectInfo(argumentIndex: -1, isDerived: true, isEmpty: false, isValid: true)\n }\n let seIdx = globalIdx - 1\n if seIdx < sideEffects.arguments.count {\n return BridgedFunction.EffectInfo(argumentIndex: seIdx, isDerived: true,\n isEmpty: sideEffects.arguments[seIdx].isEmpty, isValid: true)\n }\n }\n return BridgedFunction.EffectInfo(argumentIndex: -1, isDerived: false, isEmpty: true, isValid: false)\n },\n // getMemBehaviorFn\n { (f: BridgedFunction, observeRetains: Bool) -> BridgedMemoryBehavior in\n let e = f.function.getSideEffects()\n return e.getMemBehavior(observeRetains: observeRetains)\n },\n // argumentMayRead (used by the MemoryLifetimeVerifier)\n { (f: BridgedFunction, bridgedArgOp: BridgedOperand, bridgedAddr: BridgedValue) -> Bool in\n let argOp = Operand(bridged: bridgedArgOp)\n let addr = bridgedAddr.value\n let applySite = argOp.instruction as! FullApplySite\n let addrPath = addr.accessPath\n let calleeArgIdx = applySite.calleeArgumentIndex(of: argOp)!\n let convention = applySite.convention(of: argOp)!\n assert(convention.isIndirectIn || convention.isInout)\n let argPath = argOp.value.accessPath\n assert(!argPath.isDistinct(from: addrPath))\n let path = argPath.getProjection(to: addrPath) ?? SmallProjectionPath()\n let effects = f.function.getSideEffects(forArgument: argOp.value.at(path),\n atIndex: calleeArgIdx,\n withConvention: convention)\n return effects.memory.read\n }\n )\n }\n}\n\nextension BridgedFunction {\n public var function: Function { obj.getAs(Function.self) }\n}\n\nextension OptionalBridgedFunction {\n public var function: Function? { obj.getAs(Function.self) }\n}\n\npublic extension SideEffects.GlobalEffects {\n func getMemBehavior(observeRetains: Bool) -> BridgedMemoryBehavior {\n if allocates || ownership.destroy || (ownership.copy && observeRetains) {\n return .MayHaveSideEffects\n }\n switch (memory.read, memory.write) {\n case (false, false): return .None\n case (true, false): return .MayRead\n case (false, true): return .MayWrite\n case (true, true): return .MayReadWrite\n }\n }\n}\n\npublic struct BasicBlockList : CollectionLikeSequence, IteratorProtocol {\n private var currentBlock: BasicBlock?\n\n public init(first: BasicBlock?) { currentBlock = first }\n\n public mutating func next() -> BasicBlock? {\n if let block = currentBlock {\n currentBlock = block.next\n return block\n }\n return nil\n }\n\n public var first: BasicBlock? { currentBlock }\n\n public func reversed() -> ReverseBasicBlockList {\n if let block = currentBlock {\n let lastBlock = block.parentFunction.bridged.getLastBlock().block\n return ReverseBasicBlockList(first: lastBlock)\n }\n return ReverseBasicBlockList(first: nil)\n }\n}\n\npublic struct ReverseBasicBlockList : CollectionLikeSequence, IteratorProtocol {\n private var currentBlock: BasicBlock?\n\n public init(first: BasicBlock?) { currentBlock = first }\n\n public mutating func next() -> BasicBlock? {\n if let block = currentBlock {\n currentBlock = block.previous\n return block\n }\n return nil\n }\n\n public var first: BasicBlock? { currentBlock }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Function.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Function.swift
Swift
24,244
0.95
0.178571
0.209174
node-utils
38
2024-09-01T07:27:55.534908
GPL-3.0
false
43a3e812b74cda2ccb1908a757535802
//===--- FunctionConvention.swift - function conventions ------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\n/// SIL function parameter and result conventions based on the AST\n/// function type and SIL stage.\n///\n/// Provides Results and Parameters collections. This does not know\n/// anything about FunctionArguments. Use ArgumentConventions instead to\n/// maps FunctionArguments down to these conventions.\n///\n/// The underlying FunctionType must be contextual and expanded. SIL\n/// has no use for interface types or unexpanded types.\npublic struct FunctionConvention : CustomStringConvertible {\n let functionType: CanonicalType\n let hasLoweredAddresses: Bool\n\n public init(for functionType: CanonicalType, in function: Function) {\n self.init(for: functionType, hasLoweredAddresses: function.hasLoweredAddresses)\n }\n\n public init(for functionType: CanonicalType, hasLoweredAddresses: Bool) {\n assert(!functionType.hasTypeParameter, "requires contextual type")\n self.functionType = functionType\n self.hasLoweredAddresses = hasLoweredAddresses\n }\n\n /// All results including the error.\n public var results: Results {\n Results(bridged: SILFunctionType_getResultsWithError(functionType.bridged),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n\n public var errorResult: ResultInfo? {\n return ResultInfo(\n bridged: SILFunctionType_getErrorResult(functionType.bridged),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n\n /// Number of indirect results including the error.\n /// This avoids quadratic lazy iteration on indirectResults.count.\n public var indirectSILResultCount: Int {\n // TODO: Return packs directly in lowered-address mode\n return hasLoweredAddresses\n ? SILFunctionType_getNumIndirectFormalResultsWithError(functionType.bridged)\n : SILFunctionType_getNumPackResults(functionType.bridged)\n }\n\n /// Indirect results including the error.\n public var indirectSILResults: LazyFilterSequence<Results> {\n hasLoweredAddresses\n ? results.lazy.filter { $0.isSILIndirect }\n : results.lazy.filter { $0.convention == .pack }\n }\n\n public var parameters: Parameters {\n Parameters(bridged: SILFunctionType_getParameters(functionType.bridged),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n\n public var hasSelfParameter: Bool {\n SILFunctionType_hasSelfParam(functionType.bridged)\n }\n\n public var yields: Yields {\n Yields(bridged: SILFunctionType_getYields(functionType.bridged),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n\n /// If the function result depends on any parameters, return a Collection of LifetimeDependenceConventions for the\n /// dependence source parameters.\n public var resultDependencies: LifetimeDependencies? {\n lifetimeDependencies(for: parameters.count)\n }\n\n /// If the parameter indexed by 'targetParameterIndex' is the target of any dependencies on other parameters, return a\n /// Collection of LifetimeDependenceConventions for the dependence source parameters.\n public func parameterDependencies(for targetParameterIndex: Int) -> LifetimeDependencies? {\n lifetimeDependencies(for: targetParameterIndex)\n }\n\n public func hasLifetimeDependencies() -> Bool {\n return SILFunctionType_getLifetimeDependencies(functionType.bridged).count() != 0\n }\n\n public var description: String {\n var str = functionType.description\n for paramIdx in 0..<parameters.count {\n str += "\nparameter: " + parameters[paramIdx].description\n if let deps = parameterDependencies(for: paramIdx) {\n str += "\n lifetime: \(deps)"\n }\n }\n results.forEach { str += "\n result: " + $0.description }\n if let deps = resultDependencies {\n str += "\n lifetime: \(deps)"\n }\n return str\n }\n}\n\n/// A function result type and the rules for returning it in SIL.\npublic struct ResultInfo : CustomStringConvertible {\n /// The unsubstituted parameter type that describes the abstract\n /// calling convention of the parameter.\n ///\n /// TODO: For most purposes, you probably want \c returnValueType.\n public let type: BridgedASTType\n public let convention: ResultConvention\n public let hasLoweredAddresses: Bool\n\n /// Is this result returned indirectly in SIL? Most formally\n /// indirect results can be returned directly in SIL. This depends\n /// on whether the calling function has lowered addresses.\n public var isSILIndirect: Bool {\n switch convention {\n case .indirect:\n return hasLoweredAddresses || type.isExistentialArchetypeWithError()\n case .pack:\n return true\n case .owned, .unowned, .unownedInnerPointer, .autoreleased:\n return false\n }\n }\n\n public var description: String {\n convention.description + ": "\n + String(taking: type.getDebugDescription())\n }\n}\n\nextension FunctionConvention {\n public struct Results : Collection {\n let bridged: BridgedResultInfoArray\n let hasLoweredAddresses: Bool\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int { bridged.count() }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ index: Int) -> ResultInfo {\n return ResultInfo(bridged: bridged.at(index),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n }\n}\n\npublic struct ParameterInfo : CustomStringConvertible {\n /// The parameter type that describes the abstract calling\n /// convention of the parameter.\n public let type: CanonicalType\n public let convention: ArgumentConvention\n public let options: UInt8\n public let hasLoweredAddresses: Bool\n \n // Must be kept consistent with 'SILParameterInfo::Flag'\n public enum Flag : UInt8 {\n case notDifferentiable = 0x1\n case sending = 0x2\n case isolated = 0x4\n case implicitLeading = 0x8\n case const = 0x10\n };\n\n public init(type: CanonicalType, convention: ArgumentConvention, options: UInt8, hasLoweredAddresses: Bool) {\n self.type = type\n self.convention = convention\n self.options = options\n self.hasLoweredAddresses = hasLoweredAddresses\n }\n\n /// Is this parameter passed indirectly in SIL? Most formally\n /// indirect results can be passed directly in SIL (opaque values\n /// mode). This depends on whether the calling function has lowered\n /// addresses.\n public var isSILIndirect: Bool {\n switch convention {\n case .indirectIn, .indirectInGuaranteed:\n return hasLoweredAddresses || type.isExistentialArchetypeWithError\n case .indirectInout, .indirectInoutAliasable, .indirectInCXX:\n return true\n case .directOwned, .directUnowned, .directGuaranteed:\n return false\n case .packInout, .packOwned, .packGuaranteed:\n return true\n case .indirectOut, .packOut:\n fatalError("invalid parameter convention")\n }\n }\n\n public var description: String {\n "\(convention): \(type)"\n }\n \n public func hasOption(_ flag: Flag) -> Bool {\n return options & flag.rawValue != 0\n }\n}\n\nextension FunctionConvention {\n public struct Parameters : RandomAccessCollection {\n let bridged: BridgedParameterInfoArray\n let hasLoweredAddresses: Bool\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int { bridged.count() }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ index: Int) -> ParameterInfo {\n return ParameterInfo(bridged: bridged.at(index),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n }\n}\n\nextension FunctionConvention {\n public struct Yields : Collection {\n let bridged: BridgedYieldInfoArray\n let hasLoweredAddresses: Bool\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int { bridged.count() }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ index: Int) -> ParameterInfo {\n return ParameterInfo(bridged: bridged.at(index),\n hasLoweredAddresses: hasLoweredAddresses)\n }\n }\n}\n\npublic enum LifetimeDependenceConvention : CustomStringConvertible {\n case inherit\n case scope(addressable: Bool, addressableForDeps: Bool)\n\n public var isScoped: Bool {\n switch self {\n case .inherit:\n return false\n case .scope:\n return true\n }\n }\n\n public func isAddressable(for value: Value) -> Bool {\n switch self {\n case .inherit:\n return false\n case let .scope(addressable, addressableForDeps):\n return addressable || (addressableForDeps && value.type.isAddressableForDeps(in: value.parentFunction))\n }\n }\n\n public var description: String {\n switch self {\n case .inherit:\n return "inherit"\n case .scope:\n return "scope"\n }\n }\n}\n\nextension FunctionConvention {\n // 'targetIndex' is either the parameter index or parameters.count for the function result.\n private func lifetimeDependencies(for targetIndex: Int) -> LifetimeDependencies? {\n let bridgedDependenceInfoArray = SILFunctionType_getLifetimeDependencies(functionType.bridged)\n for infoIndex in 0..<bridgedDependenceInfoArray.count() {\n let bridgedDependenceInfo = bridgedDependenceInfoArray.at(infoIndex)\n if bridgedDependenceInfo.targetIndex == targetIndex {\n return LifetimeDependencies(bridged: bridgedDependenceInfo,\n parameterCount: parameters.count,\n hasSelfParameter: hasSelfParameter)\n }\n }\n return nil\n }\n\n /// Collection of LifetimeDependenceConvention? that parallels parameters.\n public struct LifetimeDependencies : Collection, CustomStringConvertible {\n let bridged: BridgedLifetimeDependenceInfo\n let paramCount: Int\n let hasSelfParam: Bool\n\n init(bridged: BridgedLifetimeDependenceInfo, parameterCount: Int,\n hasSelfParameter: Bool) {\n assert(!bridged.empty())\n self.bridged = bridged\n self.paramCount = parameterCount\n self.hasSelfParam = hasSelfParameter\n }\n\n public var startIndex: Int { 0 }\n\n public var endIndex: Int { paramCount }\n\n public func index(after index: Int) -> Int {\n return index + 1\n }\n\n public subscript(_ index: Int) -> LifetimeDependenceConvention? {\n let inherit = bridged.checkInherit(bridgedIndex(parameterIndex: index))\n let scope = bridged.checkScope(bridgedIndex(parameterIndex: index))\n if inherit {\n assert(!scope, "mutualy exclusive lifetime specifiers")\n return .inherit\n }\n if scope {\n let addressable = bridged.checkAddressable(bridgedIndex(parameterIndex: index))\n let addressableForDeps = bridged.checkConditionallyAddressable(bridgedIndex(parameterIndex: index))\n return .scope(addressable: addressable, addressableForDeps: addressableForDeps)\n }\n return nil\n }\n\n private func bridgedIndex(parameterIndex: Int) -> Int {\n return parameterIndex\n }\n\n public var description: String {\n String(taking: bridged.getDebugDescription()) +\n "\nparamCount: \(paramCount) self: \(hasSelfParam)"\n }\n }\n}\n\npublic enum ResultConvention : CustomStringConvertible {\n /// This result is returned indirectly, i.e. by passing the address of an uninitialized object in memory. The callee is responsible for leaving an initialized object at this address. The callee may assume that the address does not alias any valid object.\n case indirect\n\n /// The caller is responsible for destroying this return value. Its type is non-trivial.\n case owned\n\n /// The caller is not responsible for destroying this return value. Its type may be trivial, or it may simply be offered unsafely. It is valid at the instant of the return, but further operations may invalidate it.\n case unowned\n\n /// The caller is not responsible for destroying this return value. The validity of the return value is dependent on the 'self' parameter, so it may be invalidated if that parameter is released.\n case unownedInnerPointer\n\n /// This value has been (or may have been) returned autoreleased. The caller should make an effort to reclaim the autorelease. The type must be a class or class existential type, and this must be the only return value.\n case autoreleased\n\n /// This value is a pack that is returned indirectly by passing a pack address (which may or may not be further indirected, depending on the pact type). The callee is responsible for leaving an initialized object in each element of the pack.\n case pack\n\n /// Does this result convention require indirect storage? This reflects a FunctionType's conventions, as opposed to the SIL conventions that dictate SILValue types.\n public var isASTIndirect: Bool {\n switch self {\n case .indirect, .pack:\n return true\n default:\n return false\n }\n }\n public var isASTDirect: Bool {\n return !isASTIndirect\n }\n\n public var description: String {\n switch self {\n case .indirect:\n return "indirect"\n case .owned:\n return "owned"\n case .unowned:\n return "unowned"\n case .unownedInnerPointer:\n return "unownedInnerPointer"\n case .autoreleased:\n return "autoreleased"\n case .pack:\n return "pack"\n }\n }\n}\n\n// Bridging utilities\n\nextension ResultInfo {\n init(bridged: BridgedResultInfo, hasLoweredAddresses: Bool) {\n self.type = BridgedASTType(type: bridged.type)\n self.convention = ResultConvention(bridged: bridged.convention)\n self.hasLoweredAddresses = hasLoweredAddresses\n }\n init(bridged: OptionalBridgedResultInfo, hasLoweredAddresses: Bool) {\n self.type = BridgedASTType(type: bridged.type!)\n self.convention = ResultConvention(bridged: bridged.convention)\n self.hasLoweredAddresses = hasLoweredAddresses\n }\n}\n\nextension ResultConvention {\n init(bridged: BridgedResultConvention) {\n switch bridged {\n case .Indirect: self = .indirect\n case .Owned: self = .owned\n case .Unowned: self = .unowned\n case .UnownedInnerPointer: self = .unownedInnerPointer\n case .Autoreleased: self = .autoreleased\n case .Pack: self = .pack\n default:\n fatalError("unsupported result convention")\n }\n }\n}\n\nextension ParameterInfo {\n init(bridged: BridgedParameterInfo, hasLoweredAddresses: Bool) {\n self.type = CanonicalType(bridged: bridged.type)\n self.convention = bridged.convention.convention\n self.options = bridged.options\n self.hasLoweredAddresses = hasLoweredAddresses\n }\n\n public var _bridged: BridgedParameterInfo {\n BridgedParameterInfo(type.bridged, convention.bridged, options)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_FunctionConvention.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_FunctionConvention.swift
Swift
14,915
0.95
0.111111
0.143617
python-kit
972
2025-05-26T02:22:59.848686
MIT
false
3ec5cf34b0949434329ea404bb5a41f4
//===--- GlobalVariable.swift - Defines the GlobalVariable class ----------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\nfinal public class GlobalVariable : CustomStringConvertible, HasShortDescription, Hashable {\n public var varDecl: VarDecl? {\n bridged.getDecl().getAs(VarDecl.self)\n }\n\n public var name: StringRef {\n return StringRef(bridged: bridged.getName())\n }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n\n public var shortDescription: String { name.string }\n\n public var isLet: Bool { bridged.isLet() }\n\n public var linkage: Linkage { bridged.getLinkage().linkage }\n\n /// True, if the linkage of the global variable indicates that it is visible outside the current\n /// compilation unit and therefore not all of its uses are known.\n ///\n /// For example, `public` linkage.\n public var isPossiblyUsedExternally: Bool {\n return bridged.isPossiblyUsedExternally()\n }\n\n /// True, if the linkage of the global indicates that it has a definition outside the\n /// current compilation unit.\n ///\n /// For example, `public_external` linkage.\n public var isDefinedExternally: Bool { linkage.isExternal }\n\n public var staticInitializerInstructions: InstructionList? {\n if let firstStaticInitInst = bridged.getFirstStaticInitInst().instruction {\n return InstructionList(first: firstStaticInitInst)\n }\n return nil\n }\n\n public var staticInitValue: SingleValueInstruction? {\n if let staticInitInsts = staticInitializerInstructions {\n return staticInitInsts.reversed().first! as? SingleValueInstruction\n }\n return nil\n }\n\n /// True if the global's linkage and resilience expansion allow the global\n /// to be initialized statically.\n public var canBeInitializedStatically: Bool {\n return bridged.canBeInitializedStatically()\n }\n\n public var mustBeInitializedStatically: Bool {\n return bridged.mustBeInitializedStatically()\n }\n\n public var isConst: Bool {\n return bridged.isConstValue()\n }\n \n public var sourceLocation: SourceLoc? {\n return SourceLoc(bridged: bridged.getSourceLocation())\n }\n\n public static func ==(lhs: GlobalVariable, rhs: GlobalVariable) -> Bool {\n lhs === rhs\n }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n\n public var bridged: BridgedGlobalVar { BridgedGlobalVar(SwiftObject(self)) }\n}\n\n// Bridging utilities\n\nextension BridgedGlobalVar {\n public var globalVar: GlobalVariable { obj.getAs(GlobalVariable.self) }\n\n public var optional: OptionalBridgedGlobalVar {\n OptionalBridgedGlobalVar(obj: self.obj)\n }\n}\n\nextension OptionalBridgedGlobalVar {\n public var globalVar: GlobalVariable? { obj.getAs(GlobalVariable.self) }\n\n public static var none: OptionalBridgedGlobalVar {\n OptionalBridgedGlobalVar(obj: nil)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_GlobalVariable.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_GlobalVariable.swift
Swift
3,276
0.95
0.082569
0.255814
python-kit
407
2024-05-07T21:26:53.300295
GPL-3.0
false
83fdf80615ed85d21440f809a18cb0b6
//===--- Instruction.swift - Defines the Instruction classes --------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\n//===----------------------------------------------------------------------===//\n// Instruction base classes\n//===----------------------------------------------------------------------===//\n\n@_semantics("arc.immortal")\npublic class Instruction : CustomStringConvertible, Hashable {\n final public var next: Instruction? {\n bridged.getNext().instruction\n }\n\n final public var previous: Instruction? {\n bridged.getPrevious().instruction\n }\n\n final public var parentBlock: BasicBlock {\n bridged.getParent().block\n }\n\n final public var parentFunction: Function { parentBlock.parentFunction }\n\n final public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n\n final public var isDeleted: Bool {\n return bridged.isDeleted()\n }\n\n final public var isInStaticInitializer: Bool { bridged.isInStaticInitializer() }\n\n final public var operands: OperandArray {\n let operands = bridged.getOperands()\n return OperandArray(base: operands.base, count: operands.count)\n }\n\n // All operands defined by the operation.\n // Returns the prefix of `operands` that does not include trailing type dependent operands.\n final public var definedOperands: OperandArray {\n let allOperands = operands\n let typeOperands = bridged.getTypeDependentOperands()\n return allOperands[0 ..< (allOperands.count - typeOperands.count)]\n }\n\n final public var typeDependentOperands: OperandArray {\n let allOperands = operands\n let typeOperands = bridged.getTypeDependentOperands()\n return allOperands[(allOperands.count - typeOperands.count) ..< allOperands.count]\n }\n\n fileprivate var resultCount: Int { 0 }\n fileprivate func getResult(index: Int) -> Value { fatalError() }\n\n public struct Results : RandomAccessCollection {\n fileprivate let inst: Instruction\n fileprivate let numResults: Int\n\n public var startIndex: Int { 0 }\n public var endIndex: Int { numResults }\n public subscript(_ index: Int) -> Value { inst.getResult(index: index) }\n }\n\n final public var results: Results {\n Results(inst: self, numResults: resultCount)\n }\n\n final public var location: Location {\n return Location(bridged: bridged.getLocation())\n }\n\n public var mayTrap: Bool { false }\n\n final public var mayHaveSideEffects: Bool {\n return mayTrap || mayWriteToMemory\n }\n\n final public var memoryEffects: SideEffects.Memory {\n switch bridged.getMemBehavior() {\n case .None:\n return SideEffects.Memory()\n case .MayRead:\n return SideEffects.Memory(read: true)\n case .MayWrite:\n return SideEffects.Memory(write: true)\n case .MayReadWrite, .MayHaveSideEffects:\n return SideEffects.Memory(read: true, write: true)\n default:\n fatalError("invalid memory behavior")\n }\n }\n\n final public var mayReadFromMemory: Bool { memoryEffects.read }\n final public var mayWriteToMemory: Bool { memoryEffects.write }\n final public var mayReadOrWriteMemory: Bool { memoryEffects.read || memoryEffects.write }\n\n public final var maySuspend: Bool {\n return bridged.maySuspend()\n }\n\n public final var mayRelease: Bool {\n return bridged.mayRelease()\n }\n\n public final var hasUnspecifiedSideEffects: Bool {\n return bridged.mayHaveSideEffects()\n }\n\n public final var mayAccessPointer: Bool {\n return bridged.mayAccessPointer()\n }\n\n public final var mayLoadWeakOrUnowned: Bool {\n return bridged.mayLoadWeakOrUnowned()\n }\n\n public final var maySynchronize: Bool {\n return bridged.maySynchronize()\n }\n\n public final var mayBeDeinitBarrierNotConsideringSideEffects: Bool {\n return bridged.mayBeDeinitBarrierNotConsideringSideEffects()\n }\n\n public final var isEndOfScopeMarker: Bool {\n switch self {\n case is EndAccessInst, is EndBorrowInst:\n return true;\n default:\n return false;\n }\n }\n\n /// Incidental uses are marker instructions that do not propagate\n /// their operand.\n public final var isIncidentalUse: Bool {\n switch self {\n case is DebugValueInst, is FixLifetimeInst, is EndLifetimeInst,\n is IgnoredUseInst:\n return true\n default:\n return isEndOfScopeMarker\n }\n }\n\n public func visitReferencedFunctions(_ cl: (Function) -> ()) {\n }\n\n public static func ==(lhs: Instruction, rhs: Instruction) -> Bool {\n lhs === rhs\n }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n\n public var bridged: BridgedInstruction {\n BridgedInstruction(SwiftObject(self))\n }\n}\n\nextension BridgedInstruction {\n public var instruction: Instruction { obj.getAs(Instruction.self) }\n public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) }\n public var optional: OptionalBridgedInstruction {\n OptionalBridgedInstruction(self.obj)\n }\n}\n\nextension OptionalBridgedInstruction {\n public var instruction: Instruction? { obj.getAs(Instruction.self) }\n\n public static var none: OptionalBridgedInstruction {\n OptionalBridgedInstruction()\n }\n}\n\nextension Optional where Wrapped == Instruction {\n public var bridged: OptionalBridgedInstruction {\n OptionalBridgedInstruction(self?.bridged.obj)\n }\n}\n\npublic class SingleValueInstruction : Instruction, Value {\n final public var definingInstruction: Instruction? { self }\n\n fileprivate final override var resultCount: Int { 1 }\n fileprivate final override func getResult(index: Int) -> Value { self }\n\n public static func ==(lhs: SingleValueInstruction, rhs: SingleValueInstruction) -> Bool {\n lhs === rhs\n }\n\n public var isLexical: Bool { false }\n}\n\npublic final class MultipleValueInstructionResult : Value, Hashable {\n public var parentInstruction: MultipleValueInstruction {\n bridged.getParent().getAs(MultipleValueInstruction.self)\n }\n\n public var definingInstruction: Instruction? { parentInstruction }\n\n public var parentBlock: BasicBlock { parentInstruction.parentBlock }\n\n public var isLexical: Bool { false }\n\n public var index: Int { bridged.getIndex() }\n\n var bridged: BridgedMultiValueResult {\n BridgedMultiValueResult(obj: SwiftObject(self))\n }\n\n public static func ==(lhs: MultipleValueInstructionResult, rhs: MultipleValueInstructionResult) -> Bool {\n lhs === rhs\n }\n\n public func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nextension BridgedMultiValueResult {\n var result: MultipleValueInstructionResult {\n obj.getAs(MultipleValueInstructionResult.self)\n }\n}\n\npublic class MultipleValueInstruction : Instruction {\n fileprivate final override var resultCount: Int {\n bridged.MultipleValueInstruction_getNumResults()\n }\n fileprivate final override func getResult(index: Int) -> Value {\n bridged.MultipleValueInstruction_getResult(index).result\n }\n}\n\n/// Instructions, which have a single operand (not including type-dependent operands).\npublic protocol UnaryInstruction : Instruction {\n var operand: Operand { get }\n}\n\nextension UnaryInstruction {\n public var operand: Operand { operands[0] }\n}\n\n//===----------------------------------------------------------------------===//\n// no-value instructions\n//===----------------------------------------------------------------------===//\n\n/// Only one of the operands may have an address type.\npublic protocol StoringInstruction : Instruction {\n var operands: OperandArray { get }\n}\n\nextension StoringInstruction {\n public var sourceOperand: Operand { return operands[0] }\n public var destinationOperand: Operand { return operands[1] }\n public var source: Value { return sourceOperand.value }\n public var destination: Value { return destinationOperand.value }\n}\n\nfinal public class StoreInst : Instruction, StoringInstruction {\n // must match with enum class StoreOwnershipQualifier\n public enum StoreOwnership: Int {\n case unqualified = 0, initialize = 1, assign = 2, trivial = 3\n\n public init(for type: Type, in function: Function, initialize: Bool) {\n if function.hasOwnership {\n if type.isTrivial(in: function) {\n self = .trivial\n } else {\n self = initialize ? .initialize : .assign\n }\n } else {\n self = .unqualified\n }\n }\n }\n public var storeOwnership: StoreOwnership {\n StoreOwnership(rawValue: bridged.StoreInst_getStoreOwnership())!\n }\n}\n\nfinal public class StoreWeakInst : Instruction, StoringInstruction { }\nfinal public class StoreUnownedInst : Instruction, StoringInstruction { }\n\nfinal public class AssignInst : Instruction, StoringInstruction {\n // must match with enum class swift::AssignOwnershipQualifier\n public enum AssignOwnership: Int {\n case unknown = 0, reassign = 1, reinitialize = 2, initialize = 3\n }\n\n public var assignOwnership: AssignOwnership {\n AssignOwnership(rawValue: bridged.AssignInst_getAssignOwnership())!\n }\n}\n\nfinal public class AssignByWrapperInst : Instruction, StoringInstruction {}\n\nfinal public class AssignOrInitInst : Instruction, StoringInstruction {}\n\n/// Instruction that copy or move from a source to destination address.\npublic protocol SourceDestAddrInstruction : Instruction {\n var sourceOperand: Operand { get }\n var destinationOperand: Operand { get }\n var isTakeOfSrc: Bool { get }\n var isInitializationOfDest: Bool { get }\n}\n\nextension SourceDestAddrInstruction {\n public var sourceOperand: Operand { operands[0] }\n public var destinationOperand: Operand { operands[1] }\n public var source: Value { sourceOperand.value }\n public var destination: Value { destinationOperand.value }\n}\n\nfinal public class CopyAddrInst : Instruction, SourceDestAddrInstruction {\n public var isTakeOfSrc: Bool {\n bridged.CopyAddrInst_isTakeOfSrc()\n }\n public var isInitializationOfDest: Bool {\n bridged.CopyAddrInst_isInitializationOfDest()\n }\n}\n\nfinal public class ExplicitCopyAddrInst : Instruction, SourceDestAddrInstruction {\n public var source: Value { return sourceOperand.value }\n public var destination: Value { return destinationOperand.value }\n\n public var isTakeOfSrc: Bool {\n bridged.ExplicitCopyAddrInst_isTakeOfSrc()\n }\n public var isInitializationOfDest: Bool {\n bridged.ExplicitCopyAddrInst_isInitializationOfDest()\n }\n}\n\nfinal public class MarkUninitializedInst : SingleValueInstruction, UnaryInstruction {\n\n /// This enum captures what the mark_uninitialized instruction is designating.\n ///\n // Warning: this enum must be in sync with MarkUninitializedInst::Kind\n public enum Kind: Int {\n /// The start of a normal variable live range.\n case variable = 0\n\n /// "self" in a struct, enum, or root class.\n case rootSelf = 1\n\n /// The same as "RootSelf", but in a case where it's not really safe to treat 'self' as root\n /// because the original module might add more stored properties.\n ///\n /// This is only used for Swift 4 compatibility. In Swift 5, cross-module initializers are always delegatingSelf.\n case crossModuleRootSelf = 2\n\n /// "self" in a derived (non-root) class.\n case derivedSelf = 3\n\n /// "self" in a derived (non-root) class whose stored properties have already been initialized.\n case derivedSelfOnly = 4\n\n /// "self" on a struct, enum, or class in a delegating constructor (one that calls self.init).\n case delegatingSelf = 5\n\n /// "self" in a delegating class initializer where memory has already been allocated.\n case delegatingSelfAllocated = 6\n\n /// An indirectly returned result which has to be checked for initialization.\n case indirectResult = 7\n }\n\n public var kind: Kind { Kind(rawValue: bridged.MarkUninitializedInst_getKind())! }\n}\n\nfinal public class CondFailInst : Instruction, UnaryInstruction {\n public var condition: Value { operand.value }\n public override var mayTrap: Bool { true }\n\n public var message: StringRef { StringRef(bridged: bridged.CondFailInst_getMessage()) }\n}\n\nfinal public class IncrementProfilerCounterInst : Instruction {}\n\nfinal public class MarkFunctionEscapeInst : Instruction {}\n\nfinal public class HopToExecutorInst : Instruction, UnaryInstruction {}\n\nfinal public class FixLifetimeInst : Instruction, UnaryInstruction {}\n\n// See C++ VarDeclCarryingInst\npublic protocol VarDeclInstruction {\n var varDecl: VarDecl? { get }\n}\n\n/// A scoped instruction whose single result introduces a variable scope.\n///\n/// The scope-ending uses represent the end of the variable scope. This allows trivial 'let' variables to be treated\n/// like a value with ownership. 'var' variables are primarily represented as addressable allocations via alloc_box or\n/// alloc_stack, but may have redundant VariableScopeInstructions.\npublic enum VariableScopeInstruction {\n case beginBorrow(BeginBorrowInst)\n case moveValue(MoveValueInst)\n\n public init?(_ inst: Instruction?) {\n switch inst {\n case let bbi as BeginBorrowInst:\n guard bbi.isFromVarDecl else {\n return nil\n }\n self = .beginBorrow(bbi)\n case let mvi as MoveValueInst:\n guard mvi.isFromVarDecl else {\n return nil\n }\n self = .moveValue(mvi)\n default:\n return nil\n }\n }\n\n public var instruction: Instruction {\n switch self {\n case let .beginBorrow(bbi):\n return bbi\n case let .moveValue(mvi):\n return mvi\n }\n }\n\n public var scopeBegin: Value {\n instruction as! SingleValueInstruction\n }\n\n public var endOperands: LazyFilterSequence<UseList> {\n scopeBegin.uses.lazy.filter { $0.endsLifetime || $0.instruction is ExtendLifetimeInst }\n }\n\n // TODO: with SIL verification, we might be able to make varDecl non-Optional.\n public var varDecl: VarDecl? {\n if let debugVarDecl = instruction.debugVarDecl {\n return debugVarDecl\n }\n // SILGen may produce double var_decl instructions for the same variable:\n // %box = alloc_box [var_decl] "x"\n // begin_borrow %box [var_decl]\n //\n // Assume that, if the begin_borrow or move_value does not have its own debug_value, then it must actually be\n // associated with its operand's var_decl.\n return instruction.operands[0].value.definingInstruction?.findVarDecl()\n }\n}\n\nextension Instruction {\n /// Find a variable declaration assoicated with this instruction.\n public func findVarDecl() -> VarDecl? {\n if let varDeclInst = self as? VarDeclInstruction {\n return varDeclInst.varDecl\n }\n if let varScopeInst = VariableScopeInstruction(self) {\n return varScopeInst.varDecl\n }\n return debugVarDecl\n }\n\n var debugVarDecl: VarDecl? {\n for result in results {\n for use in result.uses {\n if let debugVal = use.instruction as? DebugValueInst {\n return debugVal.varDecl\n }\n }\n }\n return nil\n }\n}\n\npublic protocol DebugVariableInstruction : VarDeclInstruction {\n typealias DebugVariable = BridgedSILDebugVariable\n\n var debugVariable: DebugVariable? { get }\n}\n\n/// A meta instruction is an instruction whose location is not interesting as\n/// it is impossible to set a breakpoint on it.\n/// That could be because the instruction does not generate code (such as\n/// `debug_value`), or because the generated code would be in the prologue\n/// (`alloc_stack`).\n/// When we are moving code onto an unknown instruction (such as the start of a\n/// basic block), we want to ignore any meta instruction that might be there.\npublic protocol MetaInstruction: Instruction {}\n\nfinal public class DebugValueInst : Instruction, UnaryInstruction, DebugVariableInstruction, MetaInstruction {\n public var varDecl: VarDecl? {\n bridged.DebugValue_getDecl().getAs(VarDecl.self)\n }\n\n public var debugVariable: DebugVariable? {\n return bridged.DebugValue_hasVarInfo() ? bridged.DebugValue_getVarInfo() : nil\n }\n}\n\nfinal public class DebugStepInst : Instruction {}\n\nfinal public class SpecifyTestInst : Instruction {}\n\nfinal public class UnconditionalCheckedCastAddrInst : Instruction, SourceDestAddrInstruction {\n public var sourceFormalType: CanonicalType {\n CanonicalType(bridged: bridged.UnconditionalCheckedCastAddr_getSourceFormalType())\n }\n public var targetFormalType: CanonicalType {\n CanonicalType(bridged: bridged.UnconditionalCheckedCastAddr_getTargetFormalType())\n }\n\n public var isTakeOfSrc: Bool { true }\n public var isInitializationOfDest: Bool { true }\n public override var mayTrap: Bool { true }\n\n public var isolatedConformances: CastingIsolatedConformances {\n switch bridged.UnconditionalCheckedCastAddr_getIsolatedConformances() {\n case .Allow: .allow\n case .Prohibit: .prohibit\n @unknown default: fatalError("Unhandled CastingIsolatedConformances")\n }\n }\n}\n\nfinal public class BeginDeallocRefInst : SingleValueInstruction, UnaryInstruction {\n public var reference: Value { operands[0].value }\n public var allocation: AllocRefInstBase { operands[1].value as! AllocRefInstBase }\n}\n\nfinal public class EndInitLetRefInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class BindMemoryInst : SingleValueInstruction {}\nfinal public class RebindMemoryInst : SingleValueInstruction {}\n\npublic class RefCountingInst : Instruction, UnaryInstruction {\n public var isAtomic: Bool { bridged.RefCountingInst_getIsAtomic() }\n}\n\nfinal public class StrongRetainInst : RefCountingInst {\n public var instance: Value { operand.value }\n}\n\nfinal public class StrongRetainUnownedInst : RefCountingInst {}\n\nfinal public class UnownedRetainInst : RefCountingInst {\n public var instance: Value { operand.value }\n}\n\nfinal public class RetainValueInst : RefCountingInst {\n public var value: Value { return operand.value }\n}\n\nfinal public class UnmanagedRetainValueInst : RefCountingInst {\n public var value: Value { return operand.value }\n}\n\nfinal public class RetainValueAddrInst : RefCountingInst {\n}\n\nfinal public class ReleaseValueAddrInst : RefCountingInst {\n}\n\nfinal public class StrongReleaseInst : RefCountingInst {\n public var instance: Value { operand.value }\n}\n\nfinal public class UnownedReleaseInst : RefCountingInst {\n public var instance: Value { operand.value }\n}\n\nfinal public class ReleaseValueInst : RefCountingInst {\n public var value: Value { return operand.value }\n}\n\nfinal public class UnmanagedReleaseValueInst : RefCountingInst {\n public var value: Value { return operand.value }\n}\n\nfinal public class AutoreleaseValueInst : RefCountingInst {}\nfinal public class UnmanagedAutoreleaseValueInst : RefCountingInst {}\n\nfinal public class DestroyValueInst : Instruction, UnaryInstruction {\n public var destroyedValue: Value { operand.value }\n\n /// True if this `destroy_value` is inside a dead-end block is only needed to formally\n /// end the lifetime of its operand.\n /// Such `destroy_value` instructions are lowered to no-ops.\n public var isDeadEnd: Bool { bridged.DestroyValueInst_isDeadEnd() }\n}\n\nfinal public class DestroyAddrInst : Instruction, UnaryInstruction {\n public var destroyedAddress: Value { operand.value }\n}\n\nfinal public class EndLifetimeInst : Instruction, UnaryInstruction {}\n\nfinal public class ExtendLifetimeInst : Instruction, UnaryInstruction {}\n\nfinal public class InjectEnumAddrInst : Instruction, UnaryInstruction, EnumInstruction {\n public var `enum`: Value { operand.value }\n public var caseIndex: Int { bridged.InjectEnumAddrInst_caseIndex() }\n}\n\n//===----------------------------------------------------------------------===//\n// no-value deallocation instructions\n//===----------------------------------------------------------------------===//\n\npublic protocol Deallocation : Instruction {\n var allocatedValue: Value { get }\n}\n\nextension Deallocation {\n public var allocatedValue: Value { operands[0].value }\n}\n\n\nfinal public class DeallocStackInst : Instruction, UnaryInstruction, Deallocation {\n public var allocstack: AllocStackInst {\n return operand.value as! AllocStackInst\n }\n}\n\nfinal public class DeallocStackRefInst : Instruction, UnaryInstruction, Deallocation {\n public var allocRef: AllocRefInstBase { operand.value as! AllocRefInstBase }\n}\n\nfinal public class DeallocRefInst : Instruction, UnaryInstruction, Deallocation {}\n\nfinal public class DeallocPartialRefInst : Instruction, Deallocation {}\n\nfinal public class DeallocBoxInst : Instruction, UnaryInstruction, Deallocation {}\n\nfinal public class DeallocExistentialBoxInst : Instruction, UnaryInstruction, Deallocation {}\n\n//===----------------------------------------------------------------------===//\n// single-value instructions\n//===----------------------------------------------------------------------===//\n\npublic protocol LoadInstruction: SingleValueInstruction, UnaryInstruction {}\n\nextension LoadInstruction {\n public var address: Value { operand.value }\n}\n\nfinal public class LoadInst : SingleValueInstruction, LoadInstruction {\n // must match with enum class LoadOwnershipQualifier\n public enum LoadOwnership: Int {\n case unqualified = 0, take = 1, copy = 2, trivial = 3\n }\n public var loadOwnership: LoadOwnership {\n LoadOwnership(rawValue: bridged.LoadInst_getLoadOwnership())!\n }\n}\n\nfinal public class LoadWeakInst : SingleValueInstruction, LoadInstruction {}\nfinal public class LoadUnownedInst : SingleValueInstruction, LoadInstruction {}\n\nfinal public class BuiltinInst : SingleValueInstruction {\n public typealias ID = BridgedInstruction.BuiltinValueKind\n\n public var id: ID {\n return bridged.BuiltinInst_getID()\n }\n\n public var name: StringRef {\n return StringRef(bridged: bridged.BuiltinInst_getName())\n }\n\n public var intrinsicID: BridgedInstruction.IntrinsicID {\n return bridged.BuiltinInst_getIntrinsicID()\n }\n\n public var substitutionMap: SubstitutionMap {\n SubstitutionMap(bridged: bridged.BuiltinInst_getSubstitutionMap())\n }\n\n public var arguments: LazyMapSequence<OperandArray, Value> {\n operands.values\n }\n}\n\nfinal public class UpcastInst : SingleValueInstruction, UnaryInstruction {\n public var fromInstance: Value { operand.value }\n}\n\nfinal public\nclass UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {\n public var fromInstance: Value { operand.value }\n}\n\nfinal public\nclass UncheckedRefCastAddrInst : Instruction, SourceDestAddrInstruction {\n public var isTakeOfSrc: Bool { true }\n public var isInitializationOfDest: Bool { true }\n}\n\nfinal public class UncheckedAddrCastInst : SingleValueInstruction, UnaryInstruction {\n public var fromAddress: Value { operand.value }\n}\n\nfinal public class UncheckedTrivialBitCastInst : SingleValueInstruction, UnaryInstruction {\n public var fromValue: Value { operand.value }\n}\n\nfinal public class UncheckedBitwiseCastInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class UncheckedValueCastInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class RefToRawPointerInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class RefToUnmanagedInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class RefToUnownedInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class UnmanagedToRefInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class UnownedToRefInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {\n public var pointer: Value { operand.value }\n}\n\nfinal public\nclass AddressToPointerInst : SingleValueInstruction, UnaryInstruction {\n public var address: Value { operand.value }\n\n public var needsStackProtection: Bool {\n bridged.AddressToPointerInst_needsStackProtection()\n }\n}\n\nfinal public\nclass PointerToAddressInst : SingleValueInstruction, UnaryInstruction {\n public var pointer: Value { operand.value }\n public var isStrict: Bool { bridged.PointerToAddressInst_isStrict() }\n public var isInvariant: Bool { bridged.PointerToAddressInst_isInvariant() }\n\n public var alignment: Int? {\n let maybeAlign = bridged.PointerToAddressInst_getAlignment()\n if maybeAlign == 0 {\n return nil\n }\n return Int(exactly: maybeAlign)\n }\n}\n\npublic protocol IndexingInstruction: SingleValueInstruction {\n var base: Value { get }\n var index: Value { get }\n}\n\nextension IndexingInstruction {\n public var base: Value { operands[0].value }\n public var index: Value { operands[1].value }\n}\n\nfinal public\nclass IndexAddrInst : SingleValueInstruction, IndexingInstruction {\n public var needsStackProtection: Bool {\n bridged.IndexAddrInst_needsStackProtection()\n }\n}\n\nfinal public class IndexRawPointerInst : SingleValueInstruction, IndexingInstruction {}\n\nfinal public\nclass TailAddrInst : SingleValueInstruction, IndexingInstruction {}\n\nfinal public\nclass InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {\n public var instance: Value { operand.value }\n\n public var conformances: ConformanceArray {\n ConformanceArray(bridged: bridged.InitExistentialRefInst_getConformances())\n }\n\n public var formalConcreteType: CanonicalType {\n CanonicalType(bridged: bridged.InitExistentialRefInst_getFormalConcreteType())\n }\n}\n\nfinal public\nclass OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {\n public var existential: Value { operand.value }\n}\n\nfinal public\nclass InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass DeinitExistentialAddrInst : Instruction, UnaryInstruction {}\n\nfinal public\nclass DeinitExistentialValueInst : Instruction {}\n\nfinal public\nclass OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {\n public var metatype: Value { operand.value }\n}\n\nfinal public\nclass OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MetatypeInst : SingleValueInstruction {}\n\nfinal public\nclass ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class ObjCProtocolInst : SingleValueInstruction {}\n\nfinal public class TypeValueInst: SingleValueInstruction, UnaryInstruction {\n public var paramType: CanonicalType {\n CanonicalType(bridged: bridged.TypeValueInst_getParamType())\n }\n\n public var value: Int {\n bridged.TypeValueInst_getValue()\n }\n}\n\npublic class GlobalAccessInstruction : SingleValueInstruction {\n final public var global: GlobalVariable {\n bridged.GlobalAccessInst_getGlobal().globalVar\n }\n}\n\npublic class FunctionRefBaseInst : SingleValueInstruction {\n public var referencedFunction: Function {\n bridged.FunctionRefBaseInst_getReferencedFunction().function\n }\n\n public override func visitReferencedFunctions(_ cl: (Function) -> ()) {\n cl(referencedFunction)\n }\n}\n\nfinal public class FunctionRefInst : FunctionRefBaseInst {\n}\n\nfinal public class DynamicFunctionRefInst : FunctionRefBaseInst {\n}\n\nfinal public class PreviousDynamicFunctionRefInst : FunctionRefBaseInst {\n}\n\nfinal public class GlobalAddrInst : GlobalAccessInstruction, VarDeclInstruction {\n public var varDecl: VarDecl? {\n bridged.GlobalAddr_getDecl().getAs(VarDecl.self)\n }\n\n public var dependencyToken: Value? {\n operands.count == 1 ? operands[0].value : nil\n }\n}\n\nfinal public class GlobalValueInst : GlobalAccessInstruction {\n public var isBare: Bool { bridged.GlobalValueInst_isBare() }\n}\n\nfinal public class BaseAddrForOffsetInst : SingleValueInstruction {}\n\nfinal public class AllocGlobalInst : Instruction {\n public var global: GlobalVariable {\n bridged.AllocGlobalInst_getGlobal().globalVar\n }\n}\n\nfinal public class IntegerLiteralInst : SingleValueInstruction {\n public var value: Int? {\n let optionalInt = bridged.IntegerLiteralInst_getValue()\n if optionalInt.hasValue {\n return optionalInt.value\n }\n return nil\n }\n}\n\nfinal public class FloatLiteralInst : SingleValueInstruction {\n}\n\nfinal public class StringLiteralInst : SingleValueInstruction {\n public enum Encoding {\n case Bytes\n case UTF8\n /// UTF-8 encoding of an Objective-C selector.\n case ObjCSelector\n case UTF8_OSLOG\n }\n\n public var value: StringRef { StringRef(bridged: bridged.StringLiteralInst_getValue()) }\n\n public var encoding: Encoding {\n switch bridged.StringLiteralInst_getEncoding() {\n case 0: return .Bytes\n case 1: return .UTF8\n case 2: return .ObjCSelector\n case 3: return .UTF8_OSLOG\n default: fatalError("invalid encoding in StringLiteralInst")\n }\n }\n}\n\nfinal public class HasSymbolInst : SingleValueInstruction {}\n\nfinal public class TupleInst : SingleValueInstruction {}\n\nfinal public class TupleExtractInst : SingleValueInstruction, UnaryInstruction {\n public var `tuple`: Value { operand.value }\n public var fieldIndex: Int { bridged.TupleExtractInst_fieldIndex() }\n}\n\nfinal public\nclass TupleElementAddrInst : SingleValueInstruction, UnaryInstruction {\n public var `tuple`: Value { operand.value }\n public var fieldIndex: Int { bridged.TupleElementAddrInst_fieldIndex() }\n}\n\nfinal public class TupleAddrConstructorInst : Instruction {\n public var destinationOperand: Operand { operands[0] }\n}\n\nfinal public class StructInst : SingleValueInstruction {\n}\n\nfinal public class StructExtractInst : SingleValueInstruction, UnaryInstruction {\n public var `struct`: Value { operand.value }\n public var fieldIndex: Int { bridged.StructExtractInst_fieldIndex() }\n}\n\nfinal public\nclass StructElementAddrInst : SingleValueInstruction, UnaryInstruction {\n public var `struct`: Value { operand.value }\n public var fieldIndex: Int { bridged.StructElementAddrInst_fieldIndex() }\n}\n\npublic protocol EnumInstruction : AnyObject {\n var caseIndex: Int { get }\n}\n\nfinal public class EnumInst : SingleValueInstruction, EnumInstruction {\n public var caseIndex: Int { bridged.EnumInst_caseIndex() }\n\n public var operand: Operand? { operands.first }\n public var payload: Value? { operand?.value }\n}\n\nfinal public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {\n public var `enum`: Value { operand.value }\n public var caseIndex: Int { bridged.UncheckedEnumDataInst_caseIndex() }\n}\n\nfinal public class InitEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {\n public var `enum`: Value { operand.value }\n public var caseIndex: Int { bridged.InitEnumDataAddrInst_caseIndex() }\n}\n\nfinal public class UncheckedTakeEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {\n public var `enum`: Value { operand.value }\n public var caseIndex: Int { bridged.UncheckedTakeEnumDataAddrInst_caseIndex() }\n}\n\nfinal public class SelectEnumInst : SingleValueInstruction {\n public var enumOperand: Operand { operands[0] }\n}\n\nfinal public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction, VarDeclInstruction {\n public var instance: Value { operand.value }\n public var fieldIndex: Int { bridged.RefElementAddrInst_fieldIndex() }\n\n public var fieldIsLet: Bool { bridged.RefElementAddrInst_fieldIsLet() }\n\n public var isImmutable: Bool { bridged.RefElementAddrInst_isImmutable() }\n \n public var varDecl: VarDecl? {\n bridged.RefElementAddr_getDecl().getAs(VarDecl.self)\n }\n}\n\nfinal public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {\n public var instance: Value { operand.value }\n\n public var isImmutable: Bool { bridged.RefTailAddrInst_isImmutable() }\n}\n\nfinal public class KeyPathInst : SingleValueInstruction {\n public override func visitReferencedFunctions(_ cl: (Function) -> ()) {\n var results = BridgedInstruction.KeyPathFunctionResults()\n for componentIdx in 0..<bridged.KeyPathInst_getNumComponents() {\n bridged.KeyPathInst_getReferencedFunctions(componentIdx, &results)\n let numFuncs = results.numFunctions\n withUnsafePointer(to: &results) {\n $0.withMemoryRebound(to: BridgedFunction.self, capacity: numFuncs) {\n let functions = UnsafeBufferPointer(start: $0, count: numFuncs)\n for idx in 0..<numFuncs {\n cl(functions[idx].function)\n }\n }\n }\n }\n }\n}\n\nfinal public\nclass UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction {\n public override var mayTrap: Bool { true }\n \n public var sourceFormalType: CanonicalType {\n CanonicalType(bridged: bridged.UnconditionalCheckedCast_getSourceFormalType())\n }\n public var targetFormalType: CanonicalType {\n CanonicalType(bridged: bridged.UnconditionalCheckedCast_getTargetFormalType())\n }\n\n public var isolatedConformances: CastingIsolatedConformances {\n switch bridged.UnconditionalCheckedCast_getIsolatedConformances() {\n case .Allow: .allow\n case .Prohibit: .prohibit\n @unknown default: fatalError("Unhandled CastingIsolatedConformances")\n }\n }\n}\n\nfinal public\nclass ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {\n public var fromFunction: Value { operand.value }\n public var withoutActuallyEscaping: Bool { bridged.ConvertFunctionInst_withoutActuallyEscaping() }\n}\n\nfinal public\nclass ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {\n public var callee: Value { operand.value }\n\n public var referencedFunction: Function? {\n if let fri = callee as? FunctionRefInst {\n return fri.referencedFunction\n }\n return nil\n }\n}\n\nfinal public class ThickToObjCMetatypeInst : SingleValueInstruction {}\nfinal public class ObjCToThickMetatypeInst : SingleValueInstruction {}\n\nfinal public class CopyBlockInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class CopyBlockWithoutEscapingInst : SingleValueInstruction {}\n\nfinal public\nclass ConvertEscapeToNoEscapeInst : SingleValueInstruction, UnaryInstruction {\n public var fromFunction: Value { operand.value }\n}\n\nfinal public\nclass ObjCExistentialMetatypeToObjectInst : SingleValueInstruction {}\n\nfinal public\nclass ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public\nclass ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {\n public var value: Value { return operand.value }\n}\n\nfinal public\nclass GetAsyncContinuationInst : SingleValueInstruction {}\n\nfinal public\nclass GetAsyncContinuationAddrInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class ExtractExecutorInst : SingleValueInstruction {}\n\npublic enum MarkDependenceKind: Int32 {\n case Unresolved = 0\n case Escaping = 1\n case NonEscaping = 2\n}\n\npublic protocol MarkDependenceInstruction: Instruction {\n var baseOperand: Operand { get }\n var base: Value { get }\n var dependenceKind: MarkDependenceKind { get }\n func resolveToNonEscaping()\n func settleToEscaping()\n}\n\nextension MarkDependenceInstruction {\n public var isNonEscaping: Bool { dependenceKind == .NonEscaping }\n public var isUnresolved: Bool { dependenceKind == .Unresolved }\n}\n\nfinal public class MarkDependenceInst : SingleValueInstruction, MarkDependenceInstruction {\n public var valueOperand: Operand { operands[0] }\n public var baseOperand: Operand { operands[1] }\n public var value: Value { return valueOperand.value }\n public var base: Value { return baseOperand.value }\n\n public var dependenceKind: MarkDependenceKind {\n MarkDependenceKind(rawValue: bridged.MarkDependenceInst_dependenceKind().rawValue)!\n }\n\n public func resolveToNonEscaping() {\n bridged.MarkDependenceInst_resolveToNonEscaping()\n }\n\n public func settleToEscaping() {\n bridged.MarkDependenceInst_settleToEscaping()\n }\n\n public var hasScopedLifetime: Bool {\n return isNonEscaping && type.isObject && ownership == .owned && type.isEscapable(in: parentFunction)\n }\n}\n\nfinal public class MarkDependenceAddrInst : Instruction, MarkDependenceInstruction {\n public var addressOperand: Operand { operands[0] }\n public var baseOperand: Operand { operands[1] }\n public var address: Value { return addressOperand.value }\n public var base: Value { return baseOperand.value }\n\n public var dependenceKind: MarkDependenceKind {\n MarkDependenceKind(rawValue: bridged.MarkDependenceAddrInst_dependenceKind().rawValue)!\n }\n\n public func resolveToNonEscaping() {\n bridged.MarkDependenceAddrInst_resolveToNonEscaping()\n }\n\n public func settleToEscaping() {\n bridged.MarkDependenceAddrInst_settleToEscaping()\n }\n}\n\nfinal public class RefToBridgeObjectInst : SingleValueInstruction {\n public var convertedOperand: Operand { operands[0] }\n public var maskOperand: Operand { operands[1] }\n}\n\nfinal public class BridgeObjectToRefInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class BridgeObjectToWordInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class BorrowedFromInst : SingleValueInstruction, BorrowIntroducingInstruction {\n public var borrowedValue: Value { operands[0].value }\n public var borrowedPhi: Phi { Phi(borrowedValue)! }\n public var enclosingOperands: OperandArray {\n let ops = operands\n return ops[1..<ops.count]\n }\n public var enclosingValues: LazyMapSequence<LazySequence<OperandArray>.Elements, Value> {\n enclosingOperands.values\n }\n}\n\nfinal public class ProjectBoxInst : SingleValueInstruction, UnaryInstruction {\n public var box: Value { operand.value }\n public var fieldIndex: Int { bridged.ProjectBoxInst_fieldIndex() }\n}\n\nfinal public class ProjectExistentialBoxInst : SingleValueInstruction, UnaryInstruction {}\n\npublic protocol CopyingInstruction : SingleValueInstruction, UnaryInstruction, OwnershipTransitionInstruction {}\n\nfinal public class CopyValueInst : SingleValueInstruction, CopyingInstruction {\n public var fromValue: Value { operand.value }\n}\n\nfinal public class ExplicitCopyValueInst : SingleValueInstruction, CopyingInstruction {\n public var fromValue: Value { operand.value }\n}\n\nfinal public class UnownedCopyValueInst : SingleValueInstruction, CopyingInstruction {}\nfinal public class WeakCopyValueInst : SingleValueInstruction, CopyingInstruction {}\n\nfinal public class UncheckedOwnershipConversionInst : SingleValueInstruction {}\n\nfinal public class MoveValueInst : SingleValueInstruction, UnaryInstruction {\n public var fromValue: Value { operand.value }\n\n public override var isLexical: Bool { bridged.MoveValue_isLexical() }\n public var hasPointerEscape: Bool { bridged.MoveValue_hasPointerEscape() }\n public var isFromVarDecl: Bool { bridged.MoveValue_isFromVarDecl() }\n}\n\nfinal public class DropDeinitInst : SingleValueInstruction, UnaryInstruction {\n public var fromValue: Value { operand.value }\n}\n\nfinal public class StrongCopyUnownedValueInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class StrongCopyUnmanagedValueInst : SingleValueInstruction, UnaryInstruction {}\nfinal public class StrongCopyWeakValueInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {\n public var instance: Value { operand.value }\n public var doKeepUnique: Bool { bridged.EndCOWMutationInst_doKeepUnique() }\n}\n\nfinal public\nclass ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class PartialApplyInst : SingleValueInstruction, ApplySite {\n public var numArguments: Int { bridged.PartialApplyInst_numArguments() }\n\n /// Warning: isOnStack returns false for all closures prior to ClosureLifetimeFixup, even if they capture on-stack\n /// addresses and need to be diagnosed as non-escaping closures. Use mayEscape to determine whether a closure is\n /// non-escaping prior to ClosureLifetimeFixup.\n public var isOnStack: Bool { bridged.PartialApplyInst_isOnStack() }\n\n // Warning: ClosureLifetimeFixup does not promote all non-escaping closures to on-stack. When that promotion fails, it\n // creates a fake destroy of the closure after the captured values that the closure depends on. This is invalid OSSA,\n // so OSSA utilities need to bail-out when isOnStack is false even if hasNoescapeCapture is true to avoid encoutering\n // an invalid nested lifetime.\n public var mayEscape: Bool { !isOnStack && !hasNoescapeCapture }\n\n /// True if this closure captures anything nonescaping.\n public var hasNoescapeCapture: Bool {\n if operandConventions.contains(.indirectInoutAliasable) {\n return true\n }\n return arguments.contains { $0.type.containsNoEscapeFunction }\n }\n\n public var hasUnknownResultIsolation: Bool { bridged.PartialApplyInst_hasUnknownResultIsolation() }\n public var unappliedArgumentCount: Int { bridged.PartialApply_getCalleeArgIndexOfFirstAppliedArg() }\n public var calleeConvention: ArgumentConvention { type.bridged.getCalleeConvention().convention }\n}\n\nfinal public class ApplyInst : SingleValueInstruction, FullApplySite {\n public var numArguments: Int { bridged.ApplyInst_numArguments() }\n\n public var singleDirectResult: Value? { self }\n public var singleDirectErrorResult: Value? { nil }\n\n public var isNonThrowing: Bool { bridged.ApplyInst_getNonThrowing() }\n public var isNonAsync: Bool { bridged.ApplyInst_getNonAsync() }\n\n public typealias SpecializationInfo = BridgedGenericSpecializationInformation\n\n public var specializationInfo: SpecializationInfo { bridged.ApplyInst_getSpecializationInfo() }\n}\n\nfinal public class FunctionExtractIsolationInst : SingleValueInstruction {}\n\nfinal public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {\n public var member: DeclRef { DeclRef(bridged: bridged.ClassMethodInst_getMember()) }\n}\n\nfinal public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class WitnessMethodInst : SingleValueInstruction {\n public var member: DeclRef { DeclRef(bridged: bridged.WitnessMethodInst_getMember()) }\n public var lookupType: CanonicalType { CanonicalType(bridged: bridged.WitnessMethodInst_getLookupType()) }\n public var lookupProtocol: ProtocolDecl { bridged.WitnessMethodInst_getLookupProtocol().getAs(ProtocolDecl.self) }\n public var conformance: Conformance { Conformance(bridged: bridged.WitnessMethodInst_getConformance()) }\n}\n\nfinal public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class DestroyNotEscapedClosureInst : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MarkUnresolvedNonCopyableValueInst: SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MarkUnresolvedReferenceBindingInst : SingleValueInstruction {}\n\nfinal public class MarkUnresolvedMoveAddrInst : Instruction, SourceDestAddrInstruction {\n public var isTakeOfSrc: Bool { true }\n public var isInitializationOfDest: Bool { true }\n}\n\nfinal public class CopyableToMoveOnlyWrapperValueInst: SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MoveOnlyWrapperToCopyableValueInst: SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MoveOnlyWrapperToCopyableBoxInst: SingleValueInstruction, UnaryInstruction {}\n\nfinal public class CopyableToMoveOnlyWrapperAddrInst\n : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class MoveOnlyWrapperToCopyableAddrInst\n : SingleValueInstruction, UnaryInstruction {}\n\nfinal public class ObjectInst : SingleValueInstruction {\n public var baseOperands: OperandArray {\n operands[0..<bridged.ObjectInst_getNumBaseElements()]\n }\n\n public var tailOperands: OperandArray {\n let ops = operands\n return ops[bridged.ObjectInst_getNumBaseElements()..<ops.endIndex]\n }\n}\n\nfinal public class VectorInst : SingleValueInstruction {\n}\n\nfinal public class DifferentiableFunctionInst: SingleValueInstruction {}\n\nfinal public class LinearFunctionInst: SingleValueInstruction {}\nfinal public class DifferentiableFunctionExtractInst: SingleValueInstruction {}\nfinal public class LinearFunctionExtractInst: SingleValueInstruction {}\nfinal public class DifferentiabilityWitnessFunctionInst: SingleValueInstruction {}\n\nfinal public class ProjectBlockStorageInst: SingleValueInstruction, UnaryInstruction {}\n\nfinal public class InitBlockStorageHeaderInst: SingleValueInstruction {}\n\n//===----------------------------------------------------------------------===//\n// single-value allocation instructions\n//===----------------------------------------------------------------------===//\n\npublic protocol Allocation : SingleValueInstruction { }\n\nfinal public class AllocStackInst : SingleValueInstruction, Allocation, DebugVariableInstruction, MetaInstruction {\n public var hasDynamicLifetime: Bool { bridged.AllocStackInst_hasDynamicLifetime() }\n public var isFromVarDecl: Bool { bridged.AllocStackInst_isFromVarDecl() }\n public var usesMoveableValueDebugInfo: Bool { bridged.AllocStackInst_usesMoveableValueDebugInfo() }\n public override var isLexical: Bool { bridged.AllocStackInst_isLexical() }\n\n public var varDecl: VarDecl? {\n bridged.AllocStack_getDecl().getAs(VarDecl.self)\n }\n\n public var debugVariable: DebugVariable? {\n return bridged.AllocStack_hasVarInfo() ? bridged.AllocStack_getVarInfo() : nil\n }\n\n public var deallocations: LazyMapSequence<LazyFilterSequence<UseList>, Instruction> {\n uses.users(ofType: DeallocStackInst.self)\n }\n}\n\npublic class AllocRefInstBase : SingleValueInstruction, Allocation {\n final public var isObjC: Bool { bridged.AllocRefInstBase_isObjc() }\n\n final public var canAllocOnStack: Bool {\n bridged.AllocRefInstBase_canAllocOnStack()\n }\n\n final public var tailAllocatedCounts: OperandArray {\n let numTailTypes = bridged.AllocRefInstBase_getNumTailTypes()\n return operands[0..<numTailTypes]\n }\n\n final public var tailAllocatedTypes: TypeArray {\n TypeArray(bridged: bridged.AllocRefInstBase_getTailAllocatedTypes())\n }\n}\n\nfinal public class AllocRefInst : AllocRefInstBase {\n public var isBare: Bool { bridged.AllocRefInst_isBare() }\n}\n\nfinal public class AllocRefDynamicInst : AllocRefInstBase {\n public var isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType: Bool {\n bridged.AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType()\n }\n\n public var metatypeOperand: Operand {\n let numTailTypes = bridged.AllocRefInstBase_getNumTailTypes()\n return operands[numTailTypes]\n }\n}\n\nfinal public class AllocBoxInst : SingleValueInstruction, Allocation, DebugVariableInstruction {\n\n public var varDecl: VarDecl? {\n bridged.AllocBox_getDecl().getAs(VarDecl.self)\n }\n\n public var debugVariable: DebugVariable? {\n return bridged.AllocBox_hasVarInfo() ? bridged.AllocBox_getVarInfo() : nil\n }\n}\n\nfinal public class AllocExistentialBoxInst : SingleValueInstruction, Allocation {\n}\n\n//===----------------------------------------------------------------------===//\n// scoped instructions\n//===----------------------------------------------------------------------===//\n\n/// An instruction whose side effects extend across a scope including other instructions. These are always paired with a\n/// scope ending instruction such as `begin_access` (ending with `end_access`) and `begin_borrow` (ending with\n/// `end_borrow`).\npublic protocol ScopedInstruction {\n var instruction: Instruction { get }\n\n var endOperands: LazyFilterSequence<UseList> { get }\n\n var endInstructions: EndInstructions { get }\n}\n\nextension Instruction {\n /// Return the sequence of use points of any instruction.\n public var endInstructions: EndInstructions {\n if let scopedInst = self as? ScopedInstruction {\n return .scoped(scopedInst.endOperands.users)\n }\n return .single(self)\n }\n}\n\n/// Instructions beginning a borrow-scope which must be ended by `end_borrow`.\npublic protocol BorrowIntroducingInstruction : SingleValueInstruction, ScopedInstruction {\n}\n\nextension BorrowIntroducingInstruction {\n public var instruction: Instruction { get { self } }\n}\n\nfinal public class EndBorrowInst : Instruction, UnaryInstruction {\n public var borrow: Value { operand.value }\n}\n\nextension BorrowIntroducingInstruction {\n public var endOperands: LazyFilterSequence<UseList> {\n return uses.lazy.filter { $0.instruction is EndBorrowInst }\n }\n}\n\nfinal public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction, BorrowIntroducingInstruction {\n public var borrowedValue: Value { operand.value }\n\n public override var isLexical: Bool { bridged.BeginBorrow_isLexical() }\n public var hasPointerEscape: Bool { bridged.BeginBorrow_hasPointerEscape() }\n public var isFromVarDecl: Bool { bridged.BeginBorrow_isFromVarDecl() }\n\n public var endOperands: LazyFilterSequence<UseList> {\n return uses.endingLifetime\n }\n}\n\nfinal public class LoadBorrowInst : SingleValueInstruction, LoadInstruction, BorrowIntroducingInstruction {\n\n // True if the invariants on `load_borrow` have not been checked and should not be strictly enforced.\n //\n // This can only occur during raw SIL before move-only checking occurs. Developers can write incorrect\n // code using noncopyable types that consumes or mutates a memory location while that location is borrowed,\n // but the move-only checker must diagnose those problems before canonical SIL is formed.\n public var isUnchecked: Bool { bridged.LoadBorrowInst_isUnchecked() }\n}\n\nfinal public class StoreBorrowInst : SingleValueInstruction, StoringInstruction, BorrowIntroducingInstruction {\n public var allocStack: AllocStackInst {\n var dest = destination\n if let mark = dest as? MarkUnresolvedNonCopyableValueInst {\n dest = mark.operand.value\n }\n return dest as! AllocStackInst\n }\n\n public var endBorrows: LazyMapSequence<LazyFilterSequence<UseList>, Instruction> {\n uses.users(ofType: EndBorrowInst.self)\n }\n}\n\nfinal public class BeginAccessInst : SingleValueInstruction, UnaryInstruction {\n // The raw values must match SILAccessKind.\n public enum AccessKind: Int {\n case `init` = 0\n case read = 1\n case modify = 2\n case `deinit` = 3\n }\n public var accessKind: AccessKind {\n AccessKind(rawValue: bridged.BeginAccessInst_getAccessKind())!\n }\n\n public var isStatic: Bool { bridged.BeginAccessInst_isStatic() }\n public var isUnsafe: Bool { bridged.BeginAccessInst_isUnsafe() }\n\n public var address: Value { operand.value }\n\n public typealias EndAccessInstructions = LazyMapSequence<LazyFilterSequence<UseList>, EndAccessInst>\n\n public var endAccessInstructions: EndAccessInstructions {\n endOperands.map { $0.instruction as! EndAccessInst }\n }\n}\n\nfinal public class EndAccessInst : Instruction, UnaryInstruction {\n public var beginAccess: BeginAccessInst {\n return operand.value as! BeginAccessInst\n }\n}\n\nextension BeginAccessInst : ScopedInstruction {\n public var instruction: Instruction { get { self } }\n\n public var endOperands: LazyFilterSequence<UseList> {\n return uses.lazy.filter { $0.instruction is EndAccessInst }\n }\n}\n\n// Unpaired accesses do not have a static scope, are generally unsupported by the optimizer, and should be avoided.\nfinal public class BeginUnpairedAccessInst : Instruction {}\n\nfinal public class EndUnpairedAccessInst : Instruction {}\n\n\nfinal public class BeginApplyInst : MultipleValueInstruction, FullApplySite {\n public var numArguments: Int { bridged.BeginApplyInst_numArguments() }\n public var isCalleeAllocated: Bool { bridged.BeginApplyInst_isCalleeAllocated() }\n\n public var singleDirectResult: Value? { nil }\n public var singleDirectErrorResult: Value? { nil }\n\n public var token: Value { getResult(index: resultCount - (isCalleeAllocated ? 2 : 1)) }\n\n public var yieldedValues: Results {\n Results(inst: self, numResults: resultCount - (isCalleeAllocated ? 2 : 1))\n }\n}\n\nfinal public class EndApplyInst : SingleValueInstruction, UnaryInstruction {\n public var token: MultipleValueInstructionResult { operand.value as! MultipleValueInstructionResult }\n public var beginApply: BeginApplyInst { token.parentInstruction as! BeginApplyInst }\n}\n\nfinal public class AbortApplyInst : Instruction, UnaryInstruction {\n public var token: MultipleValueInstructionResult { operand.value as! MultipleValueInstructionResult }\n public var beginApply: BeginApplyInst { token.parentInstruction as! BeginApplyInst }\n}\n\nextension BeginApplyInst : ScopedInstruction {\n public var instruction: Instruction { get { self } }\n\n public var endOperands: LazyFilterSequence<UseList> {\n return token.uses.lazy.filter { $0.isScopeEndingUse }\n }\n}\n\n/// A sequence representing the use points of an instruction for the purpose of liveness and the general\n/// nesting of scopes.\n///\n/// Abstracts over simple single-use instructions vs. an instruction that is always paired with scope ending\n/// instructions that denote the end of the scoped operation.\npublic enum EndInstructions: CollectionLikeSequence {\n public typealias EndScopedInstructions = LazyMapSequence<LazyFilterSequence<UseList>, Instruction>\n\n case single(Instruction)\n case scoped(EndScopedInstructions)\n\n public enum Iterator : IteratorProtocol {\n case single(Instruction?)\n case scoped(EndScopedInstructions.Iterator)\n\n public mutating func next() -> Instruction? {\n switch self {\n case let .single(inst):\n if let result = inst {\n self = .single(nil)\n return result\n }\n return nil\n case var .scoped(iter):\n let result = iter.next()\n self = .scoped(iter)\n return result\n }\n }\n }\n\n public func makeIterator() -> Iterator {\n switch self {\n case let .single(inst):\n return .single(inst)\n case let .scoped(endScoped):\n return .scoped(endScoped.makeIterator())\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// multi-value instructions\n//===----------------------------------------------------------------------===//\n\nfinal public class BeginCOWMutationInst : MultipleValueInstruction, UnaryInstruction {\n public var instance: Value { operand.value }\n public var uniquenessResult: Value { return getResult(index: 0) }\n public var instanceResult: Value { return getResult(index: 1) }\n}\n\nfinal public class DestructureStructInst : MultipleValueInstruction, UnaryInstruction {\n public var `struct`: Value { operand.value }\n}\n\nfinal public class DestructureTupleInst : MultipleValueInstruction, UnaryInstruction {\n public var `tuple`: Value { operand.value }\n}\n\n//===----------------------------------------------------------------------===//\n// parameter pack instructions\n//===----------------------------------------------------------------------===//\n\nfinal public class AllocPackInst : SingleValueInstruction, Allocation {}\nfinal public class AllocPackMetadataInst : SingleValueInstruction, Allocation {}\n\nfinal public class DeallocPackInst : Instruction, UnaryInstruction, Deallocation {}\nfinal public class DeallocPackMetadataInst : Instruction, Deallocation {}\n\nfinal public class OpenPackElementInst : SingleValueInstruction {}\nfinal public class PackLengthInst : SingleValueInstruction {}\nfinal public class DynamicPackIndexInst : SingleValueInstruction {}\nfinal public class PackPackIndexInst : SingleValueInstruction {}\nfinal public class ScalarPackIndexInst : SingleValueInstruction {}\n\nfinal public class TuplePackExtractInst: SingleValueInstruction {\n public var indexOperand: Operand { operands[0] }\n public var tupleOperand: Operand { operands[1] }\n}\n\nfinal public class TuplePackElementAddrInst: SingleValueInstruction {\n public var indexOperand: Operand { operands[0] }\n public var tupleOperand: Operand { operands[1] }\n}\n\nfinal public class PackElementGetInst: SingleValueInstruction {}\n\nfinal public class PackElementSetInst: Instruction {}\n\n//===----------------------------------------------------------------------===//\n// terminator instructions\n//===----------------------------------------------------------------------===//\n\npublic class TermInst : Instruction {\n final public var successors: SuccessorArray {\n let succArray = bridged.TermInst_getSuccessors()\n return SuccessorArray(base: succArray.base, count: succArray.count)\n }\n \n public var isFunctionExiting: Bool { false }\n}\n\nfinal public class UnreachableInst : TermInst {\n}\n\nfinal public class ReturnInst : TermInst, UnaryInstruction {\n public var returnedValue: Value { operand.value }\n public override var isFunctionExiting: Bool { true }\n}\n\nfinal public class ThrowInst : TermInst, UnaryInstruction {\n public var thrownValue: Value { operand.value }\n public override var isFunctionExiting: Bool { true }\n}\n\nfinal public class ThrowAddrInst : TermInst {\n public override var isFunctionExiting: Bool { true }\n}\n\nfinal public class YieldInst : TermInst {\n}\n\nfinal public class UnwindInst : TermInst {\n public override var isFunctionExiting: Bool { true }\n}\n\nfinal public class TryApplyInst : TermInst, FullApplySite {\n public var numArguments: Int { bridged.TryApplyInst_numArguments() }\n\n public var normalBlock: BasicBlock { successors[0] }\n public var errorBlock: BasicBlock { successors[1] }\n\n public var singleDirectResult: Value? { normalBlock.arguments[0] }\n public var singleDirectErrorResult: Value? { errorBlock.arguments[0] }\n\n public var isNonAsync: Bool { bridged.TryApplyInst_getNonAsync() }\n public var specializationInfo: ApplyInst.SpecializationInfo { bridged.TryApplyInst_getSpecializationInfo() }\n}\n\nfinal public class BranchInst : TermInst {\n public var targetBlock: BasicBlock { bridged.BranchInst_getTargetBlock().block }\n\n /// Returns the target block argument for the cond_br `operand`.\n public func getArgument(for operand: Operand) -> Argument {\n return targetBlock.arguments[operand.index]\n }\n}\n\nfinal public class CondBranchInst : TermInst {\n public var trueBlock: BasicBlock { successors[0] }\n public var falseBlock: BasicBlock { successors[1] }\n\n public var condition: Value { operands[0].value }\n\n public var trueOperands: OperandArray { operands[1..<(bridged.CondBranchInst_getNumTrueArgs() &+ 1)] }\n public var falseOperands: OperandArray {\n let ops = operands\n return ops[(bridged.CondBranchInst_getNumTrueArgs() &+ 1)..<ops.count]\n }\n\n /// Returns the true or false block argument for the cond_br `operand`.\n ///\n /// Return nil if `operand` is the condition itself.\n public func getArgument(for operand: Operand) -> Argument? {\n let opIdx = operand.index\n if opIdx == 0 {\n return nil\n }\n let argIdx = opIdx - 1\n let numTrueArgs = bridged.CondBranchInst_getNumTrueArgs()\n if (0..<numTrueArgs).contains(argIdx) {\n return trueBlock.arguments[argIdx]\n } else {\n return falseBlock.arguments[argIdx - numTrueArgs]\n }\n }\n}\n\nfinal public class SwitchValueInst : TermInst {\n}\n\nfinal public class SwitchEnumInst : TermInst {\n\n public var enumOp: Value { operands[0].value }\n\n public struct CaseIndexArray : RandomAccessCollection {\n fileprivate let switchEnum: SwitchEnumInst\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { switchEnum.bridged.SwitchEnumInst_getNumCases() }\n\n public subscript(_ index: Int) -> Int {\n switchEnum.bridged.SwitchEnumInst_getCaseIndex(index)\n }\n }\n\n var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) }\n\n var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> {\n zip(caseIndices, successors)\n }\n\n // This does not handle the special case where the default covers exactly\n // the "missing" case.\n public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? {\n cases.first(where: { $0.0 == forCaseIndex })?.1\n }\n\n // This does not handle the special case where the default covers exactly\n // the "missing" case.\n public func getUniqueCase(forSuccessor: BasicBlock) -> Int? {\n cases.first(where: { $0.1 == forSuccessor })?.0\n }\n}\n\nfinal public class SwitchEnumAddrInst : TermInst {\n}\n\nfinal public class SelectEnumAddrInst : SingleValueInstruction {\n}\n\nfinal public class DynamicMethodBranchInst : TermInst {\n}\n\nfinal public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction {\n}\n\npublic enum CastingIsolatedConformances {\n case allow\n case prohibit\n\n var bridged: BridgedInstruction.CastingIsolatedConformances {\n switch self {\n case .allow: return .Allow\n case .prohibit: return .Prohibit\n }\n }\n}\n\nfinal public class CheckedCastBranchInst : TermInst, UnaryInstruction {\n public var source: Value { operand.value }\n public var successBlock: BasicBlock { bridged.CheckedCastBranch_getSuccessBlock().block }\n public var failureBlock: BasicBlock { bridged.CheckedCastBranch_getFailureBlock().block }\n\n public func updateSourceFormalTypeFromOperandLoweredType() {\n bridged.CheckedCastBranch_updateSourceFormalTypeFromOperandLoweredType()\n }\n\n public var isolatedConformances: CastingIsolatedConformances {\n switch bridged.CheckedCastBranch_getIsolatedConformances() {\n case .Allow: return .allow\n case .Prohibit: return .prohibit\n default: fatalError("Bad CastingIsolatedConformances value")\n }\n }\n}\n\nfinal public class CheckedCastAddrBranchInst : TermInst {\n public var source: Value { operands[0].value }\n public var destination: Value { operands[1].value }\n\n public var sourceFormalType: CanonicalType {\n CanonicalType(bridged: bridged.CheckedCastAddrBranch_getSourceFormalType())\n }\n public var targetFormalType: CanonicalType {\n CanonicalType(bridged: bridged.CheckedCastAddrBranch_getTargetFormalType())\n }\n\n public var successBlock: BasicBlock { bridged.CheckedCastAddrBranch_getSuccessBlock().block }\n public var failureBlock: BasicBlock { bridged.CheckedCastAddrBranch_getFailureBlock().block }\n\n public enum CastConsumptionKind {\n /// The source value is always taken, regardless of whether the cast\n /// succeeds. That is, if the cast fails, the source value is\n /// destroyed.\n case TakeAlways\n\n /// The source value is taken only on a successful cast; otherwise,\n /// it is left in place.\n case TakeOnSuccess\n\n /// The source value is always left in place, and the destination\n /// value is copied into on success.\n case CopyOnSuccess\n }\n\n public var consumptionKind: CastConsumptionKind {\n switch bridged.CheckedCastAddrBranch_getConsumptionKind() {\n case .TakeAlways: return .TakeAlways\n case .TakeOnSuccess: return .TakeOnSuccess\n case .CopyOnSuccess: return .CopyOnSuccess\n default:\n fatalError("invalid cast consumption kind")\n }\n }\n\n public var isolatedConformances: CastingIsolatedConformances {\n switch bridged.CheckedCastAddrBranch_getIsolatedConformances() {\n case .Allow: .allow\n case .Prohibit: .prohibit\n @unknown default: fatalError("Unhandled CastingIsolatedConformances")\n }\n }\n}\n\nfinal public class ThunkInst : Instruction {\n}\n\nfinal public class MergeIsolationRegionInst : Instruction {\n}\n\nfinal public class IgnoredUseInst : Instruction, UnaryInstruction {\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Instruction.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Instruction.swift
Swift
63,586
0.75
0.159744
0.086927
node-utils
639
2025-04-26T16:40:12.207106
Apache-2.0
false
95f58174c065164b358df363bbd0309b
//===--- Linkage.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SILBridging\n\npublic enum Linkage: CustomStringConvertible {\n /// This object definition is visible to multiple Swift modules (and\n /// thus potentially across linkage-unit boundaries). There are no\n /// other object definitions with this name in the program.\n ///\n /// Public functions must be definitions, i.e. must have a body, except the\n /// body is emitted by clang.\n case `public`\n\n /// This is a special linkage used for symbols which are treated\n /// as public for the purposes of SIL serialization and optimization,\n /// but do not have public entry points in the generated binary.\n ///\n /// This linkage is used for @_alwaysEmitIntoClient functions.\n ///\n /// There is no external variant of this linkage, because from other\n /// translation units in the same module, this behaves identically\n /// to the HiddenExternal linkage.\n ///\n /// When deserialized, such declarations receive Shared linkage.\n ///\n /// PublicNonABI functions must be definitions.\n case publicNonABI\n\n /// Same as \c Public, except the definition is visible within a package\n /// of modules.\n case package\n\n /// Similar to \c PublicNonABI, this definition is used for symbols treated\n /// as package but do not have package entry points in the generated binary.\n /// It's used for default argument expressions and `@_alwaysEmitIntoClient`.\n /// When deserialized, this will become \c Shared linkage.\n case packageNonABI\n\n /// This object definition is visible only to the current Swift\n /// module (and thus should not be visible across linkage-unit\n /// boundaries). There are no other object definitions with this\n /// name in the module.\n ///\n /// Hidden functions must be definitions, i.e. must have a body, except the\n /// body is emitted by clang.\n case hidden\n\n /// This object definition is visible only within a single Swift\n /// module. There may be other object definitions with this name in\n /// the module; those definitions are all guaranteed to be\n /// semantically equivalent to this one.\n ///\n /// This linkage is used e.g. for thunks and for specialized functions.\n ///\n /// Shared functions must be definitions, i.e. must have a body, except the\n /// body is emitted by clang.\n case shared\n\n /// This object definition is visible only within a single Swift\n /// file.\n ///\n /// Private functions must be definitions, i.e. must have a body, except the\n /// body is emitted by clang.\n case `private`\n\n /// A Public definition with the same name as this object will be\n /// available to the current Swift module at runtime. If this\n /// object is a definition, it is semantically equivalent to that\n /// definition.\n case publicExternal\n\n /// Similar to \c PublicExternal.\n /// Used to reference a \c Package definition in a different module\n /// within a package.\n case packageExternal\n\n /// A Public or Hidden definition with the same name as this object\n /// will be defined by the current Swift module at runtime.\n ///\n /// This linkage is only used for non-whole-module compilations to refer to\n /// functions in other files of the same module.\n case hiddenExternal\n\n public var isExternal: Bool {\n switch self {\n case .public,\n .publicNonABI,\n .package,\n .packageNonABI,\n .hidden,\n .shared,\n .private:\n return false\n case .packageExternal,\n .publicExternal,\n .hiddenExternal:\n return true\n }\n\n }\n\n public var description: String {\n switch self {\n case .public: return "public"\n case .publicNonABI: return "publicNonABI"\n case .package: return "package"\n case .packageNonABI: return "packageNonABI"\n case .hidden: return "hidden"\n case .shared: return "shared"\n case .private: return "private"\n case .packageExternal: return "packageExternal"\n case .publicExternal: return "publicExternal"\n case .hiddenExternal: return "hiddenExternal"\n }\n }\n}\n\n// Bridging utilities\n\nextension BridgedLinkage {\n var linkage: Linkage {\n switch self {\n case .Public: return .public\n case .PublicNonABI: return .publicNonABI\n case .Package: return .package\n case .PackageNonABI: return .packageNonABI\n case .Hidden: return .hidden\n case .Shared: return .shared\n case .Private: return .private\n case .PublicExternal: return .publicExternal\n case .PackageExternal: return .packageExternal\n case .HiddenExternal: return .hiddenExternal\n default:\n fatalError("unsupported argument convention")\n }\n }\n}\n\nextension Linkage {\n public var bridged: BridgedLinkage {\n switch self {\n case .public: return .Public\n case .publicNonABI: return .PublicNonABI\n case .package: return .Package\n case .packageNonABI: return .PackageNonABI\n case .hidden: return .Hidden\n case .shared: return .Shared\n case .private: return .Private\n case .publicExternal: return .PublicExternal\n case .packageExternal: return .PackageExternal\n case .hiddenExternal: return .HiddenExternal\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Linkage.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Linkage.swift
Swift
5,769
0.95
0.085366
0.47619
vue-tools
719
2025-04-15T13:42:13.767307
GPL-3.0
false
603fb0a554e36771cc286b8884658330
//===--- Location.swift - Source location ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SILBridging\nimport AST\n\npublic struct Location: Equatable, CustomStringConvertible {\n let bridged: BridgedLocation\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n \n public var sourceLoc: SourceLoc? {\n if hasValidLineNumber {\n return SourceLoc(bridged: bridged.getSourceLocation())\n }\n return nil\n }\n\n /// Keeps the debug scope but marks it as auto-generated.\n public var autoGenerated: Location {\n Location(bridged: bridged.getAutogeneratedLocation())\n }\n\n public var hasValidLineNumber: Bool { bridged.hasValidLineNumber() }\n public var isAutoGenerated: Bool { bridged.isAutoGenerated() }\n public var isInlined: Bool { bridged.isInlined() }\n\n public var isDebugSteppable: Bool { hasValidLineNumber && !isAutoGenerated }\n\n /// The `Decl` if the location refers to a declaration.\n public var decl: Decl? { bridged.getDecl().decl }\n\n public static func ==(lhs: Location, rhs: Location) -> Bool {\n lhs.bridged.isEqualTo(rhs.bridged)\n }\n\n public func hasSameSourceLocation(as other: Location) -> Bool {\n bridged.hasSameSourceLocation(other.bridged)\n }\n\n public static var artificialUnreachableLocation: Location {\n Location(bridged: BridgedLocation.getArtificialUnreachableLocation())\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Location.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Location.swift
Swift
1,808
0.95
0.072727
0.295455
vue-tools
151
2023-09-27T15:39:50.710703
BSD-3-Clause
false
a111cdb11df9fd40265e9d6ca9d90aa9
//===--- Operand.swift - Instruction operands -----------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SILBridging\n\n/// An operand of an instruction.\npublic struct Operand : CustomStringConvertible, NoReflectionChildren, Equatable {\n public let bridged: BridgedOperand\n\n public init(bridged: BridgedOperand) {\n self.bridged = bridged\n }\n\n init?(bridged: OptionalBridgedOperand) {\n guard let op = bridged.op else { return nil }\n self.bridged = BridgedOperand(op: op)\n }\n\n public var value: Value { bridged.getValue().value }\n\n public static func ==(lhs: Operand, rhs: Operand) -> Bool {\n return lhs.bridged.op == rhs.bridged.op\n }\n\n public var instruction: Instruction {\n return bridged.getUser().instruction\n }\n \n public var index: Int { instruction.operands.getIndex(of: self) }\n \n /// True if the operand is used to describe a type dependency, but it's not\n /// used as value.\n public var isTypeDependent: Bool { bridged.isTypeDependent() }\n\n public var endsLifetime: Bool { bridged.isLifetimeEnding() }\n\n public func canAccept(ownership: Ownership) -> Bool { bridged.canAcceptOwnership(ownership._bridged) }\n\n public var description: String { "operand #\(index) of \(instruction)" }\n}\n\npublic struct OperandArray : RandomAccessCollection, CustomReflectable {\n private let base: OptionalBridgedOperand\n public let count: Int\n \n init(base: OptionalBridgedOperand, count: Int) {\n self.base = base\n self.count = count\n }\n\n init(base: Operand, count: Int) {\n self.base = OptionalBridgedOperand(bridged: base.bridged)\n self.count = count\n }\n\n static public var empty: OperandArray {\n OperandArray(base: OptionalBridgedOperand(bridged: nil), count: 0)\n }\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { return count }\n \n public subscript(_ index: Int) -> Operand {\n assert(index >= startIndex && index < endIndex)\n return Operand(bridged: base.advancedBy(index))\n }\n \n public func getIndex(of operand: Operand) -> Int {\n let idx = base.distanceTo(operand.bridged)\n assert(self[idx].bridged.op == operand.bridged.op)\n return idx\n }\n \n public var customMirror: Mirror {\n let c: [Mirror.Child] = map { (label: nil, value: $0.value) }\n return Mirror(self, children: c)\n }\n \n /// Returns a sub-array defined by `bounds`.\n ///\n /// Note: this does not return a Slice. The first index of the returned array is always 0.\n public subscript(bounds: Range<Int>) -> OperandArray {\n assert(bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex)\n return OperandArray(\n base: OptionalBridgedOperand(op: base.advancedBy(bounds.lowerBound).op),\n count: bounds.upperBound - bounds.lowerBound)\n }\n\n public var values: LazyMapSequence<LazySequence<OperandArray>.Elements, Value> {\n self.lazy.map { $0.value }\n }\n}\n\npublic struct UseList : CollectionLikeSequence {\n public struct Iterator : IteratorProtocol {\n var currentOpPtr: OptionalBridgedOperand\n \n public mutating func next() -> Operand? {\n if let bridgedOp = currentOpPtr.operand {\n var op = bridgedOp\n // Skip operands of deleted instructions.\n while op.isDeleted() {\n guard let nextOp = op.getNextUse().operand else {\n return nil\n }\n op = nextOp\n }\n currentOpPtr = op.getNextUse();\n return Operand(bridged: op)\n }\n return nil\n }\n }\n\n private let firstOpPtr: OptionalBridgedOperand\n\n init(_ firstOpPtr: OptionalBridgedOperand) {\n self.firstOpPtr = firstOpPtr\n }\n\n public func makeIterator() -> Iterator {\n return Iterator(currentOpPtr: firstOpPtr)\n }\n}\n\nextension Sequence where Element == Operand {\n public var singleUse: Operand? {\n var result: Operand? = nil\n for op in self {\n if result != nil {\n return nil\n }\n result = op\n }\n return result\n }\n\n public var isSingleUse: Bool { singleUse != nil }\n\n public var ignoreTypeDependence: LazyFilterSequence<Self> {\n self.lazy.filter({!$0.isTypeDependent})\n }\n\n public var ignoreDebugUses: LazyFilterSequence<Self> {\n self.lazy.filter { !($0.instruction is DebugValueInst) }\n }\n\n public func filterUsers<I: Instruction>(ofType: I.Type) -> LazyFilterSequence<Self> {\n self.lazy.filter { $0.instruction is I }\n }\n\n public func ignoreUsers<I: Instruction>(ofType: I.Type) -> LazyFilterSequence<Self> {\n self.lazy.filter { !($0.instruction is I) }\n }\n\n public func ignore(user: Instruction) -> LazyFilterSequence<Self> {\n self.lazy.filter { !($0.instruction == user) }\n }\n\n public func getSingleUser<I: Instruction>(ofType: I.Type) -> I? {\n filterUsers(ofType: I.self).singleUse?.instruction as? I\n }\n\n public func getSingleUser<I: Instruction>(notOfType: I.Type) -> Instruction? {\n ignoreUsers(ofType: I.self).singleUse?.instruction\n }\n\n public var endingLifetime: LazyFilterSequence<Self> {\n return self.lazy.filter { $0.endsLifetime }\n }\n\n public var users: LazyMapSequence<Self, Instruction> {\n return self.lazy.map { $0.instruction }\n }\n\n public func users<I: Instruction>(ofType: I.Type) -> LazyMapSequence<LazyFilterSequence<Self>, I> {\n self.lazy.filter{ $0.instruction is I }.lazy.map { $0.instruction as! I }\n }\n\n // This overload which returns a Sequence of `Instruction` and not a Sequence of `I` is used for APIs, like\n // `InstructionSet.insert(contentsOf:)`, which require a sequence of `Instruction`.\n public func users<I: Instruction>(ofType: I.Type) -> LazyMapSequence<LazyFilterSequence<Self>, Instruction> {\n self.lazy.filter{ $0.instruction is I }.users\n }\n}\n\nextension Value {\n public var users: LazyMapSequence<UseList, Instruction> { uses.users }\n}\n\nextension Operand {\n /// Return true if this operation will store a full value into this\n /// operand's address.\n public var isAddressInitialization: Bool {\n if !value.type.isAddress {\n return false\n }\n switch instruction {\n case is StoringInstruction:\n return true\n case let srcDestInst as SourceDestAddrInstruction\n where srcDestInst.destinationOperand == self:\n return true\n case let apply as FullApplySite:\n return apply.isIndirectResult(operand: self)\n default:\n return false\n }\n }\n}\n\nextension Operand {\n /// A scope ending use is a consuming use for normal borrow scopes, but it also applies to intructions that end the\n /// scope of an address (end_access) or a token (end_apply, abort_apply),\n public var isScopeEndingUse: Bool {\n switch instruction {\n case is EndBorrowInst, is EndAccessInst, is EndApplyInst, is AbortApplyInst:\n return true\n default:\n return false\n }\n }\n}\n\nextension OptionalBridgedOperand {\n init(bridged: BridgedOperand?) {\n self = OptionalBridgedOperand(op: bridged?.op)\n }\n var operand: BridgedOperand? {\n if let op = op {\n return BridgedOperand(op: op)\n }\n return nil\n }\n}\n\n/// Categorize all uses in terms of their ownership effect. Implies ownership and lifetime constraints.\npublic enum OperandOwnership {\n /// Operands that do not use the value. They only represent a dependence on a dominating definition and do not require liveness. (type-dependent operands)\n case nonUse\n \n /// Uses that can only handle trivial values. The operand value must have None ownership. These uses require liveness but are otherwise unverified.\n case trivialUse\n \n /// Use the value only for the duration of the operation, which may have side effects. (single-instruction apply with @guaranteed argument)\n case instantaneousUse\n \n /// Use a value without requiring or propagating ownership. The operation may not have side-effects that could affect ownership. This is limited to a small number of operations that are allowed to take Unowned values. (copy_value, single-instruction apply with @unowned argument))\n case unownedInstantaneousUse\n \n /// Forwarding instruction with an Unowned result. Its operands may have any ownership.\n case forwardingUnowned\n \n /// Escape a pointer into a value which cannot be tracked or verified.\n ///\n /// PointerEscape operands indicate a SIL deficiency to suffuciently model dependencies. They never arise from user-level escapes.\n case pointerEscape\n \n /// Bitwise escape. Escapes the nontrivial contents of the value. OSSA does not enforce the lifetime of the escaping bits. The programmer must explicitly force lifetime extension. (ref_to_unowned, unchecked_trivial_bitcast)\n case bitwiseEscape\n \n /// Borrow. Propagates the owned or guaranteed value within a scope, without ending its lifetime. (begin_borrow, begin_apply with @guaranteed argument)\n case borrow\n \n /// Destroying Consume. Destroys the owned value immediately. (store, destroy, @owned destructure).\n case destroyingConsume\n\n /// Forwarding Consume. Consumes the owned value indirectly via a move. (br, destructure, tuple, struct, cast, switch).\n case forwardingConsume\n \n /// Interior Pointer. Propagates a trivial value (e.g. address, pointer, or no-escape closure) that depends on the guaranteed value within the base's borrow scope. The verifier checks that all uses of the trivial\n /// value are in scope. (ref_element_addr, open_existential_box)\n case interiorPointer\n\n /// Any Interior Pointer. An interior pointer that allows any operand ownership. This will be removed as soon as SIL\n /// migrates away from extraneous borrow scopes.\n case anyInteriorPointer\n\n /// Forwarded Borrow. Propagates the guaranteed value within the base's borrow scope. (tuple_extract, struct_extract, cast, switch)\n case guaranteedForwarding\n \n /// End Borrow. End the borrow scope opened directly by the operand. The operand must be a begin_borrow, begin_apply, or function argument. (end_borrow, end_apply)\n case endBorrow\n \n /// Reborrow. Ends the borrow scope opened directly by the operand and begins one or multiple disjoint borrow scopes. If a forwarded value is reborrowed, then its base must also be reborrowed at the same point. (br, FIXME: should also include destructure, tuple, struct)\n case reborrow\n\n public var endsLifetime: Bool {\n switch self {\n case .nonUse, .trivialUse, .instantaneousUse, .unownedInstantaneousUse,\n .forwardingUnowned, .pointerEscape, .bitwiseEscape, .borrow,\n .interiorPointer, .anyInteriorPointer, .guaranteedForwarding:\n return false\n case .destroyingConsume, .forwardingConsume, .endBorrow, .reborrow:\n return true\n }\n }\n\n public var _bridged: BridgedOperand.OperandOwnership {\n switch self {\n case .nonUse:\n return BridgedOperand.OperandOwnership.NonUse\n case .trivialUse:\n return BridgedOperand.OperandOwnership.TrivialUse\n case .instantaneousUse:\n return BridgedOperand.OperandOwnership.InstantaneousUse\n case .unownedInstantaneousUse:\n return BridgedOperand.OperandOwnership.UnownedInstantaneousUse\n case .forwardingUnowned:\n return BridgedOperand.OperandOwnership.ForwardingUnowned\n case .pointerEscape:\n return BridgedOperand.OperandOwnership.PointerEscape\n case .bitwiseEscape:\n return BridgedOperand.OperandOwnership.BitwiseEscape\n case .borrow:\n return BridgedOperand.OperandOwnership.Borrow\n case .destroyingConsume:\n return BridgedOperand.OperandOwnership.DestroyingConsume\n case .forwardingConsume:\n return BridgedOperand.OperandOwnership.ForwardingConsume\n case .interiorPointer:\n return BridgedOperand.OperandOwnership.InteriorPointer\n case .anyInteriorPointer:\n return BridgedOperand.OperandOwnership.AnyInteriorPointer\n case .guaranteedForwarding:\n return BridgedOperand.OperandOwnership.GuaranteedForwarding\n case .endBorrow:\n return BridgedOperand.OperandOwnership.EndBorrow\n case .reborrow:\n return BridgedOperand.OperandOwnership.Reborrow\n }\n }\n}\n\nextension Operand {\n public var ownership: OperandOwnership {\n switch bridged.getOperandOwnership() {\n case .NonUse: return .nonUse\n case .TrivialUse: return .trivialUse\n case .InstantaneousUse: return .instantaneousUse\n case .UnownedInstantaneousUse: return .unownedInstantaneousUse\n case .ForwardingUnowned: return .forwardingUnowned\n case .PointerEscape: return .pointerEscape\n case .BitwiseEscape: return .bitwiseEscape\n case .Borrow: return .borrow\n case .DestroyingConsume: return .destroyingConsume\n case .ForwardingConsume: return .forwardingConsume\n case .InteriorPointer: return .interiorPointer\n case .AnyInteriorPointer: return .anyInteriorPointer\n case .GuaranteedForwarding: return .guaranteedForwarding\n case .EndBorrow: return .endBorrow\n case .Reborrow: return .reborrow\n default:\n fatalError("unsupported operand ownership")\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Operand.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Operand.swift
Swift
13,196
0.95
0.057377
0.144737
python-kit
694
2025-06-16T18:22:26.538860
MIT
false
26580379d072445d37fb8c996aff5510
//===--- Registration.swift - register SIL classes ------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport SILBridging\n\nprivate func register<T: AnyObject>(_ cl: T.Type) {\n "\(cl)"._withBridgedStringRef { nameStr in\n let metatype = unsafeBitCast(cl, to: SwiftMetatype.self)\n registerBridgedClass(nameStr, metatype)\n }\n}\n\npublic func registerSILClasses() {\n Function.register()\n register(BasicBlock.self)\n register(GlobalVariable.self)\n\n register(MultipleValueInstructionResult.self)\n\n register(Undef.self)\n register(PlaceholderValue.self)\n\n register(FunctionArgument.self)\n register(Argument.self)\n\n register(StoreInst.self)\n register(StoreWeakInst.self)\n register(StoreUnownedInst.self)\n register(StoreBorrowInst.self)\n register(AssignInst.self)\n register(AssignByWrapperInst.self)\n register(AssignOrInitInst.self)\n register(CopyAddrInst.self)\n register(ExplicitCopyAddrInst.self)\n register(EndAccessInst.self)\n register(BeginUnpairedAccessInst.self)\n register(EndUnpairedAccessInst.self)\n register(EndBorrowInst.self)\n register(CondFailInst.self)\n register(IncrementProfilerCounterInst.self)\n register(MarkFunctionEscapeInst.self)\n register(HopToExecutorInst.self)\n register(MarkUninitializedInst.self)\n register(FixLifetimeInst.self)\n register(DebugValueInst.self)\n register(DebugStepInst.self)\n register(SpecifyTestInst.self)\n register(UnconditionalCheckedCastAddrInst.self)\n register(BeginDeallocRefInst.self)\n register(EndInitLetRefInst.self)\n register(BindMemoryInst.self)\n register(RebindMemoryInst.self)\n register(EndApplyInst.self)\n register(AbortApplyInst.self)\n register(StrongRetainInst.self)\n register(StrongRetainUnownedInst.self)\n register(UnownedRetainInst.self)\n register(UnmanagedRetainValueInst.self)\n register(RetainValueInst.self)\n register(StrongReleaseInst.self)\n register(RetainValueAddrInst.self)\n register(ReleaseValueAddrInst.self)\n register(UnownedReleaseInst.self)\n register(UnmanagedReleaseValueInst.self)\n register(AutoreleaseValueInst.self)\n register(UnmanagedAutoreleaseValueInst.self)\n register(ReleaseValueInst.self)\n register(DestroyValueInst.self)\n register(DestroyAddrInst.self)\n register(EndLifetimeInst.self)\n register(ExtendLifetimeInst.self)\n register(StrongCopyUnownedValueInst.self)\n register(StrongCopyUnmanagedValueInst.self)\n register(StrongCopyWeakValueInst.self)\n register(InjectEnumAddrInst.self)\n register(DeallocStackInst.self)\n register(DeallocPackInst.self)\n register(DeallocPackMetadataInst.self)\n register(DeallocStackRefInst.self)\n register(DeallocRefInst.self)\n register(DeallocPartialRefInst.self)\n register(DeallocBoxInst.self)\n register(DeallocExistentialBoxInst.self)\n register(LoadInst.self)\n register(LoadWeakInst.self)\n register(LoadUnownedInst.self)\n register(LoadBorrowInst.self)\n register(BuiltinInst.self)\n register(UpcastInst.self)\n register(UncheckedRefCastInst.self)\n register(UncheckedRefCastAddrInst.self)\n register(UncheckedAddrCastInst.self)\n register(UncheckedTrivialBitCastInst.self)\n register(UncheckedBitwiseCastInst.self)\n register(UncheckedValueCastInst.self)\n register(RefToRawPointerInst.self)\n register(RefToUnmanagedInst.self)\n register(RefToUnownedInst.self)\n register(UnmanagedToRefInst.self)\n register(UnownedToRefInst.self)\n register(MarkUnresolvedNonCopyableValueInst.self)\n register(MarkUnresolvedReferenceBindingInst.self)\n register(MarkUnresolvedMoveAddrInst.self)\n register(CopyableToMoveOnlyWrapperValueInst.self)\n register(MoveOnlyWrapperToCopyableValueInst.self)\n register(MoveOnlyWrapperToCopyableBoxInst.self)\n register(CopyableToMoveOnlyWrapperAddrInst.self)\n register(MoveOnlyWrapperToCopyableAddrInst.self)\n register(ObjectInst.self)\n register(VectorInst.self)\n register(TuplePackExtractInst.self)\n register(TuplePackElementAddrInst.self)\n register(PackElementGetInst.self)\n register(PackElementSetInst.self)\n register(DifferentiableFunctionInst.self)\n register(LinearFunctionInst.self)\n register(DifferentiableFunctionExtractInst.self)\n register(LinearFunctionExtractInst.self)\n register(DifferentiabilityWitnessFunctionInst.self)\n register(ProjectBlockStorageInst.self)\n register(InitBlockStorageHeaderInst.self)\n register(RawPointerToRefInst.self)\n register(AddressToPointerInst.self)\n register(PointerToAddressInst.self)\n register(IndexAddrInst.self)\n register(IndexRawPointerInst.self)\n register(TailAddrInst.self)\n register(InitExistentialRefInst.self)\n register(OpenExistentialRefInst.self)\n register(InitExistentialValueInst.self)\n register(DeinitExistentialValueInst.self)\n register(OpenExistentialValueInst.self)\n register(InitExistentialAddrInst.self)\n register(DeinitExistentialAddrInst.self)\n register(OpenExistentialAddrInst.self)\n register(OpenExistentialBoxInst.self)\n register(OpenExistentialBoxValueInst.self)\n register(InitExistentialMetatypeInst.self)\n register(OpenExistentialMetatypeInst.self)\n register(MetatypeInst.self)\n register(ValueMetatypeInst.self)\n register(ExistentialMetatypeInst.self)\n register(TypeValueInst.self)\n register(OpenPackElementInst.self)\n register(PackLengthInst.self)\n register(DynamicPackIndexInst.self)\n register(PackPackIndexInst.self)\n register(ScalarPackIndexInst.self)\n register(ObjCProtocolInst.self)\n register(FunctionRefInst.self)\n register(DynamicFunctionRefInst.self)\n register(PreviousDynamicFunctionRefInst.self)\n register(GlobalAddrInst.self)\n register(GlobalValueInst.self)\n register(BaseAddrForOffsetInst.self)\n register(AllocGlobalInst.self)\n register(IntegerLiteralInst.self)\n register(FloatLiteralInst.self)\n register(StringLiteralInst.self)\n register(HasSymbolInst.self)\n register(TupleInst.self)\n register(TupleExtractInst.self)\n register(TupleElementAddrInst.self)\n register(TupleAddrConstructorInst.self)\n register(StructInst.self)\n register(StructExtractInst.self)\n register(StructElementAddrInst.self)\n register(EnumInst.self)\n register(UncheckedEnumDataInst.self)\n register(InitEnumDataAddrInst.self)\n register(UncheckedTakeEnumDataAddrInst.self)\n register(SelectEnumInst.self)\n register(RefElementAddrInst.self)\n register(RefTailAddrInst.self)\n register(KeyPathInst.self)\n register(UnconditionalCheckedCastInst.self)\n register(ConvertFunctionInst.self)\n register(ThinToThickFunctionInst.self)\n register(ThickToObjCMetatypeInst.self)\n register(ObjCToThickMetatypeInst.self)\n register(CopyBlockInst.self)\n register(CopyBlockWithoutEscapingInst.self)\n register(ConvertEscapeToNoEscapeInst.self)\n register(ObjCExistentialMetatypeToObjectInst.self)\n register(ObjCMetatypeToObjectInst.self)\n register(ValueToBridgeObjectInst.self)\n register(MarkDependenceInst.self)\n register(MarkDependenceAddrInst.self)\n register(RefToBridgeObjectInst.self)\n register(BridgeObjectToRefInst.self)\n register(BridgeObjectToWordInst.self)\n register(GetAsyncContinuationInst.self)\n register(GetAsyncContinuationAddrInst.self)\n register(ExtractExecutorInst.self)\n register(BeginAccessInst.self)\n register(BeginBorrowInst.self)\n register(BorrowedFromInst.self)\n register(ProjectBoxInst.self)\n register(ProjectExistentialBoxInst.self)\n register(CopyValueInst.self)\n register(ExplicitCopyValueInst.self)\n register(UnownedCopyValueInst.self)\n register(WeakCopyValueInst.self)\n register(UncheckedOwnershipConversionInst.self)\n register(MoveValueInst.self)\n register(DropDeinitInst.self)\n register(EndCOWMutationInst.self)\n register(ClassifyBridgeObjectInst.self)\n register(PartialApplyInst.self)\n register(ApplyInst.self)\n register(FunctionExtractIsolationInst.self)\n register(ClassMethodInst.self)\n register(SuperMethodInst.self)\n register(ObjCMethodInst.self)\n register(ObjCSuperMethodInst.self)\n register(WitnessMethodInst.self)\n register(IsUniqueInst.self)\n register(DestroyNotEscapedClosureInst.self)\n register(AllocStackInst.self)\n register(AllocPackInst.self)\n register(AllocPackMetadataInst.self)\n register(AllocRefInst.self)\n register(AllocRefDynamicInst.self)\n register(AllocBoxInst.self)\n register(AllocExistentialBoxInst.self)\n\n register(BeginCOWMutationInst.self)\n register(DestructureStructInst.self)\n register(DestructureTupleInst.self)\n register(BeginApplyInst.self)\n\n register(UnreachableInst.self)\n register(ReturnInst.self)\n register(ThrowInst.self)\n register(ThrowAddrInst.self)\n register(YieldInst.self)\n register(UnwindInst.self)\n register(TryApplyInst.self)\n register(BranchInst.self)\n register(CondBranchInst.self)\n register(SwitchValueInst.self)\n register(SwitchEnumInst.self)\n register(SwitchEnumAddrInst.self)\n register(SelectEnumAddrInst.self)\n register(DynamicMethodBranchInst.self)\n register(AwaitAsyncContinuationInst.self)\n register(CheckedCastBranchInst.self)\n register(CheckedCastAddrBranchInst.self)\n register(ThunkInst.self)\n register(MergeIsolationRegionInst.self)\n register(IgnoredUseInst.self)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Registration.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Registration.swift
Swift
9,355
0.95
0.007634
0.043478
node-utils
582
2023-11-02T04:53:10.488734
BSD-3-Clause
false
fc7fe4055bbfa1ec161565b34dc55ca9
//===--- SILStage.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic enum SILStage: Int {\n /// "Raw" SIL, emitted by SILGen, but not yet run through guaranteed\n /// optimization and diagnostic passes.\n ///\n /// Raw SIL does not have fully-constructed SSA and may contain undiagnosed\n /// dataflow errors.\n case raw\n\n /// Canonical SIL, which has been run through at least the guaranteed\n /// optimization and diagnostic passes.\n ///\n /// Canonical SIL has stricter invariants than raw SIL. It must not contain\n /// dataflow errors, and some instructions must be canonicalized to simpler\n /// forms.\n case canonical\n\n /// Lowered SIL, which has been prepared for IRGen and will no longer\n /// be passed to canonical SIL transform passes.\n ///\n /// In lowered SIL, the SILType of all SILValues is its SIL storage\n /// type. Explicit storage is required for all address-only and resilient\n /// types.\n ///\n /// Generating the initial Raw SIL is typically referred to as lowering (from\n /// the AST). To disambiguate, refer to the process of generating the lowered\n /// stage of SIL as "address lowering".\n case lowered\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_SILStage.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_SILStage.swift
Swift
1,600
0.95
0.1
0.864865
node-utils
349
2024-01-10T11:04:42.464693
GPL-3.0
false
a9d1c166af1ef510610ed89a1d0534ff
//===--- Type.swift - Value type ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport AST\nimport SILBridging\n\n/// A Swift type that has been lowered to a SIL representation type.\n/// A `SIL.Type` is basically an `AST.CanonicalType` with the distinction between "object" and "address" type\n/// (`*T` is the type of an address pointing at T).\n/// Note that not all `CanonicalType`s can be represented as a `SIL.Type`.\npublic struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedType\n\n public var description: String {\n String(taking: bridged.getDebugDescription())\n }\n\n public var isAddress: Bool { bridged.isAddress() }\n public var isObject: Bool { !isAddress }\n\n public var addressType: Type { bridged.getAddressType().type }\n public var objectType: Type { bridged.getObjectType().type }\n\n public var rawType: AST.`Type` { canonicalType.rawType }\n public var canonicalType: CanonicalType { CanonicalType(bridged: bridged.getCanType()) }\n\n public func getLoweredType(in function: Function) -> Type {\n function.bridged.getLoweredType(self.bridged).type\n }\n\n //===--------------------------------------------------------------------===//\n // Various type properties\n //===--------------------------------------------------------------------===//\n\n public func isTrivial(in function: Function) -> Bool {\n return bridged.isTrivial(function.bridged)\n }\n\n /// Returns true if the type is a trivial type and is and does not contain a Builtin.RawPointer.\n public func isTrivialNonPointer(in function: Function) -> Bool {\n return !bridged.isNonTrivialOrContainsRawPointer(function.bridged)\n }\n\n public func isLoadable(in function: Function) -> Bool {\n return bridged.isLoadable(function.bridged)\n }\n\n public func isReferenceCounted(in function: Function) -> Bool {\n return bridged.isReferenceCounted(function.bridged)\n }\n\n public var isBox: Bool { bridged.isBox() }\n\n public var isMoveOnly: Bool { bridged.isMoveOnly() }\n\n /// Return true if this type conforms to Escapable.\n ///\n /// Note: invalid types are non-Escapable, so take care not to make assumptions about non-Escapable types.\n public func isEscapable(in function: Function) -> Bool {\n bridged.isEscapable(function.bridged)\n }\n\n /// Return true if this type conforms to Escapable and is not a noescape function type.\n ///\n /// Warning: may return true for (source-level) non-escaping closures. After SILGen, all partial_apply instructions\n /// have an escaping function type. ClosureLifetimeFixup only changes them to noescape function type if they are\n /// promoted to [on_stack]. But regardless of stack promotion, a non-escaping closure value's lifetime is constrained\n /// by the lifetime of its captures. Use Value.mayEscape instead to check for this case.\n public func mayEscape(in function: Function) -> Bool {\n !isNoEscapeFunction && isEscapable(in: function)\n }\n\n public var builtinVectorElementType: Type { canonicalType.builtinVectorElementType.silType! }\n\n public var superClassType: Type? { canonicalType.superClassType?.silType }\n\n public func isExactSuperclass(of type: Type) -> Bool {\n bridged.isExactSuperclassOf(type.bridged)\n }\n\n public func loweredInstanceTypeOfMetatype(in function: Function) -> Type {\n return canonicalType.instanceTypeOfMetatype.loweredType(in: function)\n }\n\n public var isMarkedAsImmortal: Bool { bridged.isMarkedAsImmortal() }\n\n /// True if a value of this type can have its address taken by a lifetime-dependent value.\n public func isAddressableForDeps(in function: Function) -> Bool {\n bridged.isAddressableForDeps(function.bridged)\n }\n\n //===--------------------------------------------------------------------===//\n // Properties of lowered `SILFunctionType`s\n //===--------------------------------------------------------------------===//\n\n public var containsNoEscapeFunction: Bool { bridged.containsNoEscapeFunction() }\n\n // Returns a new SILFunctionType with changed "escapeness".\n public func getFunctionType(withNoEscape: Bool) -> Type {\n bridged.getFunctionTypeWithNoEscape(withNoEscape).type\n }\n\n /// True if a function with this type can be code-generated in Embedded Swift.\n /// These are basically all non-generic functions. But also certain generic functions are supported:\n /// Generic function arguments which have a class-bound type are valid in Embedded Swift, because for\n /// such arguments, no metadata is needed, except the isa-pointer of the class.\n public var hasValidSignatureForEmbedded: Bool {\n let genericSignature = invocationGenericSignatureOfFunction\n for genParam in genericSignature.genericParameters {\n let mappedParam = genericSignature.mapTypeIntoContext(genParam)\n if mappedParam.isArchetype && !mappedParam.archetypeRequiresClass {\n return false\n }\n }\n return true\n }\n\n //===--------------------------------------------------------------------===//\n // Aggregates\n //===--------------------------------------------------------------------===//\n\n public var isVoid: Bool { isTuple && tupleElements.isEmpty }\n\n /// True if the type has no stored properties.\n /// For example an empty tuple or an empty struct or a combination of such.\n public func isEmpty(in function: Function) -> Bool {\n bridged.isEmpty(function.bridged)\n }\n\n public var tupleElements: TupleElementArray {\n precondition(isTuple)\n return TupleElementArray(type: self)\n }\n\n public func getBoxFields(in function: Function) -> BoxFieldsArray {\n precondition(isBox)\n return BoxFieldsArray(type: self, function: function)\n }\n\n /// Returns nil if the nominal is a resilient type because in this case the complete list\n /// of fields is not known.\n public func getNominalFields(in function: Function) -> NominalFieldsArray? {\n guard let nominal = nominal, !nominal.isResilient(in: function) else {\n return nil\n }\n return NominalFieldsArray(type: self, function: function)\n }\n\n /// Returns nil if the enum is a resilient type because in this case the complete list\n /// of cases is not known.\n public func getEnumCases(in function: Function) -> EnumCases? {\n guard let nominal = nominal,\n let en = nominal as? EnumDecl,\n !en.isResilient(in: function)\n else {\n return nil\n }\n return EnumCases(enumType: self, function: function)\n }\n\n public func getIndexOfEnumCase(withName name: String) -> Int? {\n let idx = name._withBridgedStringRef {\n bridged.getCaseIdxOfEnumType($0)\n }\n return idx >= 0 ? idx : nil\n }\n\n /// Returns true if this is a struct, enum or tuple and `otherType` is contained in this type - or is the same type.\n public func aggregateIsOrContains(_ otherType: Type, in function: Function) -> Bool {\n if self == otherType {\n return true\n }\n if isStruct {\n guard let fields = getNominalFields(in: function) else {\n return true\n }\n return fields.contains { $0.aggregateIsOrContains(otherType, in: function) }\n }\n if isTuple {\n return tupleElements.contains { $0.aggregateIsOrContains(otherType, in: function) }\n }\n if isEnum {\n guard let cases = getEnumCases(in: function) else {\n return true\n }\n return cases.contains { $0.payload?.aggregateIsOrContains(otherType, in: function) ?? false }\n }\n return false\n }\n}\n\nextension Type: Equatable {\n public static func ==(lhs: Type, rhs: Type) -> Bool { \n lhs.bridged.opaqueValue == rhs.bridged.opaqueValue\n }\n}\n\npublic struct TypeArray : RandomAccessCollection, CustomReflectable {\n public let bridged: BridgedSILTypeArray\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { return bridged.getCount() }\n\n public init(bridged: BridgedSILTypeArray) {\n self.bridged = bridged\n }\n\n public subscript(_ index: Int) -> Type {\n bridged.getAt(index).type\n }\n\n public var customMirror: Mirror {\n let c: [Mirror.Child] = map { (label: nil, value: $0) }\n return Mirror(self, children: c)\n }\n}\n\npublic struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray {\n fileprivate let type: Type\n fileprivate let function: Function\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { Int(type.bridged.getNumNominalFields()) }\n\n public subscript(_ index: Int) -> Type {\n type.bridged.getFieldType(index, function.bridged).type\n }\n\n public func getIndexOfField(withName name: String) -> Int? {\n let idx = name._withBridgedStringRef {\n type.bridged.getFieldIdxOfNominalType($0)\n }\n return idx >= 0 ? idx : nil\n }\n\n public func getNameOfField(withIndex idx: Int) -> StringRef {\n StringRef(bridged: type.bridged.getFieldName(idx))\n }\n}\n\npublic struct EnumCase {\n public let payload: Type?\n public let index: Int\n}\n\npublic struct EnumCases : CollectionLikeSequence, IteratorProtocol {\n fileprivate let enumType: Type\n fileprivate let function: Function\n private var caseIterator: BridgedType.EnumElementIterator\n private var caseIndex = 0\n\n fileprivate init(enumType: Type, function: Function) {\n self.enumType = enumType\n self.function = function\n self.caseIterator = enumType.bridged.getFirstEnumCaseIterator()\n }\n\n public mutating func next() -> EnumCase? {\n if !enumType.bridged.isEndCaseIterator(caseIterator) {\n defer {\n caseIterator = caseIterator.getNext()\n caseIndex += 1\n }\n return EnumCase(payload: enumType.bridged.getEnumCasePayload(caseIterator, function.bridged).typeOrNil,\n index: caseIndex)\n }\n return nil\n }\n}\n\npublic struct TupleElementArray : RandomAccessCollection, FormattedLikeArray {\n fileprivate let type: Type\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { Int(type.bridged.getNumTupleElements()) }\n\n public subscript(_ index: Int) -> Type {\n type.bridged.getTupleElementType(index).type\n }\n}\n\npublic struct BoxFieldsArray : RandomAccessCollection, FormattedLikeArray {\n fileprivate let type: Type\n fileprivate let function: Function\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { Int(type.bridged.getNumBoxFields()) }\n\n public subscript(_ index: Int) -> Type {\n type.bridged.getBoxFieldType(index, function.bridged).type\n }\n}\n\nextension Type: DiagnosticArgument {\n public func _withBridgedDiagnosticArgument(_ fn: (BridgedDiagnosticArgument) -> Void) {\n rawType._withBridgedDiagnosticArgument(fn)\n }\n}\n\nextension BridgedType {\n public var type: Type { Type(bridged: self) }\n var typeOrNil: Type? { isNull() ? nil : type }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Type.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Type.swift
Swift
11,113
0.95
0.239617
0.184314
react-lib
554
2023-11-22T23:11:00.066646
GPL-3.0
false
8fd4f0b2323ccc44c7d8623a53bd24b7
//===--- AccessUtils.swift - Utilities for analyzing memory accesses ------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// This file provides a set of utilities for analyzing memory accesses.\n// It defines the following concepts\n// - `AccessBase`: represents the base address of a memory access.\n// - `AccessPath`: a pair of an `AccessBase` and `SmallProjectionPath` with the\n// the path describing the specific address (in terms of projections) of the\n// access.\n// - Access storage path (which is of type `ProjectedValue`): identifies the\n// reference (or a value which contains a reference) an address originates from.\n//\n// The snippet below shows the relationship between the access concepts.\n// ```\n// %ref = struct_extract %value, #f1 access storage path\n// %base = ref_element_addr %ref, #f2 AccessBase AccessPath |\n// %scope = begin_access %base AccessScope | |\n// %t = tuple_element_addr %scope, 0 | |\n// %s = struct_element_addr %t, #f3 v v\n// %l = load %s the access\n// ```\n//===----------------------------------------------------------------------===//\n\n/// AccessBase describes the base address of a memory access (e.g. of a `load` or `store``).\n/// The "base address" is defined as the address which is obtained from the access address by\n/// looking through all address projections.\n/// This means that the base address is either the same as the access address or:\n/// the access address is a chain of address projections of the base address.\n/// The following snippets show examples of memory accesses and their respective bases.\n///\n/// ```\n/// %base1 = ref_element_addr %ref, #Obj.field // A `class` base\n/// %base2 = alloc_stack $S // A `stack` base\n/// %base3 = global_addr @gaddr // A `global` base\n/// %addr1 = struct_element_addr %base1\n/// %access1 = store %v1 to [trivial] %addr1 // accessed address is offset from base\n/// %access2 = store %v2 to [trivial] %base2 // accessed address is base itself\n/// ```\n///\n/// The base address is never inside an access scope.\npublic enum AccessBase : CustomStringConvertible, Hashable {\n\n /// The address of a boxed variable, i.e. a field of an `alloc_box`.\n case box(ProjectBoxInst)\n \n /// The address of a stack-allocated value, i.e. an `alloc_stack`\n case stack(AllocStackInst)\n \n /// The address of a global variable.\n ///\n /// TODO: make this payload the global address. Make AccessBase.address non-optional. Make AccessBase comparison see\n /// though things like project_box and global_addr. Then cleanup APIs like LifetimeDependence.Scope that carry extra\n /// address values around.\n case global(GlobalVariable)\n \n /// The address of a stored property of a class instance.\n case `class`(RefElementAddrInst)\n \n /// The base address of the tail allocated elements of a class instance.\n case tail(RefTailAddrInst)\n\n /// An indirect function argument, like `@inout`.\n case argument(FunctionArgument)\n \n /// An indirect result of a `begin_apply`.\n case yield(MultipleValueInstructionResult)\n\n /// store_borrow is never the base of a formal access, but calling Value.enclosingScope on an arbitrary address will\n /// return it as the accessBase. A store_borrow always stores into an alloc_stack, but it is handled separately\n /// because it may be useful for clients to know which value was stored in the temporary stack location for the\n /// duration of this borrow scope.\n case storeBorrow(StoreBorrowInst)\n\n /// An address which is derived from a `Builtin.RawPointer`.\n case pointer(PointerToAddressInst)\n\n // The result of an `index_addr` with a non-constant index.\n // This can only occur in access paths returned by `Value.constantAccessPath`.\n // In "regular" access paths such `index_addr` projections are contained in the `projectionPath` (`i*`).\n case index(IndexAddrInst)\n\n /// The access base is some SIL pattern which does not fit into any other case.\n /// This should be a very rare situation.\n ///\n /// TODO: unidentified should preserve its base address value, but AccessBase must be Hashable.\n case unidentified\n\n public init(baseAddress: Value) {\n switch baseAddress {\n case let rea as RefElementAddrInst : self = .class(rea)\n case let rta as RefTailAddrInst : self = .tail(rta)\n case let pbi as ProjectBoxInst : self = .box(pbi)\n case let asi as AllocStackInst : self = .stack(asi)\n case let arg as FunctionArgument : self = .argument(arg)\n case let ga as GlobalAddrInst : self = .global(ga.global)\n case let mvr as MultipleValueInstructionResult:\n if mvr.parentInstruction is BeginApplyInst && baseAddress.type.isAddress {\n self = .yield(mvr)\n } else {\n self = .unidentified\n }\n case let sb as StoreBorrowInst:\n self = .storeBorrow(sb)\n case let p2a as PointerToAddressInst:\n if let global = p2a.resultOfGlobalAddressorCall {\n self = .global(global)\n } else {\n self = .pointer(p2a)\n }\n default:\n self = .unidentified\n }\n }\n\n /// Return 'nil' for global varabiables and unidentified addresses.\n public var address: Value? {\n switch self {\n case .global, .unidentified: return nil\n case .box(let pbi): return pbi\n case .stack(let asi): return asi\n case .class(let rea): return rea\n case .tail(let rta): return rta\n case .argument(let arg): return arg\n case .yield(let result): return result\n case .storeBorrow(let sb): return sb\n case .pointer(let p): return p\n case .index(let ia): return ia\n }\n }\n\n public var description: String {\n switch self {\n case .unidentified: return "?"\n case .box(let pbi): return "box - \(pbi)"\n case .stack(let asi): return "stack - \(asi)"\n case .global(let gl): return "global - @\(gl.name)"\n case .class(let rea): return "class - \(rea)"\n case .tail(let rta): return "tail - \(rta.instance)"\n case .argument(let arg): return "argument - \(arg)"\n case .yield(let result): return "yield - \(result)"\n case .storeBorrow(let sb): return "storeBorrow - \(sb)"\n case .pointer(let p): return "pointer - \(p)"\n case .index(let ia): return "index - \(ia)"\n }\n }\n\n /// True, if this is an access to a class instance.\n public var isObjectAccess: Bool {\n switch self {\n case .class, .tail:\n return true\n case .box, .stack, .global, .argument, .yield, .storeBorrow, .pointer, .index, .unidentified:\n return false\n }\n }\n\n /// The reference value if this is an access to a referenced object (class, box, tail).\n public var reference: Value? {\n switch self {\n case .box(let pbi): return pbi.box\n case .class(let rea): return rea.instance\n case .tail(let rta): return rta.instance\n case .stack, .global, .argument, .yield, .storeBorrow, .pointer, .index, .unidentified:\n return nil\n }\n }\n\n /// True if this access base may be derived from a reference that is only valid within a locally\n /// scoped OSSA lifetime. For example:\n ///\n /// %reference = begin_borrow %1\n /// %base = ref_tail_addr %reference <- %base must not be used outside the borrow scope\n /// end_borrow %reference\n ///\n /// This is not true for scoped storage such as alloc_stack and @in arguments.\n ///\n public var hasLocalOwnershipLifetime: Bool {\n if let reference = reference {\n // Conservatively assume that everything which is a ref-counted object is within an ownership scope.\n // TODO: we could e.g. exclude guaranteed function arguments.\n return reference.ownership != .none\n }\n return false\n }\n\n /// True, if the baseAddress is of an immutable property or global variable\n public var isLet: Bool {\n switch self {\n case .class(let rea): return rea.fieldIsLet\n case .global(let g): return g.isLet\n case .box, .stack, .tail, .argument, .yield, .storeBorrow, .pointer, .index, .unidentified:\n return false\n }\n }\n\n /// True, if the address is produced by an allocation in its function.\n public var isLocal: Bool {\n switch self {\n case .box(let pbi): return pbi.box.referenceRoot is AllocBoxInst\n case .class(let rea): return rea.instance.referenceRoot is AllocRefInstBase\n case .tail(let rta): return rta.instance.referenceRoot is AllocRefInstBase\n case .stack, .storeBorrow: return true\n case .global, .argument, .yield, .pointer, .index, .unidentified:\n return false\n }\n }\n\n /// True, if the kind of storage of the access is known (e.g. a class property, or global variable).\n public var hasKnownStorageKind: Bool {\n switch self {\n case .box, .class, .tail, .stack, .storeBorrow, .global:\n return true\n case .argument, .yield, .pointer, .index, .unidentified:\n return false\n }\n }\n\n /// Returns true if it's guaranteed that this access has the same base address as the `other` access.\n ///\n /// `isEqual` abstracts away the projection instructions that are included as part of the AccessBase:\n /// multiple `project_box` and `ref_element_addr` instructions are equivalent bases as long as they\n /// refer to the same variable or class property.\n public func isEqual(to other: AccessBase) -> Bool {\n switch (self, other) {\n case (.box(let pb1), .box(let pb2)):\n return pb1.box.referenceRoot == pb2.box.referenceRoot\n case (.class(let rea1), .class(let rea2)):\n return rea1.fieldIndex == rea2.fieldIndex &&\n rea1.instance.referenceRoot == rea2.instance.referenceRoot\n case (.tail(let rta1), .tail(let rta2)):\n return rta1.instance.referenceRoot == rta2.instance.referenceRoot &&\n rta1.type == rta2.type\n case (.stack(let as1), .stack(let as2)):\n return as1 == as2\n case (.global(let gl1), .global(let gl2)):\n return gl1 == gl2\n case (.argument(let arg1), .argument(let arg2)):\n return arg1 == arg2\n case (.yield(let baResult1), .yield(let baResult2)):\n return baResult1 == baResult2\n case (.storeBorrow(let sb1), .storeBorrow(let sb2)):\n return sb1 == sb2\n case (.pointer(let p1), .pointer(let p2)):\n return p1 == p2\n case (.index(let ia1), .index(let ia2)):\n return ia1 == ia2\n default:\n return false\n }\n }\n\n /// Returns `true` if the two access bases do not alias.\n public func isDistinct(from other: AccessBase) -> Bool {\n\n func isDifferentAllocation(_ lhs: Value, _ rhs: Value) -> Bool {\n switch (lhs, rhs) {\n case (is Allocation, is Allocation):\n return lhs != rhs\n case (is Allocation, is FunctionArgument),\n (is FunctionArgument, is Allocation):\n // A local allocation cannot alias with something passed to the function.\n return true\n default:\n return false\n }\n }\n\n func hasDifferentType(_ lhs: Value, _ rhs: Value) -> Bool {\n return lhs.type != rhs.type &&\n // If the types have unbound generic arguments then we don't know\n // the possible range of the type. A type such as $Array<Int> may\n // alias $Array<T>. Right now we are conservative and we assume\n // that $UnsafeMutablePointer<T> and $Int may alias.\n !lhs.type.hasArchetype && !rhs.type.hasArchetype\n }\n\n func argIsDistinct(_ arg: FunctionArgument, from other: AccessBase) -> Bool {\n if arg.convention.isExclusiveIndirect {\n // Exclusive indirect arguments cannot alias with an address for which we know that it\n // is not derived from that argument (which might be the case for `pointer` and `yield`).\n return other.hasKnownStorageKind\n }\n // Non-exclusive argument still cannot alias with anything allocated locally in the function.\n return other.isLocal\n }\n\n switch (self, other) {\n \n // First handle all pairs of the same kind (except `yield`, `pointer` and `index`).\n case (.box(let pb), .box(let otherPb)):\n return pb.fieldIndex != otherPb.fieldIndex ||\n isDifferentAllocation(pb.box.referenceRoot, otherPb.box.referenceRoot) ||\n hasDifferentType(pb.box, otherPb.box)\n case (.stack(let asi), .stack(let otherAsi)):\n return asi != otherAsi\n case (.global(let global), .global(let otherGlobal)):\n return global != otherGlobal\n case (.class(let rea), .class(let otherRea)):\n return rea.fieldIndex != otherRea.fieldIndex ||\n isDifferentAllocation(rea.instance, otherRea.instance) ||\n hasDifferentType(rea.instance, otherRea.instance)\n case (.tail(let rta), .tail(let otherRta)):\n return isDifferentAllocation(rta.instance, otherRta.instance) ||\n hasDifferentType(rta.instance, otherRta.instance)\n case (.argument(let arg), .argument(let otherArg)):\n return (arg.convention.isExclusiveIndirect || otherArg.convention.isExclusiveIndirect) && arg != otherArg\n \n // Handle arguments vs non-arguments\n case (.argument(let arg), _):\n return argIsDistinct(arg, from: other)\n case (_, .argument(let otherArg)):\n return argIsDistinct(otherArg, from: self)\n\n case (.storeBorrow(let arg), .storeBorrow(let otherArg)):\n return arg.allocStack != otherArg.allocStack\n\n // Handle the special case of store_borrow - alloc_stack, because that would give a false result in the default case.\n case (.storeBorrow(let sbi), .stack(let asi)):\n return sbi.allocStack != asi\n case (.stack(let asi), .storeBorrow(let sbi)):\n return sbi.allocStack != asi\n\n default:\n // As we already handled pairs of the same kind, here we handle pairs with different kinds.\n // Different storage kinds cannot alias, regardless where the storage comes from.\n // E.g. a class property address cannot alias with a global variable address.\n return hasKnownStorageKind && other.hasKnownStorageKind\n }\n }\n}\n\n/// An `AccessPath` is a pair of a `base: AccessBase` and a `projectionPath: Path`\n/// which denotes the offset of the access from the base in terms of projections.\npublic struct AccessPath : CustomStringConvertible, Hashable {\n public let base: AccessBase\n\n /// address projections only\n public let projectionPath: SmallProjectionPath\n\n public static func unidentified() -> AccessPath {\n return AccessPath(base: .unidentified, projectionPath: SmallProjectionPath())\n }\n\n public var description: String {\n "\(projectionPath): \(base)"\n }\n\n public func isDistinct(from other: AccessPath) -> Bool {\n if base.isDistinct(from: other.base) {\n // We can already derived from the bases that there is no alias.\n // No need to look at the projection paths.\n return true\n }\n if base == other.base ||\n (base.hasKnownStorageKind && other.base.hasKnownStorageKind) {\n if !projectionPath.mayOverlap(with: other.projectionPath) {\n return true\n }\n }\n return false\n }\n\n /// Returns true if this access addresses the same memory location as `other` or if `other`\n /// is a sub-field of this access.\n\n /// Note that this access _contains_ `other` if `other` has a _larger_ projection path than this access.\n /// For example:\n /// `%value.s0` contains `%value.s0.s1`\n public func isEqualOrContains(_ other: AccessPath) -> Bool {\n return getProjection(to: other) != nil\n }\n\n public var materializableProjectionPath: SmallProjectionPath? {\n if projectionPath.isMaterializable {\n return projectionPath\n }\n return nil\n }\n\n /// Returns the projection path to `other` if this access path is equal or contains `other`.\n ///\n /// For example,\n /// `%value.s0`.getProjection(to: `%value.s0.s1`)\n /// yields\n /// `s1`\n public func getProjection(to other: AccessPath) -> SmallProjectionPath? {\n if !base.isEqual(to: other.base) {\n return nil\n }\n if let resultPath = projectionPath.subtract(from: other.projectionPath),\n // Indexing is not a projection where the base overlaps the projected address.\n !resultPath.pop().kind.isIndexedElement\n {\n return resultPath\n }\n return nil\n }\n\n /// Like `getProjection`, but also requires that the resulting projection path is materializable.\n public func getMaterializableProjection(to other: AccessPath) -> SmallProjectionPath? {\n if let projectionPath = getProjection(to: other),\n projectionPath.isMaterializable {\n return projectionPath\n }\n return nil\n }\n}\n\nprivate func canBeOperandOfIndexAddr(_ value: Value) -> Bool {\n switch value {\n case is IndexAddrInst, is RefTailAddrInst, is PointerToAddressInst:\n return true\n default:\n return false\n }\n}\n\n/// Tries to identify from which address the pointer operand originates from.\n/// This is useful to identify patterns like\n/// ```\n/// %orig_addr = global_addr @...\n/// %ptr = address_to_pointer %orig_addr\n/// %addr = pointer_to_address %ptr\n/// ```\npublic extension PointerToAddressInst {\n var originatingAddress: Value? {\n\n struct Walker : ValueUseDefWalker {\n let addrType: Type\n var result: Value?\n var walkUpCache = WalkerCache<Path>()\n\n mutating func rootDef(value: Value, path: SmallProjectionPath) -> WalkResult {\n if let atp = value as? AddressToPointerInst {\n if let res = result, atp.address != res {\n return .abortWalk\n }\n\n if addrType != atp.address.type { return .abortWalk }\n if !path.isEmpty { return .abortWalk }\n\n self.result = atp.address\n return .continueWalk\n }\n return .abortWalk\n }\n\n mutating func walkUp(value: Value, path: SmallProjectionPath) -> WalkResult {\n switch value {\n case is Argument, is MarkDependenceInst, is CopyValueInst,\n is StructExtractInst, is TupleExtractInst, is StructInst, is TupleInst, is AddressToPointerInst:\n return walkUpDefault(value: value, path: path)\n default:\n return .abortWalk\n }\n }\n }\n\n var walker = Walker(addrType: type)\n if walker.walkUp(value: pointer, path: SmallProjectionPath()) == .abortWalk {\n return nil\n }\n return walker.result\n }\n\n var resultOfGlobalAddressorCall: GlobalVariable? {\n if isStrict,\n let apply = pointer as? ApplyInst,\n let callee = apply.referencedFunction,\n let global = callee.globalOfGlobalInitFunction\n {\n return global\n }\n return nil\n }\n}\n\n/// TODO: migrate AccessBase to use this instead of GlobalVariable because many utilities need to get back to a\n/// representative SIL Value.\npublic enum GlobalAccessBase {\n case global(GlobalAddrInst)\n case initializer(PointerToAddressInst)\n\n public init?(address: Value) {\n switch address {\n case let ga as GlobalAddrInst:\n self = .global(ga)\n case let p2a as PointerToAddressInst where p2a.resultOfGlobalAddressorCall != nil:\n self = .initializer(p2a)\n default:\n return nil\n }\n }\n\n public var address: Value {\n switch self {\n case let .global(ga):\n return ga\n case let .initializer(p2a):\n return p2a\n }\n }\n}\n\n/// The `EnclosingAccessScope` of an access is the innermost `begin_access`\n/// instruction that checks for exclusivity of the access.\n/// If there is no `begin_access` instruction found, then the scope is\n/// the base itself.\n///\n/// The access scopes for the snippet below are:\n/// (l1, .base(%addr)), (l2, .scope(%a2)), (l3, .scope(%a3))\n///\n/// ````\n/// %addr = ... : $*Int64\n/// %l1 = load %addr : $*Int64\n/// %a1 = begin_access [read] [dynamic] %addr : $*Int64\n/// %a2 = begin_access [read] [dynamic] %addr : $*Int64\n/// %l2 = load %a2 : $*Int64\n/// end_access %a2 : $*Int64\n/// end_access %a1 : $*Int64\n/// %a3 = begin_access [read] [dynamic] [no_nested_conflict] %addr : $*Int64\n/// %l3 = load %a3 : $*Int64\n/// end_access %a3 : $*Int64\n/// ```\npublic enum EnclosingAccessScope {\n case access(BeginAccessInst)\n case base(AccessBase)\n case dependence(MarkDependenceInst)\n\n // TODO: make this non-optional after fixing AccessBase.global.\n public var address: Value? {\n switch self {\n case let .access(beginAccess):\n return beginAccess\n case let .base(accessBase):\n return accessBase.address\n case let .dependence(markDep):\n return markDep\n }\n }\n}\n\n// An AccessBase with the nested enclosing scopes that contain the original address in bottom-up order.\npublic struct AccessBaseAndScopes {\n public let base: AccessBase\n public let scopes: SingleInlineArray<EnclosingAccessScope>\n\n public init(base: AccessBase, scopes: SingleInlineArray<EnclosingAccessScope>) {\n self.base = base\n self.scopes = scopes\n }\n\n public var enclosingAccess: EnclosingAccessScope {\n return scopes.first ?? .base(base)\n }\n\n public var innermostAccess: BeginAccessInst? {\n for scope in scopes {\n if case let .access(beginAccess) = scope {\n return beginAccess\n }\n }\n return nil\n }\n}\n\nextension AccessBaseAndScopes {\n // This must return false if a mark_dependence scope is present.\n public var isOnlyReadAccess: Bool {\n scopes.allSatisfy(\n {\n if case let .access(beginAccess) = $0 {\n return beginAccess.accessKind == .read\n }\n // preserve any dependence scopes.\n return false\n })\n }\n}\n\nextension BeginAccessInst {\n // Recognize an access scope for a unsafe addressor:\n // %adr = pointer_to_address\n // %md = mark_dependence %adr\n // begin_access [unsafe] %md\n public var unsafeAddressorSelf: Value? {\n guard self.isUnsafe else {\n return nil\n }\n switch self.address.enclosingAccessScope {\n case .access, .base:\n return nil\n case let .dependence(markDep):\n switch markDep.value.enclosingAccessScope {\n case .access, .dependence:\n return nil\n case let .base(accessBase):\n guard case .pointer = accessBase else {\n return nil\n }\n return markDep.base\n }\n }\n }\n}\n\nprivate struct EnclosingAccessWalker : AddressUseDefWalker {\n var enclosingScope: EnclosingAccessScope?\n\n mutating func walk(startAt address: Value, initialPath: UnusedWalkingPath = UnusedWalkingPath()) {\n if walkUp(address: address, path: UnusedWalkingPath()) == .abortWalk {\n assert(enclosingScope == nil, "shouldn't have set an enclosing scope in an aborted walk")\n }\n }\n\n mutating func rootDef(address: Value, path: UnusedWalkingPath) -> WalkResult {\n assert(enclosingScope == nil, "rootDef should only called once")\n // Try identifying the address a pointer originates from\n if let p2ai = address as? PointerToAddressInst, let originatingAddr = p2ai.originatingAddress {\n return walkUp(address: originatingAddr, path: path)\n }\n enclosingScope = .base(AccessBase(baseAddress: address))\n return .continueWalk\n }\n\n mutating func walkUp(address: Value, path: UnusedWalkingPath) -> WalkResult {\n switch address {\n case let ba as BeginAccessInst:\n enclosingScope = .access(ba)\n return .continueWalk\n case let md as MarkDependenceInst:\n enclosingScope = .dependence(md)\n return .continueWalk\n default:\n return walkUpDefault(address: address, path: path)\n }\n }\n}\n\nprivate struct AccessPathWalker : AddressUseDefWalker {\n var result = AccessPath.unidentified()\n\n // List of nested BeginAccessInst & MarkDependenceInst: inside-out order.\n var foundEnclosingScopes = SingleInlineArray<EnclosingAccessScope>()\n\n let enforceConstantProjectionPath: Bool\n\n init(enforceConstantProjectionPath: Bool = false) {\n self.enforceConstantProjectionPath = enforceConstantProjectionPath\n }\n\n mutating func walk(startAt address: Value, initialPath: SmallProjectionPath = SmallProjectionPath()) {\n if walkUp(address: address, path: Path(projectionPath: initialPath)) == .abortWalk {\n assert(result.base == .unidentified,\n "shouldn't have set an access base in an aborted walk")\n }\n }\n\n struct Path : SmallProjectionWalkingPath {\n let projectionPath: SmallProjectionPath\n\n // Tracks whether an `index_addr` instruction was crossed.\n // It should be (FIXME: check if it's enforced) that operands\n // of `index_addr` must be `tail_addr` or other `index_addr` results.\n let indexAddr: Bool\n\n init(projectionPath: SmallProjectionPath = SmallProjectionPath(), indexAddr: Bool = false) {\n self.projectionPath = projectionPath\n self.indexAddr = indexAddr\n }\n\n func with(projectionPath: SmallProjectionPath) -> Self {\n return Self(projectionPath: projectionPath, indexAddr: indexAddr)\n }\n\n func with(indexAddr: Bool) -> Self {\n return Self(projectionPath: projectionPath, indexAddr: indexAddr)\n }\n\n func merge(with other: Self) -> Self {\n return Self(\n projectionPath: projectionPath.merge(with: other.projectionPath),\n indexAddr: indexAddr || other.indexAddr\n )\n }\n }\n\n mutating func rootDef(address: Value, path: Path) -> WalkResult {\n assert(result.base == .unidentified, "rootDef should only called once")\n // Try identifying the address a pointer originates from\n if let p2ai = address as? PointerToAddressInst, let originatingAddr = p2ai.originatingAddress {\n return walkUp(address: originatingAddr, path: path)\n }\n let base = AccessBase(baseAddress: address)\n self.result = AccessPath(base: base, projectionPath: path.projectionPath)\n return .continueWalk\n }\n\n mutating func walkUp(address: Value, path: Path) -> WalkResult {\n if let indexAddr = address as? IndexAddrInst {\n if !(indexAddr.index is IntegerLiteralInst) && enforceConstantProjectionPath {\n self.result = AccessPath(base: .index(indexAddr), projectionPath: path.projectionPath)\n return .continueWalk\n }\n // Track that we crossed an `index_addr` during the walk-up\n return walkUpDefault(address: indexAddr, path: path.with(indexAddr: true))\n } else if path.indexAddr && !canBeOperandOfIndexAddr(address) {\n // An `index_addr` instruction cannot be derived from an address\n // projection. Bail out\n return .abortWalk\n } else if let ba = address as? BeginAccessInst {\n foundEnclosingScopes.push(.access(ba))\n } else if let md = address as? MarkDependenceInst {\n foundEnclosingScopes.push(.dependence(md))\n }\n return walkUpDefault(address: address, path: path.with(indexAddr: false))\n }\n}\n\nextension Value {\n // Convenient properties to avoid instantiating an explicit AccessPathWalker.\n //\n // Although an AccessPathWalker is created for each call of these properties,\n // it's very unlikely that this will end up in memory allocations.\n // Only in the rare case of `pointer_to_address` -> `address_to_pointer` pairs, which\n // go through phi-arguments, the AccessPathWalker will allocate memnory in its cache.\n\n /// Computes the access base of this address value.\n public var accessBase: AccessBase { accessPath.base }\n\n /// Computes the access path of this address value.\n public var accessPath: AccessPath {\n var walker = AccessPathWalker()\n walker.walk(startAt: self)\n return walker.result\n }\n\n /// Like `accessPath`, but ensures that the projectionPath only contains "constant" elements.\n /// This means: if the access contains an `index_addr` projection with a non-constant index,\n /// the `projectionPath` does _not_ contain the `index_addr`.\n /// Instead, the `base` is an `AccessBase.index` which refers to the `index_addr`.\n /// For example:\n /// ```\n /// %1 = ref_tail_addr %some_reference\n /// %2 = index_addr %1, %some_non_const_value\n /// %3 = struct_element_addr %2, #field2\n /// ```\n /// `%3.accessPath` = base: tail(`%1`), projectionPath: `i*.s2`\n /// `%3.constantAccessPath` = base: index(`%2`), projectionPath: `s2`\n ///\n public var constantAccessPath: AccessPath {\n var walker = AccessPathWalker(enforceConstantProjectionPath: true)\n walker.walk(startAt: self)\n return walker.result\n }\n\n public func getAccessPath(fromInitialPath: SmallProjectionPath) -> AccessPath {\n var walker = AccessPathWalker()\n walker.walk(startAt: self, initialPath: fromInitialPath)\n return walker.result\n }\n\n /// Computes the access path of this address value and also returns the scope.\n public var accessPathWithScope: (AccessPath, scope: BeginAccessInst?) {\n var walker = AccessPathWalker()\n walker.walk(startAt: self)\n let baseAndScopes = AccessBaseAndScopes(base: walker.result.base, scopes: walker.foundEnclosingScopes)\n return (walker.result, baseAndScopes.innermostAccess)\n }\n\n /// Computes the enclosing access scope of this address value.\n public var enclosingAccessScope: EnclosingAccessScope {\n var walker = EnclosingAccessWalker()\n walker.walk(startAt: self)\n return walker.enclosingScope ?? .base(.unidentified)\n }\n\n public var accessBaseWithScopes: AccessBaseAndScopes {\n var walker = AccessPathWalker()\n walker.walk(startAt: self)\n return AccessBaseAndScopes(base: walker.result.base, scopes: walker.foundEnclosingScopes)\n }\n\n /// The root definition of a reference, obtained by skipping ownership forwarding and ownership transition.\n public var referenceRoot: Value {\n var value: Value = self\n while true {\n if let forward = value.forwardingInstruction, forward.preservesIdentity,\n let operand = forward.singleForwardedOperand {\n value = operand.value\n continue\n }\n if let transition = value.definingInstruction as? OwnershipTransitionInstruction {\n value = transition.operand.value\n continue\n }\n return value\n }\n }\n}\n\n/// A ValueUseDef walker that that visits access storage paths of an address.\n///\n/// An access storage path is the reference (or a value which contains a reference)\n/// an address originates from.\n/// In the following example the `storage` is `contains_ref` with `path` `"s0.c0.s0"`\n/// ```\n/// %ref = struct_extract %contains_ref : $S, #S.l\n/// %base = ref_element_addr %ref : $List, #List.x\n/// %addr = struct_element_addr %base : $X, #X.e\n/// store %v to [trivial] %addr : $*Int\n/// ```\n///\n/// Warning: This does not find the correct storage root of the\n/// lifetime of an object projection, such as .box or .class because\n/// ValueUseDefWalker ignores ownership and, for example, walks past copies.\nextension ValueUseDefWalker where Path == SmallProjectionPath {\n /// The main entry point.\n /// Given an `accessPath` where the access base is a reference (class, tail, box), call\n /// the `visit` function for all storage roots with a the corresponding path.\n /// Returns true on success.\n /// Returns false if not all storage roots could be identified or if `accessPath` has not a "reference" base.\n public mutating func visitAccessStorageRoots(of accessPath: AccessPath) -> Bool {\n walkUpCache.clear()\n let path = accessPath.projectionPath\n switch accessPath.base {\n case .box(let pbi):\n return walkUp(value: pbi.box, path: path.push(.classField, index: pbi.fieldIndex)) != .abortWalk\n case .class(let rea):\n return walkUp(value: rea.instance, path: path.push(.classField, index: rea.fieldIndex)) != .abortWalk\n case .tail(let rta):\n return walkUp(value: rta.instance, path: path.push(.tailElements, index: 0)) != .abortWalk\n case .stack, .global, .argument, .yield, .storeBorrow, .pointer, .index, .unidentified:\n return false\n }\n }\n}\n\nextension Function {\n public var globalOfGlobalInitFunction: GlobalVariable? {\n if isGlobalInitFunction,\n let ret = returnInstruction,\n let atp = ret.returnedValue as? AddressToPointerInst,\n let ga = atp.address as? GlobalAddrInst {\n return ga.global\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_AccessUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_AccessUtils.swift
Swift
32,417
0.95
0.136523
0.280313
vue-tools
517
2024-05-12T02:00:58.614699
BSD-3-Clause
false
bdc93aa66cb84fef9bfc9d050338b2ac
//===--- SequenceUtilities.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\n\n/// Types conforming to `HasName` will be displayed by their name (instead of the\n/// full object) in collection descriptions.\n///\n/// This is useful to make collections, e.g. of BasicBlocks or Functions, readable.\npublic protocol HasShortDescription {\n var shortDescription: String { get }\n}\n\nprivate struct CustomMirrorChild : CustomStringConvertible, NoReflectionChildren {\n public var description: String\n \n public init(description: String) { self.description = description }\n}\n\n/// Makes a Sequence's `description` and `customMirror` formatted like Array, e.g. [a, b, c].\npublic protocol FormattedLikeArray : Sequence, CustomStringConvertible, CustomReflectable {\n}\n\nextension FormattedLikeArray {\n /// Display a Sequence in an array like format, e.g. [a, b, c]\n public var description: String {\n "[" + map {\n if let named = $0 as? HasShortDescription {\n return named.shortDescription\n }\n return String(describing: $0)\n }.joined(separator: ", ") + "]"\n }\n \n /// The mirror which adds the children of a Sequence, similar to `Array`.\n public var customMirror: Mirror {\n // If the one-line description is not too large, print that instead of the\n // children in separate lines.\n if description.count <= 80 {\n return Mirror(self, children: [])\n }\n let c: [Mirror.Child] = map {\n let val: Any\n if let named = $0 as? HasShortDescription {\n val = CustomMirrorChild(description: named.shortDescription)\n } else {\n val = $0\n }\n return (label: nil, value: val)\n }\n return Mirror(self, children: c, displayStyle: .collection)\n }\n}\n\n/// A Sequence which is not consuming and therefore behaves like a Collection.\n///\n/// Many sequences in SIL and the optimizer should be collections but cannot\n/// because their Index cannot conform to Comparable. Those sequences conform\n/// to CollectionLikeSequence.\n///\n/// For convenience it also inherits from FormattedLikeArray.\npublic protocol CollectionLikeSequence : FormattedLikeArray {\n}\n\npublic extension Sequence {\n var isEmpty: Bool { !contains(where: { _ in true }) }\n\n var singleElement: Element? {\n var singleElement: Element? = nil\n for e in self {\n if singleElement != nil {\n return nil\n }\n singleElement = e\n }\n return singleElement\n }\n\n var first: Element? { first(where: { _ in true }) }\n}\n\n// Also make the lazy sequences a CollectionLikeSequence if the underlying sequence is one.\n\nextension LazySequence : /*@retroactive*/ SIL.CollectionLikeSequence,\n /*@retroactive*/ SIL.FormattedLikeArray,\n /*@retroactive*/ Swift.CustomStringConvertible,\n /*@retroactive*/ Swift.CustomReflectable\n where Base: CollectionLikeSequence {}\n\nextension FlattenSequence : /*@retroactive*/ SIL.CollectionLikeSequence,\n /*@retroactive*/ SIL.FormattedLikeArray,\n /*@retroactive*/ Swift.CustomStringConvertible,\n /*@retroactive*/ Swift.CustomReflectable\n where Base: CollectionLikeSequence {}\n\nextension LazyMapSequence : /*@retroactive*/ SIL.CollectionLikeSequence,\n /*@retroactive*/ SIL.FormattedLikeArray,\n /*@retroactive*/ Swift.CustomStringConvertible,\n /*@retroactive*/ Swift.CustomReflectable\n where Base: CollectionLikeSequence {}\n\nextension LazyFilterSequence : /*@retroactive*/ SIL.CollectionLikeSequence,\n /*@retroactive*/ SIL.FormattedLikeArray,\n /*@retroactive*/ Swift.CustomStringConvertible,\n /*@retroactive*/ Swift.CustomReflectable\n where Base: CollectionLikeSequence {}\n\n//===----------------------------------------------------------------------===//\n// Single-Element Inline Array\n//===----------------------------------------------------------------------===//\n\npublic struct SingleInlineArray<Element>: RandomAccessCollection, FormattedLikeArray {\n public var singleElement: Element?\n private var multipleElements: [Element] = []\n\n public init() {}\n\n public init(element: Element) {\n singleElement = element\n }\n\n public var startIndex: Int { 0 }\n public var endIndex: Int {\n singleElement == nil ? 0 : multipleElements.count + 1\n }\n\n public subscript(_ index: Int) -> Element {\n _read {\n if index == 0 {\n yield singleElement!\n } else {\n yield multipleElements[index - 1]\n }\n }\n _modify {\n if index == 0 {\n yield &singleElement!\n } else {\n yield &multipleElements[index - 1]\n }\n }\n }\n\n public mutating func append(_ element: __owned Element) {\n push(element)\n }\n\n public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element {\n for element in newElements {\n push(element)\n }\n }\n\n public mutating func push(_ element: __owned Element) {\n guard singleElement != nil else {\n singleElement = element\n return\n }\n multipleElements.append(element)\n }\n\n public mutating func popLast() -> Element? {\n if multipleElements.isEmpty {\n let last = singleElement\n singleElement = nil\n return last\n }\n return multipleElements.popLast()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_SequenceUtilities.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_SequenceUtilities.swift
Swift
5,995
0.95
0.067039
0.281046
awesome-app
242
2023-09-14T15:11:17.774888
GPL-3.0
false
9a0e93a4a18307e9b24dbc6131730a89
//===--- SmallProjectionPath.swift - a path of projections ----------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\n\n// Needed to make some important utility functions in `Basic` available to importers of `SIL`.\n// For example, let `Basic.assert` be used in Optimizer module.\n@_exported import Basic\n\n/// A small and very efficient representation of a projection path.\n///\n/// A `SmallProjectionPath` can be parsed and printed in SIL syntax and parsed from Swift\n/// source code - the SIL syntax is more compact than the Swift syntax.\n/// In the following, we use the SIL syntax for the examples.\n///\n/// The `SmallProjectionPath` represents a path of value or address projections.\n/// For example, the projection path which represents\n///\n/// %t = struct_extract %s: $Str, #Str.tupleField // first field in Str\n/// %c = tuple_extract %f : $(Int, Class), 4\n/// %r = ref_element_addr %c $Class, #Class.classField // 3rd field in Class\n///\n/// is `s0.4.c2`, where `s0` is the first path component and `c2` is the last component.\n///\n/// A `SmallProjectionPath` can be a concrete path (like the example above): it only\n/// contains concrete field elements, e.g. `s0.c2.e1`\n/// Or it can be a pattern path, where one or more path components are wild cards, e.g.\n/// `v**.c*` means: any number of value projections (struct, enum, tuple) followed by\n/// a single class field projection.\n///\n/// Internally, a `SmallProjectionPath` is represented as a single 64-bit word.\n/// This is very efficient, but it also means that a path cannot exceed a certain length.\n/// If too many projections are pushed onto a path, the path is converted to a `**` wildcard,\n/// which means: it represents any number of any kind of projections.\n/// Though, it's very unlikely that the limit will be reached in real world scenarios.\n///\npublic struct SmallProjectionPath : Hashable, CustomStringConvertible, NoReflectionChildren {\n\n /// The physical representation of the path. The path components are stored in\n /// reverse order: the first path component is stored in the lowest bits (LSB),\n /// the last component is stored in the highest bits (MSB).\n /// Each path component consists of zero or more "index-overflow" bytes followed\n /// by the "index-kind" main byte (from LSB to MSB).\n ///\n /// index overflow byte: bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n /// +---+---+---+---+---+---+---+---+\n /// content: | index high bits | 1 |\n ///\n /// main byte (small kind): bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n /// +---+---+---+---+---+---+---+---+\n /// content: | index low bits| kind | 0 |\n ///\n /// "Large" kind values (>= 0x7) don't have an associated index and the main\n /// byte looks like:\n ///\n /// main byte (large kind): bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n /// +---+---+---+---+---+---+---+---+\n /// content: | kind high bits| 1 | 1 | 1 | 0 |\n ///\n private let bytes: UInt64\n\n // TODO: add better support for tail elements by tracking the\n // index of `index_addr` instructions.\n public enum FieldKind : Int {\n case root = 0x0 // The pseudo component denoting the end of the path.\n case structField = 0x1 // A concrete struct field: syntax e.g. `s3`\n case tupleField = 0x2 // A concrete tuple element: syntax e.g. `2`\n case enumCase = 0x3 // A concrete enum case (with payload): syntax e.g. `e4'\n case classField = 0x4 // A concrete class field: syntax e.g. `c1`\n case indexedElement = 0x5 // A constant offset into an array of elements: syntax e.g. 'i2'\n // The index must be greater than 0 and there must not be two successive element indices in the path.\n\n // "Large" kinds: starting from here the low 3 bits must be 1.\n // This and all following kinds (we'll add in the future) cannot have a field index.\n case tailElements = 0x07 // (0 << 3) | 0x7 A tail allocated element of a class: syntax `ct`\n case existential = 0x0f // (1 << 3) | 0x7 A concrete value projected out of an existential: synatx 'x'\n case anyClassField = 0x17 // (2 << 3) | 0x7 Any class field, including tail elements: syntax `c*`\n case anyIndexedElement = 0x1f // (3 << 3) | 0x7 An unknown offset into an array of elements.\n // There must not be two successive element indices in the path.\n case anyValueFields = 0x27 // (4 << 3) | 0x7 Any number of any value fields (struct, tuple, enum): syntax `v**`\n case anything = 0x2f // (5 << 3) | 0x7 Any number of any fields: syntax `**`\n\n public var isValueField: Bool {\n switch self {\n case .anyValueFields, .structField, .tupleField, .enumCase, .indexedElement, .anyIndexedElement, .existential:\n return true\n case .root, .anything, .anyClassField, .classField, .tailElements:\n return false\n }\n }\n \n public var isClassField: Bool {\n switch self {\n case .anyClassField, .classField, .tailElements:\n return true\n case .root, .anything, .anyValueFields, .structField, .tupleField, .enumCase, .indexedElement, .anyIndexedElement, .existential:\n return false\n }\n }\n\n public var isIndexedElement: Bool {\n switch self {\n case .anyIndexedElement, .indexedElement:\n return true\n default:\n return false\n }\n }\n }\n\n public init() { self.bytes = 0 }\n\n /// Creates a new path with an initial element.\n public init(_ kind: FieldKind, index: Int = 0) {\n self = Self().push(kind, index: index)\n }\n\n private init(bytes: UInt64) { self.bytes = bytes }\n\n public var isEmpty: Bool { bytes == 0 }\n\n public var description: String {\n let (kind, idx, sp) = pop()\n let subPath = sp\n let s: String\n switch kind {\n case .root: return ""\n case .structField: s = "s\(idx)"\n case .tupleField: s = "\(idx)"\n case .enumCase: s = "e\(idx)"\n case .classField: s = "c\(idx)"\n case .tailElements: s = "ct"\n case .existential: s = "x"\n case .indexedElement: s = "i\(idx)"\n case .anyIndexedElement: s = "i*"\n case .anything: s = "**"\n case .anyValueFields: s = "v**"\n case .anyClassField: s = "c*"\n }\n if subPath.isEmpty {\n return s\n }\n return "\(s).\(subPath)"\n }\n\n /// Returns the top (= the first) path component and the number of its encoding bits.\n private var top: (kind: FieldKind, index: Int, numBits: Int) {\n var idx = 0\n var b = bytes\n var numBits = 0\n \n // Parse any index overflow bytes.\n while (b & 1) == 1 {\n idx = (idx << 7) | Int((b >> 1) & 0x7f)\n b >>= 8\n numBits = numBits &+ 8\n }\n var kindVal = (b >> 1) & 0x7\n if kindVal == 0x7 {\n // A "large" kind - without any index\n kindVal = (b >> 1) & 0x7f\n assert(idx == 0)\n assert(numBits == 0)\n } else {\n // A "small" kind with an index\n idx = (idx << 4) | Int((b >> 4) & 0xf)\n }\n let k = FieldKind(rawValue: Int(kindVal))!\n if k == .anything {\n assert((b >> 8) == 0, "'anything' only allowed in last path component")\n numBits = 8\n } else {\n numBits = numBits &+ 8\n }\n return (k, idx, numBits)\n }\n\n /// Pops \p numBits from the path.\n private func pop(numBits: Int) -> SmallProjectionPath {\n return Self(bytes: bytes &>> numBits)\n }\n\n /// Pops and returns the first path component included the resulting path\n /// after popping.\n ///\n /// For example, popping from `s0.c3.e1` returns (`s`, 0, `c3.e1`)\n public func pop() -> (kind: FieldKind, index: Int, path: SmallProjectionPath) {\n let (k, idx, numBits) = top\n return (k, idx, pop(numBits: numBits))\n }\n\n /// Pushes a new first component to the path and returns the new path.\n ///\n /// For example, pushing `s0` to `c3.e1` returns `s0.c3.e1`.\n public func push(_ kind: FieldKind, index: Int = 0) -> SmallProjectionPath {\n assert(kind != .anything || bytes == 0, "'anything' only allowed in last path component")\n if (kind.isIndexedElement) {\n let (k, i, numBits) = top\n if kind == .indexedElement {\n if index == 0 {\n // Ignore zero indices\n return self\n }\n if k == .indexedElement {\n // "Merge" two constant successive indexed elements\n return pop(numBits: numBits).push(.indexedElement, index: index + i)\n }\n }\n // "Merge" two successive indexed elements which doesn't have a constant result\n if (k.isIndexedElement) {\n return pop(numBits: numBits).push(.anyIndexedElement)\n }\n }\n var idx = index\n var b = bytes\n if (b >> 56) != 0 {\n // Overflow\n return Self(.anything)\n }\n b = (b << 8) | UInt64(((idx & 0xf) << 4) | (kind.rawValue << 1))\n idx >>= 4\n while idx != 0 {\n if (b >> 56) != 0 { return Self(.anything) }\n b = (b << 8) | UInt64(((idx & 0x7f) << 1) | 1)\n idx >>= 7\n }\n return Self(bytes: b)\n }\n\n /// Pops the first path component if it is exactly of kind `kind` - not considering wildcards.\n ///\n /// Returns the index of the component and the new path or - if not matching - returns nil.\n public func pop(kind: FieldKind) -> (index: Int, path: SmallProjectionPath)? {\n let (k, idx, newPath) = pop()\n if k != kind { return nil }\n return (idx, newPath)\n }\n\n /// Pops the first path component if it matches `kind` and (optionally) `index`.\n ///\n /// For example:\n /// popping `s0` from `s0.c3.e1` returns `c3.e1`\n /// popping `c2` from `c*.e1` returns `e1`\n /// popping `s0` from `v**.c3.e1` return `v**.c3.e1` (because `v**` means _any_ number of value fields)\n /// popping `s0` from `c*.e1` returns nil\n ///\n /// Note that if `kind` is a wildcard, also the first path component must be a wildcard to popped.\n /// For example:\n /// popping `v**` from `s0.c1` returns nil\n /// popping `v**` from `v**.c1` returns `v**.c1` (because `v**` means _any_ number of value fields)\n /// popping `c*` from `c0.e3` returns nil\n /// popping `c*` from `c*.e3` returns `e3`\n public func popIfMatches(_ kind: FieldKind, index: Int? = nil) -> SmallProjectionPath? {\n let (k, idx, numBits) = top\n switch k {\n case .anything:\n return self\n case .anyValueFields:\n if kind.isValueField { return self }\n return pop(numBits: numBits).popIfMatches(kind, index: index)\n case .anyClassField:\n if kind.isClassField {\n return pop(numBits: numBits)\n }\n return nil\n case .anyIndexedElement:\n if kind.isIndexedElement {\n return self\n }\n return pop(numBits: numBits).popIfMatches(kind, index: index)\n case kind:\n if let i = index {\n if i != idx { return nil }\n }\n return pop(numBits: numBits)\n default:\n return nil\n }\n }\n\n /// Returns true if the path has at least one class projection.\n /// For example:\n /// returns false for `v**`\n /// returns true for `v**.c0.s1.v**`\n /// returns false for `**` (because '**' can have zero class projections)\n public var hasClassProjection: Bool {\n var p = self\n while true {\n let (k, _, numBits) = p.top\n if k == .root { return false }\n if k.isClassField { return true }\n p = p.pop(numBits: numBits)\n }\n }\n\n /// Returns true if the path may have a class projection.\n /// For example:\n /// returns false for `v**`\n /// returns true for `c0`\n /// returns true for `**` (because '**' can have any number of class projections)\n public var mayHaveClassProjection: Bool {\n return !matches(pattern: Self(.anyValueFields))\n }\n\n /// Returns true if the path may have a class projection.\n /// For example:\n /// returns false for `v**`\n /// returns false for `c0`\n /// returns true for `c0.c1`\n /// returns true for `c0.**` (because '**' can have any number of class projections)\n /// returns true for `**` (because '**' can have any number of class projections)\n public var mayHaveTwoClassProjections: Bool {\n return !matches(pattern: Self(.anyValueFields)) &&\n !matches(pattern: Self(.anyValueFields).push(.anyClassField).push(.anyValueFields))\n }\n\n /// Pops all value field components from the beginning of the path.\n /// For example:\n /// `s0.e2.3.c4.s1` -> `c4.s1`\n /// `v**.c4.s1` -> `c4.s1`\n /// `**` -> `**` (because `**` can also be a class field)\n public func popAllValueFields() -> SmallProjectionPath {\n var p = self\n while true {\n let (k, _, numBits) = p.top\n if !k.isValueField { return p }\n p = p.pop(numBits: numBits)\n }\n }\n\n public func popIndexedElements() -> SmallProjectionPath {\n var p = self\n while true {\n let (k, _, numBits) = p.top\n if !k.isIndexedElement { return p }\n p = p.pop(numBits: numBits)\n }\n }\n\n /// Pops the last class projection and all following value fields from the tail of the path.\n /// For example:\n /// `s0.e2.3.c4.s1` -> `s0.e2.3`\n /// `v**.c1.c4.s1` -> `v**.c1`\n /// `c1.**` -> `c1.**` (because it's unknown how many class projections are in `**`)\n public func popLastClassAndValuesFromTail() -> SmallProjectionPath {\n var p = self\n var totalBits = 0\n var neededBits = 0\n while true {\n let (k, _, numBits) = p.top\n if k == .root { break }\n if k.isClassField {\n neededBits = totalBits\n totalBits += numBits\n } else {\n totalBits += numBits\n if !k.isValueField {\n // k is `anything`\n neededBits = totalBits\n }\n }\n p = p.pop(numBits: numBits)\n }\n if neededBits == 64 { return self }\n return SmallProjectionPath(bytes: bytes & ((1 << neededBits) - 1))\n }\n\n /// Returns true if this path matches a pattern path.\n ///\n /// Formally speaking:\n /// If this path is a concrete path, returns true if it matches the pattern.\n /// If this path is a pattern path itself, returns true if all concrete paths which\n /// match this path also match the pattern path.\n /// For example:\n /// `s0.c3.e1` matches `s0.c3.e1`\n /// `s0.c3.e1` matches `v**.c*.e1`\n /// `v**.c*.e1` does not match `s0.c3.e1`!\n /// Note that matching is not reflexive.\n public func matches(pattern: SmallProjectionPath) -> Bool {\n let (patternKind, patternIdx, subPattern) = pattern.pop()\n switch patternKind {\n case .root: return isEmpty\n case .anything: return true\n case .anyValueFields:\n return popAllValueFields().matches(pattern: subPattern)\n case .anyClassField:\n let (kind, _, subPath) = pop()\n if !kind.isClassField { return false }\n return subPath.matches(pattern: subPattern)\n case .anyIndexedElement:\n return popIndexedElements().matches(pattern: subPattern)\n case .structField, .tupleField, .enumCase, .classField, .tailElements, .indexedElement, .existential:\n let (kind, index, subPath) = pop()\n if kind != patternKind || index != patternIdx { return false }\n return subPath.matches(pattern: subPattern)\n }\n }\n\n /// Returns the merged path of this path and `rhs`.\n ///\n /// Merging means that all paths which match this path and `rhs` will also match the result.\n /// If `rhs` is not equal to this path, the result is computed by replacing\n /// mismatching components by wildcards.\n /// For example:\n /// `s0.c3.e4` merged with `s0.c1.e4` -> `s0.c*.e4`\n /// `s0.s1.c3` merged with `e4.c3` -> `v**.c3`\n /// `s0.c1.c2` merged with `s0.c3` -> `s0.**`\n public func merge(with rhs: SmallProjectionPath) -> SmallProjectionPath {\n if self == rhs { return self }\n \n let (lhsKind, lhsIdx, lhsBits) = top\n let (rhsKind, rhsIdx, rhsBits) = rhs.top\n if lhsKind == rhsKind && lhsIdx == rhsIdx {\n assert(lhsBits == rhsBits)\n let subPath = pop(numBits: lhsBits).merge(with: rhs.pop(numBits: rhsBits))\n if lhsKind == .anyValueFields && subPath.top.kind == .anyValueFields {\n return subPath\n }\n return subPath.push(lhsKind, index: lhsIdx)\n }\n if lhsKind.isIndexedElement || rhsKind.isIndexedElement {\n let subPath = popIndexedElements().merge(with: rhs.popIndexedElements())\n let subPathTopKind = subPath.top.kind\n assert(!subPathTopKind.isIndexedElement)\n if subPathTopKind == .anything || subPathTopKind == .anyValueFields {\n return subPath\n }\n return subPath.push(.anyIndexedElement)\n }\n if lhsKind.isValueField || rhsKind.isValueField {\n let subPath = popAllValueFields().merge(with: rhs.popAllValueFields())\n assert(!subPath.top.kind.isValueField)\n if subPath.top.kind == .anything {\n return subPath\n }\n return subPath.push(.anyValueFields)\n }\n if lhsKind.isClassField && rhsKind.isClassField {\n let subPath = pop(numBits: lhsBits).merge(with: rhs.pop(numBits: rhsBits))\n return subPath.push(.anyClassField)\n }\n return Self(.anything)\n }\n\n /// Returns true if this path may overlap with `rhs`.\n ///\n /// "Overlapping" means that both paths may project the same field.\n /// For example:\n /// `s0.s1` and `s0.s1` overlap (the paths are identical)\n /// `s0.s1` and `s0.s2` don't overlap\n /// `s0.s1` and `s0` overlap (the second path is a sub-path of the first one)\n /// `s0.v**` and `s0.s1` overlap\n public func mayOverlap(with rhs: SmallProjectionPath) -> Bool {\n if isEmpty || rhs.isEmpty {\n return true\n }\n \n let (lhsKind, lhsIdx, lhsBits) = top\n let (rhsKind, rhsIdx, rhsBits) = rhs.top\n \n if lhsKind == .anything || rhsKind == .anything {\n return true\n }\n if lhsKind == .anyIndexedElement || rhsKind == .anyIndexedElement {\n return popIndexedElements().mayOverlap(with: rhs.popIndexedElements())\n }\n if lhsKind == .anyValueFields || rhsKind == .anyValueFields {\n return popAllValueFields().mayOverlap(with: rhs.popAllValueFields())\n }\n if (lhsKind == rhsKind && lhsIdx == rhsIdx) ||\n (lhsKind == .anyClassField && rhsKind.isClassField) ||\n (lhsKind.isClassField && rhsKind == .anyClassField) {\n return pop(numBits: lhsBits).mayOverlap(with: rhs.pop(numBits: rhsBits))\n }\n return false\n }\n\n /// Subtracts this path from a larger path if this path is a prefix of the other path.\n ///\n /// For example:\n /// subtracting `s0` from `s0.s1` yields `s1`\n /// subtracting `s0` from `s1` yields nil, because `s0` is not a prefix of `s1`\n /// subtracting `s0.s1` from `s0.s1` yields an empty path\n /// subtracting `i*.s1` from `i*.s1` yields nil, because the actual index is unknown on both sides\n public func subtract(from rhs: SmallProjectionPath) -> SmallProjectionPath? {\n let (lhsKind, lhsIdx, lhsBits) = top\n switch lhsKind {\n case .root:\n return rhs\n case .classField, .tailElements, .structField, .tupleField, .enumCase, .existential, .indexedElement:\n let (rhsKind, rhsIdx, rhsBits) = rhs.top\n if lhsKind == rhsKind && lhsIdx == rhsIdx {\n return pop(numBits: lhsBits).subtract(from: rhs.pop(numBits: rhsBits))\n }\n return nil\n case .anything, .anyValueFields, .anyClassField, .anyIndexedElement:\n return nil\n }\n }\n\n /// Returns true if the path only contains projections which can be materialized as\n /// SIL struct or tuple projection instructions - for values or addresses.\n public var isMaterializable: Bool {\n let (kind, _, subPath) = pop()\n switch kind {\n case .root:\n return true\n case .structField, .tupleField:\n return subPath.isMaterializable\n default:\n return false\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Parsing\n//===----------------------------------------------------------------------===//\n\nextension StringParser {\n\n mutating func parseProjectionPathFromSource(for function: Function, type: Type?) throws -> SmallProjectionPath {\n var entries: [(SmallProjectionPath.FieldKind, Int)] = []\n var currentTy = type\n repeat {\n if consume("**") {\n entries.append((.anything, 0))\n currentTy = nil\n } else if consume("class*") {\n if let ty = currentTy, !ty.isClass {\n try throwError("cannot use 'anyClassField' on a non-class type - add 'anyValueFields' first")\n }\n entries.append((.anyClassField, 0))\n currentTy = nil\n } else if consume("value**") {\n entries.append((.anyValueFields, 0))\n currentTy = nil\n } else if let tupleElemIdx = consumeInt() {\n guard let ty = currentTy, ty.isTuple else {\n try throwError("cannot use a tuple index after 'any' field selection")\n }\n let tupleElements = ty.tupleElements\n if tupleElemIdx >= tupleElements.count {\n try throwError("tuple element index too large")\n }\n entries.append((.tupleField, tupleElemIdx))\n currentTy = tupleElements[tupleElemIdx]\n } else if let name = consumeIdentifier() {\n guard let ty = currentTy else {\n try throwError("cannot use field name after 'any' field selection")\n }\n if !ty.isClass && !ty.isStruct {\n try throwError("unknown kind of nominal type")\n }\n guard let nominalFields = ty.getNominalFields(in: function) else {\n try throwError("resilient types are not supported")\n }\n guard let fieldIdx = nominalFields.getIndexOfField(withName: name) else {\n try throwError("field not found")\n }\n if ty.isClass {\n entries.append((.classField, fieldIdx))\n } else {\n assert(ty.isStruct)\n entries.append((.structField, fieldIdx))\n }\n currentTy = nominalFields[fieldIdx]\n } else {\n try throwError("expected selection path component")\n }\n } while consume(".")\n \n if let ty = currentTy, !ty.isClass {\n try throwError("the select field is not a class - add 'anyValueFields'")\n }\n \n return try createPath(from: entries)\n }\n\n mutating func parseProjectionPathFromSIL() throws -> SmallProjectionPath {\n var entries: [(SmallProjectionPath.FieldKind, Int)] = []\n while true {\n if consume("**") {\n entries.append((.anything, 0))\n } else if consume("c*") {\n entries.append((.anyClassField, 0))\n } else if consume("v**") {\n entries.append((.anyValueFields, 0))\n } else if consume("i*") {\n entries.append((.anyIndexedElement, 0))\n } else if consume("ct") {\n entries.append((.tailElements, 0))\n } else if consume("x") {\n entries.append((.existential, 0))\n } else if consume("c") {\n guard let idx = consumeInt(withWhiteSpace: false) else {\n try throwError("expected class field index")\n }\n entries.append((.classField, idx))\n } else if consume("e") {\n guard let idx = consumeInt(withWhiteSpace: false) else {\n try throwError("expected enum case index")\n }\n entries.append((.enumCase, idx))\n } else if consume("s") {\n guard let idx = consumeInt(withWhiteSpace: false) else {\n try throwError("expected struct field index")\n }\n entries.append((.structField, idx))\n } else if consume("i") {\n guard let idx = consumeInt(withWhiteSpace: false) else {\n try throwError("expected index")\n }\n entries.append((.indexedElement, idx))\n } else if let tupleElemIdx = consumeInt() {\n entries.append((.tupleField, tupleElemIdx))\n } else if !consume(".") {\n return try createPath(from: entries)\n }\n }\n }\n\n private func createPath(from entries: [(SmallProjectionPath.FieldKind, Int)]) throws -> SmallProjectionPath {\n var path = SmallProjectionPath()\n var first = true\n for (kind, idx) in entries.reversed() {\n if !first && kind == .anything {\n try throwError("'**' only allowed in last path component")\n }\n path = path.push(kind, index: idx)\n \n // Check for overflow\n if !first && path == SmallProjectionPath(.anything) {\n try throwError("path is too long")\n }\n first = false\n }\n return path\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Unit Tests\n//===----------------------------------------------------------------------===//\n\nextension SmallProjectionPath {\n public static func runUnitTests() {\n \n basicPushPop()\n parsing()\n merging()\n subtracting()\n matching()\n overlapping()\n predicates()\n path2path()\n \n func basicPushPop() {\n let p1 = SmallProjectionPath(.structField, index: 3)\n .push(.classField, index: 12345678)\n let (k2, i2, p2) = p1.pop()\n assert(k2 == .classField && i2 == 12345678)\n let (k3, i3, p3) = p2.pop()\n assert(k3 == .structField && i3 == 3)\n assert(p3.isEmpty)\n let (k4, i4, _) = p2.push(.enumCase, index: 876).pop()\n assert(k4 == .enumCase && i4 == 876)\n let p5 = SmallProjectionPath(.anything)\n assert(p5.pop().path.isEmpty)\n let p6 = SmallProjectionPath(.indexedElement, index: 1).push(.indexedElement, index: 2)\n let (k6, i6, p7) = p6.pop()\n assert(k6 == .indexedElement && i6 == 3 && p7.isEmpty)\n let p8 = SmallProjectionPath(.indexedElement, index: 0)\n assert(p8.isEmpty)\n let p9 = SmallProjectionPath(.indexedElement, index: 1).push(.anyIndexedElement)\n let (k9, i9, p10) = p9.pop()\n assert(k9 == .anyIndexedElement && i9 == 0 && p10.isEmpty)\n let p11 = SmallProjectionPath(.anyIndexedElement).push(.indexedElement, index: 1)\n let (k11, i11, p12) = p11.pop()\n assert(k11 == .anyIndexedElement && i11 == 0 && p12.isEmpty)\n }\n \n func parsing() {\n testParse("v**.c*", expect: SmallProjectionPath(.anyClassField)\n .push(.anyValueFields))\n testParse("s3.c*.v**.s1", expect: SmallProjectionPath(.structField, index: 1)\n .push(.anyValueFields)\n .push(.anyClassField)\n .push(.structField, index: 3))\n testParse("2.c*.e6.ct.**", expect: SmallProjectionPath(.anything)\n .push(.tailElements)\n .push(.enumCase, index: 6)\n .push(.anyClassField)\n .push(.tupleField, index: 2))\n testParse("i3.x.i*", expect: SmallProjectionPath(.anyIndexedElement)\n .push(.existential)\n .push(.indexedElement, index: 3))\n\n do {\n var parser = StringParser("c*.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.**")\n _ = try parser.parseProjectionPathFromSIL()\n fatalError("too long path not detected")\n } catch {\n }\n do {\n var parser = StringParser("**.s0")\n _ = try parser.parseProjectionPathFromSIL()\n fatalError("wrong '**' not detected")\n } catch {\n }\n }\n\n func testParse(_ pathStr: String, expect: SmallProjectionPath) {\n var parser = StringParser(pathStr)\n let path = try! parser.parseProjectionPathFromSIL()\n assert(path == expect)\n let str = path.description\n assert(str == pathStr)\n }\n \n func merging() {\n testMerge("c1.c0", "c0", expect: "c*.**")\n testMerge("c2.c1", "c2", expect: "c2.**")\n testMerge("s3.c0", "v**.c0", expect: "v**.c0")\n testMerge("c0", "s2.c1", expect: "v**.c*")\n testMerge("s1.s1.c2", "s1.c2", expect: "s1.v**.c2")\n testMerge("s1.s0", "s2.s0", expect: "v**")\n testMerge("ct", "c2", expect: "c*")\n testMerge("i1", "i2", expect: "i*")\n testMerge("i*", "i2", expect: "i*")\n testMerge("s0.i*.e3", "s0.e3", expect: "s0.i*.e3")\n testMerge("i*", "v**", expect: "v**")\n\n testMerge("ct.s0.e0.v**.c0", "ct.s0.e0.v**.c0", expect: "ct.s0.e0.v**.c0")\n testMerge("ct.s0.s0.c0", "ct.s0.e0.s0.c0", expect: "ct.s0.v**.c0")\n }\n\n func testMerge(_ lhsStr: String, _ rhsStr: String,\n expect expectStr: String) {\n var lhsParser = StringParser(lhsStr)\n let lhs = try! lhsParser.parseProjectionPathFromSIL()\n var rhsParser = StringParser(rhsStr)\n let rhs = try! rhsParser.parseProjectionPathFromSIL()\n var expectParser = StringParser(expectStr)\n let expect = try! expectParser.parseProjectionPathFromSIL()\n\n let result = lhs.merge(with: rhs)\n assert(result == expect)\n let result2 = rhs.merge(with: lhs)\n assert(result2 == expect)\n }\n \n func subtracting() {\n testSubtract("s0", "s0.s1", expect: "s1")\n testSubtract("s0", "s1", expect: nil)\n testSubtract("s0.s1", "s0.s1", expect: "")\n testSubtract("i*.s1", "i*.s1", expect: nil)\n testSubtract("ct.s1.0.i3.x", "ct.s1.0.i3.x", expect: "")\n testSubtract("c0.s1.0.i3", "c0.s1.0.i3.x", expect: "x")\n testSubtract("s1.0.i3.x", "s1.0.i3", expect: nil)\n testSubtract("v**.s1", "v**.s1", expect: nil)\n testSubtract("i*", "i*", expect: nil)\n }\n\n func testSubtract(_ lhsStr: String, _ rhsStr: String, expect expectStr: String?) {\n var lhsParser = StringParser(lhsStr)\n let lhs = try! lhsParser.parseProjectionPathFromSIL()\n var rhsParser = StringParser(rhsStr)\n let rhs = try! rhsParser.parseProjectionPathFromSIL()\n\n let result = lhs.subtract(from: rhs)\n\n if let expectStr = expectStr {\n var expectParser = StringParser(expectStr)\n let expect = try! expectParser.parseProjectionPathFromSIL()\n assert(result! == expect)\n } else {\n assert(result == nil)\n }\n }\n\n func matching() {\n testMatch("ct", "c*", expect: true)\n testMatch("c1", "c*", expect: true)\n testMatch("s2", "v**", expect: true)\n testMatch("1", "v**", expect: true)\n testMatch("e1", "v**", expect: true)\n testMatch("c*", "c1", expect: false)\n testMatch("c*", "ct", expect: false)\n testMatch("v**", "s0", expect: false)\n testMatch("i1", "i1", expect: true)\n testMatch("i1", "i*", expect: true)\n testMatch("i*", "i1", expect: false)\n\n testMatch("s0.s1", "s0.s1", expect: true)\n testMatch("s0.s2", "s0.s1", expect: false)\n testMatch("s0", "s0.v**", expect: true)\n testMatch("s0.s1", "s0.v**", expect: true)\n testMatch("s0.1.e2", "s0.v**", expect: true)\n testMatch("s0.v**.x.e2", "v**", expect: true)\n testMatch("s0.v**", "s0.s1", expect: false)\n testMatch("s0.s1.c*", "s0.v**", expect: false)\n testMatch("s0.v**", "s0.**", expect: true)\n testMatch("s1.v**", "s0.**", expect: false)\n testMatch("s0.**", "s0.v**", expect: false)\n testMatch("s0.s1", "s0.i*.s1", expect: true)\n }\n\n func testMatch(_ lhsStr: String, _ rhsStr: String, expect: Bool) {\n var lhsParser = StringParser(lhsStr)\n let lhs = try! lhsParser.parseProjectionPathFromSIL()\n var rhsParser = StringParser(rhsStr)\n let rhs = try! rhsParser.parseProjectionPathFromSIL()\n let result = lhs.matches(pattern: rhs)\n assert(result == expect)\n }\n\n func overlapping() {\n testOverlap("s0.s1.s2", "s0.s1.s2", expect: true)\n testOverlap("s0.s1.s2", "s0.s2.s2", expect: false)\n testOverlap("s0.s1.s2", "s0.e1.s2", expect: false)\n testOverlap("s0.s1.s2", "s0.s1", expect: true)\n testOverlap("s0.s1.s2", "s1.s2", expect: false)\n\n testOverlap("s0.c*.s2", "s0.ct.s2", expect: true)\n testOverlap("s0.c*.s2", "s0.c1.s2", expect: true)\n testOverlap("s0.c*.s2", "s0.c1.c2.s2", expect: false)\n testOverlap("s0.c*.s2", "s0.s2", expect: false)\n\n testOverlap("s0.v**.s2", "s0.s3.x", expect: true)\n testOverlap("s0.v**.s2.c2", "s0.s3.c1", expect: false)\n testOverlap("s0.v**.s2", "s1.s3", expect: false)\n testOverlap("s0.v**.s2", "s0.v**.s3", expect: true)\n\n testOverlap("s0.**", "s0.s3.c1", expect: true)\n testOverlap("**", "s0.s3.c1", expect: true)\n\n testOverlap("i1", "i*", expect: true)\n testOverlap("i1", "v**", expect: true)\n testOverlap("s0.i*.s1", "s0.s1", expect: true)\n }\n\n func testOverlap(_ lhsStr: String, _ rhsStr: String, expect: Bool) {\n var lhsParser = StringParser(lhsStr)\n let lhs = try! lhsParser.parseProjectionPathFromSIL()\n var rhsParser = StringParser(rhsStr)\n let rhs = try! rhsParser.parseProjectionPathFromSIL()\n let result = lhs.mayOverlap(with: rhs)\n assert(result == expect)\n let reversedResult = rhs.mayOverlap(with: lhs)\n assert(reversedResult == expect)\n }\n\n func predicates() {\n testPredicate("v**", \.hasClassProjection, expect: false)\n testPredicate("v**.c0.s1.v**", \.hasClassProjection, expect: true)\n testPredicate("c0.**", \.hasClassProjection, expect: true)\n testPredicate("c0.c1", \.hasClassProjection, expect: true)\n testPredicate("ct", \.hasClassProjection, expect: true)\n testPredicate("s0", \.hasClassProjection, expect: false)\n\n testPredicate("v**", \.mayHaveClassProjection, expect: false)\n testPredicate("c0", \.mayHaveClassProjection, expect: true)\n testPredicate("1", \.mayHaveClassProjection, expect: false)\n testPredicate("**", \.mayHaveClassProjection, expect: true)\n\n testPredicate("v**", \.mayHaveTwoClassProjections, expect: false)\n testPredicate("c0", \.mayHaveTwoClassProjections, expect: false)\n testPredicate("**", \.mayHaveTwoClassProjections, expect: true)\n testPredicate("v**.c*.s2.1.c0", \.mayHaveTwoClassProjections, expect: true)\n testPredicate("c*.s2.1.c0.v**", \.mayHaveTwoClassProjections, expect: true)\n testPredicate("v**.c*.**", \.mayHaveTwoClassProjections, expect: true)\n }\n\n func testPredicate(_ pathStr: String, _ property: (SmallProjectionPath) -> Bool, expect: Bool) {\n var parser = StringParser(pathStr)\n let path = try! parser.parseProjectionPathFromSIL()\n let result = property(path)\n assert(result == expect)\n }\n \n func path2path() {\n testPath2Path("s0.e2.3.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1")\n testPath2Path("v**.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1")\n testPath2Path("**", { $0.popAllValueFields() }, expect: "**")\n\n testPath2Path("s0.e2.3.c4.s1.e2.v**.**", { $0.popLastClassAndValuesFromTail() }, expect: "s0.e2.3.c4.s1.e2.v**.**")\n testPath2Path("s0.c2.3.c4.s1", { $0.popLastClassAndValuesFromTail() }, expect: "s0.c2.3")\n testPath2Path("v**.c*.s1", { $0.popLastClassAndValuesFromTail() }, expect: "v**")\n testPath2Path("s1.ct.v**", { $0.popLastClassAndValuesFromTail() }, expect: "s1")\n testPath2Path("c0.c1.c2", { $0.popLastClassAndValuesFromTail() }, expect: "c0.c1")\n testPath2Path("**", { $0.popLastClassAndValuesFromTail() }, expect: "**")\n\n testPath2Path("v**.c3", { $0.popIfMatches(.anyValueFields) }, expect: "v**.c3")\n testPath2Path("**", { $0.popIfMatches(.anyValueFields) }, expect: "**")\n testPath2Path("s0.c3", { $0.popIfMatches(.anyValueFields) }, expect: nil)\n \n testPath2Path("c0.s3", { $0.popIfMatches(.anyClassField) }, expect: nil)\n testPath2Path("**", { $0.popIfMatches(.anyClassField) }, expect: "**")\n testPath2Path("c*.e3", { $0.popIfMatches(.anyClassField) }, expect: "e3")\n\n testPath2Path("i*.e3.s0", { $0.popIfMatches(.enumCase, index: 3) }, expect: "s0")\n testPath2Path("i1.e3.s0", { $0.popIfMatches(.enumCase, index: 3) }, expect: nil)\n testPath2Path("i*.e3.s0", { $0.popIfMatches(.indexedElement, index: 0) }, expect: "i*.e3.s0")\n }\n\n func testPath2Path(_ pathStr: String, _ transform: (SmallProjectionPath) -> SmallProjectionPath?, expect: String?) {\n var parser = StringParser(pathStr)\n let path = try! parser.parseProjectionPathFromSIL()\n let result = transform(path)\n if let expect = expect {\n var expectParser = StringParser(expect)\n let expectPath = try! expectParser.parseProjectionPathFromSIL()\n assert(result == expectPath)\n } else {\n assert(result == nil)\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_SmallProjectionPath.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_SmallProjectionPath.swift
Swift
37,515
0.95
0.181916
0.203052
node-utils
876
2023-11-07T00:42:18.873656
BSD-3-Clause
false
0ed23d608e992360d413d7084136f388
//===--- WalkUtils.swift - Utilities for use-def def-use walks ------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// This file provides utilities for SSA def-use and use-def walking.\n// There are four walker protocols:\n// * for both directions: down (= def-use) and up (= use-def)\n// * for values and addresses\n// ```\n// protocol ValueDefUseWalker\n// protocol AddressDefUseWalker\n// protocol ValueUseDefWalker\n// protocol AddressUseDefWalker\n// ```\n//\n// To use a walker, just conform to one (or multiple) of those protocols.\n// There are several ways to configure the walker by providing implementations of\n// their protocol functions. For details see the protocol definitions.\n// The value-walkers also require to provide a "cache" property - see `WalkerCache`.\n//\n// The walkers maintain a "path" during the walk, which in it's simplest form can\n// just be a SmallProjectionPath. For details see `WalkingPath`.\n//===----------------------------------------------------------------------===//\n\n/// Result returned by the walker functions\npublic enum WalkResult {\n /// Continue the walk\n case continueWalk\n /// Stop the walks of all uses, a sufficient condition has been found\n case abortWalk\n}\n\nextension Sequence {\n // Walk each element until the walk aborts.\n public func walk(\n _ walker: (Element) throws -> WalkResult\n ) rethrows -> WalkResult {\n return try contains { try walker($0) == .abortWalk } ? .abortWalk : .continueWalk\n }\n}\n\n/// The path which is updated throughout a walk.\n///\n/// Usually this is just a SmallProjectionPath, but clients can implement their own path, e.g.\n/// to maintain additional data throughout the walk.\npublic protocol WalkingPath : Equatable {\n typealias FieldKind = SmallProjectionPath.FieldKind\n\n /// Returns the merged path of this path and `with`.\n func merge(with: Self) -> Self\n \n /// Pops the first path component if it is exactly of kind `kind` - not considering wildcards.\n ///\n /// Returns the index of the component and the new path or - if not matching - returns nil.\n /// Called for destructure instructions during down-walking and for aggregate instructions during up-walking.\n func pop(kind: FieldKind) -> (index: Int, path: Self)?\n\n /// Pops the first path component if it matches `kind` and (optionally) `index`.\n ///\n /// Called for projection instructions during down-walking and for aggregate instructions during up-walking.\n func popIfMatches(_ kind: FieldKind, index: Int?) -> Self?\n \n /// Pushes a new first component to the path and returns the new path.\n ///\n /// Called for aggregate instructions during down-walking and for projection instructions during up-walking.\n func push(_ kind: FieldKind, index: Int) -> Self\n}\n\nextension SmallProjectionPath : WalkingPath { }\n\n/// A `WalkingPath` where `push` and `pop` instructions\n/// are forwarded to an underlying `projectionPath`.\npublic protocol SmallProjectionWalkingPath : WalkingPath {\n /// During the walk, a projection path indicates where the initial value is\n /// contained in an aggregate.\n /// Example for a walk-down:\n /// \code\n /// %1 = alloc_ref // 1. initial value, path = empty\n /// %2 = struct $S (%1) // 2. path = s0\n /// %3 = tuple (%other, %1) // 3. path = t1.s0\n /// %4 = tuple_extract %3, 1 // 4. path = s0\n /// %5 = struct_extract %4, #field // 5. path = empty\n /// \endcode\n ///\n var projectionPath: SmallProjectionPath { get }\n func with(projectionPath: SmallProjectionPath) -> Self\n}\n\nextension SmallProjectionWalkingPath {\n public func pop(kind: FieldKind) -> (index: Int, path: Self)? {\n if let (idx, p) = projectionPath.pop(kind: kind) {\n return (idx, with(projectionPath: p))\n }\n return nil\n }\n\n public func popIfMatches(_ kind: FieldKind, index: Int?) -> Self? {\n if let p = projectionPath.popIfMatches(kind, index: index) {\n return with(projectionPath: p)\n }\n return nil\n }\n\n public func push(_ kind: FieldKind, index: Int) -> Self {\n return with(projectionPath: projectionPath.push(kind, index: index))\n }\n}\n\n/// A walking path which matches everything.\n///\n/// Useful for walkers which don't care about the path and unconditionally walk to all defs/uses.\npublic struct UnusedWalkingPath : WalkingPath {\n public init() {}\n public func merge(with: Self) -> Self { self }\n public func pop(kind: FieldKind) -> (index: Int, path: Self)? { nil }\n public func popIfMatches(_ kind: FieldKind, index: Int?) -> Self? { self }\n public func push(_ kind: FieldKind, index: Int) -> Self { self }\n}\n\n/// Caches the state of a walk.\n///\n/// A client must provide this cache in a `walkUpCache` or `walkDownCache` property.\npublic struct WalkerCache<Path : WalkingPath> {\n\n public init() {}\n\n public mutating func needWalk(for value: Value, path: Path) -> Path? {\n\n // Handle the first inline entry.\n guard let e = inlineEntry0 else {\n inlineEntry0 = (value, path)\n return path\n }\n if e.value == value {\n let newPath = e.path.merge(with: path)\n if newPath != e.path {\n inlineEntry0 = (value, newPath)\n return newPath\n }\n return nil\n }\n \n // Handle the second inline entry.\n guard let e = inlineEntry1 else {\n inlineEntry1 = (value, path)\n return path\n }\n if e.value == value {\n let newPath = e.path.merge(with: path)\n if newPath != e.path {\n inlineEntry1 = (value, newPath)\n return newPath\n }\n return nil\n }\n \n // If there are more than two elements, it goes into the `cache` Dictionary.\n return cache[value.hashable, default: CacheEntry()].needWalk(path: path)\n }\n\n mutating func clear() {\n inlineEntry0 = nil\n inlineEntry1 = nil\n cache.removeAll(keepingCapacity: true)\n }\n\n private struct CacheEntry {\n var cachedPath: Path?\n \n mutating func needWalk(path: Path) -> Path? {\n guard let previousPath = cachedPath else {\n self.cachedPath = path\n return path\n }\n let newPath = previousPath.merge(with: path)\n if newPath != previousPath {\n self.cachedPath = newPath\n return newPath\n }\n return nil\n }\n }\n\n // If there are no more than 2 elements in the cache, we can avoid using the `cache` Dictionary,\n // which avoids memory allocations.\n // Fortunately this is the common case by far (about 97% of all walker invocations).\n private var inlineEntry0: (value: Value, path: Path)?\n private var inlineEntry1: (value: Value, path: Path)?\n\n // All elements, which don't fit into the inline entries.\n private var cache = Dictionary<HashableValue, CacheEntry>()\n}\n\n/// - A `DefUseWalker` finds all uses of a target value.\n///\n/// - A target value is described by an "initial" value and a projection path.\n/// 1. If the projection path is empty (`""`) then the target value is the initial value itself.\n/// 2. If the projection path is non-empty (`"s0.1.e3"`), then the target value is the one\n/// reachable from the initial value through the series of projections described by the path.\n/// - A path can also contain a pattern such as `"v**"` which means any series of "value"\n/// projections (excluding `ref_element_addr` and similar, i.e. `c*`) from any field.\n/// In the `v**` case, the target value*s* are many, i.e. all the ones reachable from\n/// the initial value through _any of the fields_ through _any number_ of value projections.\n/// `c*` means values reachable through a _single_ projection of _any_ of the fields of the class.\n///\n/// - A walk is started with a call to `walkDownUses(initial, path: path)`.\n/// - This function will call `walkDown(operand, path: path)`\n/// for every use of `initial` as `operand` in an instruction.\n/// - For each use, then the walk can continue with initial value the result if the result of the using\n/// instruction might still reach the target value with a new projection path.\n/// 1. If the use is a construction such as a\n/// `%res = struct $S (%f0)` (or `%res = tuple (%unk, %1)`) instruction and the path is `p`\n/// then the `%res` result value reaches the target value through the new projection`s0.p` (respectively `1.p`).\n/// 2. If the use is a projection such as `%res = struct_extract %s : $S, #S.field0` and the\n/// path is `s0.s1` then the target value is reachable from `%res` with path `s1`.\n/// If the path doesn't match `unmatchedPath` is called.\n/// 3. If the use is a "forwarding instruction", such as a cast, the walk continues with the same path.\n/// 4. If the use is an unhandled instruction then `leafUse` is called to denote that the client has to\n/// handle this use.\n///\n/// There are two types of DefUseWalkers, one for values (`ValueDefUseWalker`) and one for\n/// addresses (`AddressDefUseWalker`)\n\n\n/// A `ValueDefUseWalker` can only handle "value" initial values, which correspond\n/// to types that are not addresses, i.e. _do not have_ an asterisk (`*`) in the textual\n/// representation of their SIL type (`$T`).\n/// These can be values of reference type, or struct/tuple etc.\n/// A `ValueDefUseWalker.walkDownDefault` called on a use of a initial "value" which\n/// yields an "address" value (such as `ref_element_addr %initial_value`) will call `leafUse`\n/// since the walk can't proceed.\n///\n/// Example call `walkDownUses(%str, path: "s0.s1")`\n/// ```\n/// %fa = struct_extract %str : $S1, #S1.fa // 1. field 0, walkDownUses(%fa, "s1")\n/// %fb = struct_extract %str : $S1, #S1.fb // 5. field 1, unmatchedPath(%str, "s0.s1")\n/// %fa.ga = struct_extract %fa : $S2, #S2.ga // 2. field 1, walkDownUses(%fa.ga, "")\n/// ... = struct_extract %fa.ga: $S3, #S3.ha // 3. empty path, unmatchedPath(%fa.ga, "")\n/// ... = <instruction> %fa.ga: // 4. unknown instruction, leafUse(%fa.ga, "")\n/// ... = <instruction> %str: // 6. unknown instruction, leafUse(%str, "s0.s1")\n/// ```\npublic protocol ValueDefUseWalker {\n associatedtype Path: WalkingPath\n \n /// Called on each use. The implementor can decide to continue the walk by calling\n /// `walkDownDefault(value: value, path: path)` or\n /// do nothing.\n mutating func walkDown(value: Operand, path: Path) -> WalkResult\n \n /// Walks down all results of the multi-value instruction `inst`.\n ///\n /// This is called if the path doesn't filter a specific result, but contains a wildcard which matches all results.\n /// Clients can but don't need to customize this function.\n mutating func walkDownAllResults(of inst: MultipleValueInstruction, path: Path) -> WalkResult\n\n /// `leafUse` is called from `walkDownDefault` when the walk can't continue for this use since\n /// this is an instruction unknown to the default walker which _might_ be a "transitive use"\n /// of the target value (such as `destroy_value %initial` or a `builtin ... %initial` instruction)\n mutating func leafUse(value: Operand, path: Path) -> WalkResult\n \n /// `unmatchedPath` is called from `walkDownDefault` when this is a use\n /// of the initial value in an instruction recognized by the walker\n /// but for which the requested `path` does not allow the walk to continue.\n mutating func unmatchedPath(value: Operand, path: Path) -> WalkResult\n\n /// A client must implement this function to cache walking results.\n /// The function returns `nil` if the walk doesn't need to continue because\n /// the `def` was already handled before.\n /// In case the walk needs to be continued, this function returns the path for continuing the walk.\n ///\n /// This method is called for two cases:\n /// 1. To avoid exponential complexity during a walk down with a wildcard path `v**` or `**`\n /// ```\n /// (%1, %2, %3, %4) = destructure_tuple %t1\n /// %t2 = tuple (%1, %2, %3, %4)\n /// (%5, %6, %7, %8) = destructure_tuple %t2\n /// %t3 = tuple (%5, %6, %7, %8)\n /// ```\n /// 2. To handle "phi webs" of `br` instructions which would lead to an infinite\n /// walk down. In this case the implementor must ensure that eventually\n /// `shouldRecomputeDown` returns `nil`, i.e. a fixpoint has been reached.\n /// - If the implementor doesn't need for the walk to cross phi webs,\n /// it can intercept `BranchInst`/`CondBranchInst` in `walkDown` and\n /// not call `walkDownDefault` for these cases.\n /// - Phi webs arise only for "value"s.\n var walkDownCache: WalkerCache<Path> { get set }\n}\n\nextension ValueDefUseWalker {\n public mutating func walkDown(value operand: Operand, path: Path) -> WalkResult {\n return walkDownDefault(value: operand, path: path)\n }\n \n public mutating func unmatchedPath(value: Operand, path: Path) -> WalkResult {\n return .continueWalk\n }\n \n /// Given an operand to an instruction, tries to continue the walk with the uses of\n /// instruction's result if the target value is reachable from it (i.e. matches the `path`) .\n /// If the walk can't continue, it calls `leafUse` or `unmatchedPath`\n public mutating func walkDownDefault(value operand: Operand, path: Path) -> WalkResult {\n let instruction = operand.instruction\n switch instruction {\n case let str as StructInst:\n return walkDownUses(ofValue: str,\n path: path.push(.structField, index: operand.index))\n case let t as TupleInst:\n return walkDownUses(ofValue: t,\n path: path.push(.tupleField, index: operand.index))\n case let e as EnumInst:\n return walkDownUses(ofValue: e,\n path: path.push(.enumCase, index: e.caseIndex))\n case let se as StructExtractInst:\n if let path = path.popIfMatches(.structField, index: se.fieldIndex) {\n return walkDownUses(ofValue: se, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let te as TupleExtractInst:\n if let path = path.popIfMatches(.tupleField, index: te.fieldIndex) {\n return walkDownUses(ofValue: te, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let ued as UncheckedEnumDataInst:\n if let path = path.popIfMatches(.enumCase, index: ued.caseIndex) {\n return walkDownUses(ofValue: ued, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let ds as DestructureStructInst:\n if let (index, path) = path.pop(kind: .structField) {\n return walkDownUses(ofValue: ds.results[index], path: path)\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n return walkDownAllResults(of: ds, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let dt as DestructureTupleInst:\n if let (index, path) = path.pop(kind: .tupleField) {\n return walkDownUses(ofValue: dt.results[index], path: path)\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n return walkDownAllResults(of: dt, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let ier as InitExistentialRefInst:\n return walkDownUses(ofValue: ier, path: path.push(.existential, index: 0))\n case let oer as OpenExistentialRefInst:\n if let path = path.popIfMatches(.existential, index: 0) {\n return walkDownUses(ofValue: oer, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case is BeginBorrowInst, is CopyValueInst, is MoveValueInst,\n is UpcastInst, is EndCOWMutationInst, is EndInitLetRefInst,\n is RefToBridgeObjectInst, is BridgeObjectToRefInst, is MarkUnresolvedNonCopyableValueInst:\n return walkDownUses(ofValue: (instruction as! SingleValueInstruction), path: path)\n case let urc as UncheckedRefCastInst:\n if urc.type.isClassExistential || urc.fromInstance.type.isClassExistential {\n // Sometimes `unchecked_ref_cast` is misused to cast between AnyObject and a class (instead of\n // init_existential_ref and open_existential_ref).\n // We need to ignore this because otherwise the path wouldn't contain the right `existential` field kind.\n return leafUse(value: operand, path: path)\n }\n // The `unchecked_ref_cast` is designed to be able to cast between\n // `Optional<ClassType>` and `ClassType`. We need to handle these\n // cases by checking if the type is optional and adjust the path\n // accordingly.\n switch (urc.type.isOptional, urc.fromInstance.type.isOptional) {\n case (true, false):\n return walkDownUses(ofValue: urc, path: path.push(.enumCase, index: 1))\n case (false, true):\n if let path = path.popIfMatches(.enumCase, index: 1) {\n return walkDownUses(ofValue: urc, path: path)\n }\n return unmatchedPath(value: operand, path: path)\n default:\n return walkDownUses(ofValue: urc, path: path)\n }\n case let beginDealloc as BeginDeallocRefInst:\n if operand.index == 0 {\n return walkDownUses(ofValue: beginDealloc, path: path)\n }\n return .continueWalk\n case let mdi as MarkDependenceInst:\n if operand.index == 0 {\n return walkDownUses(ofValue: mdi, path: path)\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let br as BranchInst:\n let val = br.getArgument(for: operand)\n if let path = walkDownCache.needWalk(for: val, path: path) {\n return walkDownUses(ofValue: val, path: path)\n } else {\n return .continueWalk\n }\n case let cbr as CondBranchInst:\n if let val = cbr.getArgument(for: operand) {\n if let path = walkDownCache.needWalk(for: val, path: path) {\n return walkDownUses(ofValue: val, path: path)\n } else {\n return .continueWalk\n }\n } else {\n return leafUse(value: operand, path: path)\n }\n case let se as SwitchEnumInst:\n if let (caseIdx, path) = path.pop(kind: .enumCase),\n let succBlock = se.getUniqueSuccessor(forCaseIndex: caseIdx),\n let payload = succBlock.arguments.first {\n return walkDownUses(ofValue: payload, path: path)\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n for succBlock in se.parentBlock.successors {\n if let payload = succBlock.arguments.first,\n walkDownUses(ofValue: payload, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n } else {\n return unmatchedPath(value: operand, path: path)\n }\n case let bcm as BeginCOWMutationInst:\n return walkDownUses(ofValue: bcm.instanceResult, path: path)\n default:\n return leafUse(value: operand, path: path)\n }\n }\n \n /// Starts the walk\n public mutating func walkDownUses(ofValue: Value, path: Path) -> WalkResult {\n for operand in ofValue.uses where !operand.isTypeDependent {\n if walkDown(value: operand, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n \n public mutating func walkDownAllResults(of inst: MultipleValueInstruction, path: Path) -> WalkResult {\n for result in inst.results {\n if let path = walkDownCache.needWalk(for: result, path: path) {\n if walkDownUses(ofValue: result, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n }\n return .continueWalk\n }\n}\n\n/// An `AddressDefUseWalker` can only handle initial "addresses", which correspond\n/// to types that are addresses (`$*T`).\n/// An `AddressDefUseWalker.walkDownDefault` called on a use of an initial "address"\n/// which results in a "value" (such as `load %initial_addr`) will call `leafUse` since the walk\n/// can't proceed.\n/// All functions return a boolean flag which, if true, can stop the walk of the other uses\n/// and the whole walk.\npublic protocol AddressDefUseWalker {\n associatedtype Path: WalkingPath\n \n /// Called on each use. The implementor can decide to continue the walk by calling\n /// `walkDownDefault(address: address, path: path)` or\n /// do nothing.\n mutating func walkDown(address: Operand, path: Path) -> WalkResult\n \n /// `leafUse` is called from `walkDownDefault` when the walk can't continue for this use since\n /// this is an instruction unknown to the default walker which might be a "transitive use"\n /// of the target value (such as `destroy_addr %initial_addr` or a `builtin ... %initial_addr` instruction).\n mutating func leafUse(address: Operand, path: Path) -> WalkResult\n \n /// `unmatchedPath` is called from `walkDownDefault` when this is a use\n /// of the initial address in an instruction recognized by the walker\n /// but for which the requested `path` does not allow the walk to continue.\n mutating func unmatchedPath(address: Operand, path: Path) -> WalkResult\n}\n\nextension AddressDefUseWalker {\n public mutating func walkDown(address operand: Operand, path: Path) -> WalkResult {\n return walkDownDefault(address: operand, path: path)\n }\n \n public mutating func unmatchedPath(address: Operand, path: Path) -> WalkResult {\n return .continueWalk\n }\n \n public mutating func walkDownDefault(address operand: Operand, path: Path) -> WalkResult {\n let instruction = operand.instruction\n switch instruction {\n case let sea as StructElementAddrInst:\n if let path = path.popIfMatches(.structField, index: sea.fieldIndex) {\n return walkDownUses(ofAddress: sea, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n case let tea as TupleElementAddrInst:\n if let path = path.popIfMatches(.tupleField, index: tea.fieldIndex) {\n return walkDownUses(ofAddress: tea, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n case is InitEnumDataAddrInst, is UncheckedTakeEnumDataAddrInst:\n let ei = instruction as! SingleValueInstruction\n if let path = path.popIfMatches(.enumCase, index: (instruction as! EnumInstruction).caseIndex) {\n return walkDownUses(ofAddress: ei, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n case is InitExistentialAddrInst, is OpenExistentialAddrInst:\n if let path = path.popIfMatches(.existential, index: 0) {\n return walkDownUses(ofAddress: instruction as! SingleValueInstruction, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n case let ia as IndexAddrInst:\n if let (pathIdx, subPath) = path.pop(kind: .indexedElement) {\n if let idx = ia.constantIndex,\n idx == pathIdx {\n return walkDownUses(ofAddress: ia, path: subPath)\n }\n return walkDownUses(ofAddress: ia, path: subPath.push(.anyIndexedElement, index: 0))\n }\n return walkDownUses(ofAddress: ia, path: path)\n case let mmc as MarkUnresolvedNonCopyableValueInst:\n return walkDownUses(ofAddress: mmc, path: path)\n case let ba as BeginAccessInst:\n // Don't treat `end_access` as leaf-use. Just ignore it.\n return walkDownNonEndAccessUses(of: ba, path: path)\n case let mdi as MarkDependenceInst:\n if operand.index == 0 {\n return walkDownUses(ofAddress: mdi, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n case is MarkDependenceAddrInst:\n if operand.index == 0 {\n return leafUse(address: operand, path: path)\n } else {\n return unmatchedPath(address: operand, path: path)\n }\n default:\n return leafUse(address: operand, path: path)\n }\n }\n \n public mutating func walkDownUses(ofAddress: Value, path: Path) -> WalkResult {\n for operand in ofAddress.uses where !operand.isTypeDependent {\n if walkDown(address: operand, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n\n private mutating func walkDownNonEndAccessUses(of beginAccess: BeginAccessInst, path: Path) -> WalkResult {\n for operand in beginAccess.uses where !operand.isTypeDependent {\n if !(operand.instruction is EndAccessInst),\n walkDown(address: operand, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n return .continueWalk\n }\n}\n\n/// - A `UseDefWalker` can be used to find all "generating" definitions of\n/// a target value.\n/// - A target value is described by an "initial" value and a projection path as in a `DefUseWalker.`\n/// 1. If the projection path is empty (`""`) then the target value is the initial value itself.\n/// 2. If the projection path is non-empty (`"s0.1.e3"`), then the target value is the one\n/// reachable through the series of projections described by the path, applied to the initial value.\n/// - The same notes about wildcard paths in `DefUseWalker` apply here.\n///\n/// - A walk is started with a call to `walkUp(initial, path: path)`.\n///\n/// - The implementor of `walkUp` can then track the definition if needed and\n/// continue the walk by calling `walkUpDefault`.\n/// `walkUpDefault` will do the following:\n/// 1. If the instruction of the definition is a projection, then it will continue\n/// the walk by calling `walkUp` on the operand definition and an adjusted (pushed) path\n/// to reflect that a further projection is needed to reach the value of interest from the new initial value.\n/// 2. If the instruction of the definition is a value construction such as `struct` and\n/// the head of the path matches the instruction type then the walk continues\n/// with a call to `walkUp` with initial value the operand definition denoted by the path\n/// and the suffix path as path since the target value can now be reached with fewer projections.\n/// If the defining instruction of the value does not match the head of the path as in\n/// `%t = tuple ...` and `"s0.t1"` then `unmatchedPath(%t, ...)` is called.\n/// 3. If the instruction is a forwarding instruction, such as a cast, the walk continues with `walkUp`\n/// with the operand definition as initial value and same path.\n/// 4. If the instruction is not handled by this walker or the path is empty, then `rootDef` is called to\n/// denote that the walk can't continue and that the definition of the target has been reached.\npublic protocol ValueUseDefWalker {\n associatedtype Path: WalkingPath\n \n /// Starting point of the walk. The implementor can decide to continue the walk by calling\n /// `walkUpDefault(value: value, path: path)` or\n /// do nothing.\n mutating func walkUp(value: Value, path: Path) -> WalkResult\n\n /// Walks up all operands of `def`. This is called if the path doesn't filter a specific operand,\n /// but contains a wildcard which matches all operands.\n /// Clients can but don't need to customize this function.\n mutating func walkUpAllOperands(of def: Instruction, path: Path) -> WalkResult\n\n /// `rootDef` is called from `walkUpDefault` when the walk can't continue for this use since\n /// either\n /// * the defining instruction is unknown to the default walker\n /// * the `path` is empty (`""`) and therefore this is the definition of the target value.\n mutating func rootDef(value: Value, path: Path) -> WalkResult\n \n /// `unmatchedPath` is called from `walkUpDefault` when the defining instruction\n /// is unrelated to the `path` the walk should follow.\n mutating func unmatchedPath(value: Value, path: Path) -> WalkResult\n \n /// A client must implement this function to cache walking results.\n /// The function returns nil if the walk doesn't need to continue because\n /// the `def` was already handled before.\n /// In case the walk needs to be continued, this function returns the path\n /// for continuing the walk.\n var walkUpCache: WalkerCache<Path> { get set }\n}\n\nextension ValueUseDefWalker {\n public mutating func walkUp(value: Value, path: Path) -> WalkResult {\n return walkUpDefault(value: value, path: path)\n }\n \n public mutating func unmatchedPath(value: Value, path: Path) -> WalkResult {\n return .continueWalk\n }\n \n public mutating func walkUpDefault(value def: Value, path: Path) -> WalkResult {\n switch def {\n case let str as StructInst:\n if let (index, path) = path.pop(kind: .structField) {\n if index >= str.operands.count {\n // This can happen if there is a type mismatch, e.g. two different concrete types of an existential\n // are visited for the same path.\n return unmatchedPath(value: str, path: path)\n }\n return walkUp(value: str.operands[index].value, path: path)\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n return walkUpAllOperands(of: str, path: path)\n } else {\n return unmatchedPath(value: str, path: path)\n }\n case let t as TupleInst:\n if let (index, path) = path.pop(kind: .tupleField) {\n if index >= t.operands.count {\n // This can happen if there is a type mismatch, e.g. two different concrete types of an existential\n // are visited for the same path.\n return unmatchedPath(value: t, path: path)\n }\n return walkUp(value: t.operands[index].value, path: path)\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n return walkUpAllOperands(of: t, path: path)\n } else {\n return unmatchedPath(value: t, path: path)\n }\n case let e as EnumInst:\n if let path = path.popIfMatches(.enumCase, index: e.caseIndex),\n let payload = e.payload {\n return walkUp(value: payload, path: path)\n\n } else if path.popIfMatches(.anyValueFields, index: nil) != nil {\n if let payload = e.payload {\n return walkUp(value: payload, path: path)\n } else {\n // without a payload, this enum is itself a definition root.\n return rootDef(value: e, path: path)\n }\n\n } else {\n return unmatchedPath(value: e, path: path)\n }\n case let se as StructExtractInst:\n return walkUp(value: se.struct, path: path.push(.structField, index: se.fieldIndex))\n case let te as TupleExtractInst:\n return walkUp(value: te.tuple, path: path.push(.tupleField, index: te.fieldIndex))\n case let ued as UncheckedEnumDataInst:\n return walkUp(value: ued.enum, path: path.push(.enumCase, index: ued.caseIndex))\n case let mvr as MultipleValueInstructionResult:\n let instruction = mvr.parentInstruction\n if let ds = instruction as? DestructureStructInst {\n return walkUp(value: ds.struct, path: path.push(.structField, index: mvr.index))\n } else if let dt = instruction as? DestructureTupleInst {\n return walkUp(value: dt.tuple, path: path.push(.tupleField, index: mvr.index))\n } else if let bcm = instruction as? BeginCOWMutationInst {\n return walkUp(value: bcm.instance, path: path)\n } else {\n return rootDef(value: mvr, path: path)\n }\n case let ier as InitExistentialRefInst:\n if let path = path.popIfMatches(.existential, index: 0) {\n return walkUp(value: ier.instance, path: path)\n } else {\n return unmatchedPath(value: ier, path: path)\n }\n case let oer as OpenExistentialRefInst:\n return walkUp(value: oer.existential, path: path.push(.existential, index: 0))\n case is BeginBorrowInst, is CopyValueInst, is MoveValueInst,\n is UpcastInst, is EndCOWMutationInst, is EndInitLetRefInst,\n is BeginDeallocRefInst, is MarkDependenceInst,\n is RefToBridgeObjectInst, is BridgeObjectToRefInst, is MarkUnresolvedNonCopyableValueInst:\n return walkUp(value: (def as! Instruction).operands[0].value, path: path)\n case let urc as UncheckedRefCastInst:\n if urc.type.isClassExistential || urc.fromInstance.type.isClassExistential {\n // Sometimes `unchecked_ref_cast` is misused to cast between AnyObject and a class (instead of\n // init_existential_ref and open_existential_ref).\n // We need to ignore this because otherwise the path wouldn't contain the right `existential` field kind.\n return rootDef(value: urc, path: path)\n }\n // The `unchecked_ref_cast` is designed to be able to cast between\n // `Optional<ClassType>` and `ClassType`. We need to handle these\n // cases by checking if the type is optional and adjust the path\n // accordingly.\n switch (urc.type.isOptional, urc.fromInstance.type.isOptional) {\n case (true, false):\n if let path = path.popIfMatches(.enumCase, index: 1) {\n return walkUp(value: urc.fromInstance, path: path)\n }\n return unmatchedPath(value: urc.fromInstance, path: path)\n case (false, true):\n return walkUp(value: urc.fromInstance, path: path.push(.enumCase, index: 1))\n default:\n return walkUp(value: urc.fromInstance, path: path)\n }\n case let arg as Argument:\n if let phi = Phi(arg) {\n for incoming in phi.incomingValues {\n // Check the cache to avoid cycles in the walk\n if let path = walkUpCache.needWalk(for: incoming, path: path) {\n if walkUp(value: incoming, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n }\n return .continueWalk\n }\n if let termResult = TerminatorResult(arg) {\n let pred = termResult.predecessor\n if let se = pred.terminator as? SwitchEnumInst,\n let caseIdx = se.getUniqueCase(forSuccessor: termResult.successor) {\n return walkUp(value: se.enumOp, path: path.push(.enumCase, index: caseIdx))\n }\n }\n return rootDef(value: def, path: path)\n default:\n return rootDef(value: def, path: path)\n }\n }\n \n public mutating func walkUpAllOperands(of def: Instruction, path: Path) -> WalkResult {\n for operand in def.operands {\n // `shouldRecompute` is called to avoid exponential complexity in\n // programs like\n //\n // (%1, %2) = destructure_struct %0\n // %3 = struct $Struct %1 %2\n // (%4, %5) = destructure_struct %3\n // %6 = struct $Struct %4 %5\n if let path = walkUpCache.needWalk(for: operand.value, path: path) {\n if walkUp(value: operand.value, path: path) == .abortWalk {\n return .abortWalk\n }\n }\n }\n return .continueWalk\n }\n}\n\npublic protocol AddressUseDefWalker {\n associatedtype Path: WalkingPath\n \n /// Starting point of the walk. The implementor can decide to continue the walk by calling\n /// `walkUpDefault(address: address, path: path)` or\n /// do nothing.\n mutating func walkUp(address: Value, path: Path) -> WalkResult\n \n /// `rootDef` is called from `walkUpDefault` when the walk can't continue for this use since\n /// either\n /// * the defining instruction is unknown to the default walker\n /// * the `path` is empty (`""`) and therefore this is the definition of the target value.\n mutating func rootDef(address: Value, path: Path) -> WalkResult\n \n /// `unmatchedPath` is called from `walkUpDefault` when the defining instruction\n /// is unrelated to the `path` the walk should follow.\n mutating func unmatchedPath(address: Value, path: Path) -> WalkResult\n}\n\nextension AddressUseDefWalker {\n \n public mutating func walkUp(address: Value, path: Path) -> WalkResult {\n return walkUpDefault(address: address, path: path)\n }\n \n public mutating func unmatchedPath(address: Value, path: Path) -> WalkResult {\n return .continueWalk\n }\n \n public mutating func walkUpDefault(address def: Value, path: Path) -> WalkResult {\n switch def {\n case let sea as StructElementAddrInst:\n return walkUp(address: sea.struct, path: path.push(.structField, index: sea.fieldIndex))\n case let tea as TupleElementAddrInst:\n return walkUp(address: tea.tuple, path: path.push(.tupleField, index: tea.fieldIndex))\n case let ida as InitEnumDataAddrInst:\n return walkUp(address: ida.operand.value, path: path.push(.enumCase, index: ida.caseIndex))\n case let uteda as UncheckedTakeEnumDataAddrInst:\n return walkUp(address: uteda.operand.value, path: path.push(.enumCase, index: uteda.caseIndex))\n case is InitExistentialAddrInst, is OpenExistentialAddrInst:\n return walkUp(address: (def as! Instruction).operands[0].value, path: path.push(.existential, index: 0))\n case is BeginAccessInst, is MarkUnresolvedNonCopyableValueInst:\n return walkUp(address: (def as! Instruction).operands[0].value, path: path)\n case let ia as IndexAddrInst:\n if let idx = ia.constantIndex {\n return walkUp(address: ia.base, path: path.push(.indexedElement, index: idx))\n } else {\n return walkUp(address: ia.base, path: path.push(.anyIndexedElement, index: 0))\n }\n case is MarkDependenceInst, is MarkUninitializedInst:\n return walkUp(address: (def as! Instruction).operands[0].value, path: path)\n case is MoveOnlyWrapperToCopyableAddrInst,\n is CopyableToMoveOnlyWrapperAddrInst:\n return walkUp(address: (def as! Instruction).operands[0].value, path: path)\n default:\n return rootDef(address: def, path: path)\n }\n }\n}\n\nprivate extension IndexAddrInst {\n var constantIndex: Int? {\n if let literal = index as? IntegerLiteralInst,\n let indexValue = literal.value\n {\n return indexValue\n }\n return nil\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_WalkUtils.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Utilities_WalkUtils.swift
Swift
37,782
0.95
0.196009
0.325255
node-utils
491
2025-03-08T14:36:20.645644
Apache-2.0
false
c3ae1e7989678abee553ace70670de01
//===--- Value.swift - the Value protocol ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basic\nimport SILBridging\n\n@_semantics("arc.immortal")\npublic protocol Value : AnyObject, CustomStringConvertible {\n var uses: UseList { get }\n var type: Type { get }\n var ownership: Ownership { get }\n \n /// The instruction which defines the value.\n ///\n /// This is nil if the value is not defined by an instruction, e.g. an `Argument`.\n var definingInstruction: Instruction? { get }\n \n /// The block where the value is defined.\n var parentBlock: BasicBlock { get }\n\n /// The function where the value lives in.\n ///\n /// It's not legal to get the parentFunction of an instruction in a global initializer.\n var parentFunction: Function { get }\n\n /// True if the value has a trivial type.\n var hasTrivialType: Bool { get }\n\n /// True if the value has a trivial type which is and does not contain a Builtin.RawPointer.\n var hasTrivialNonPointerType: Bool { get }\n\n var isLexical: Bool { get }\n}\n\npublic enum Ownership {\n /// A Value with `unowned` ownership kind is an independent value that\n /// has a lifetime that is only guaranteed to last until the next program\n /// visible side-effect. To maintain the lifetime of an unowned value, it\n /// must be converted to an owned representation via a copy_value.\n ///\n /// Unowned ownership kind occurs mainly along method/function boundaries in\n /// between Swift and Objective-C code.\n case unowned\n \n /// A Value with `owned` ownership kind is an independent value that has\n /// an ownership independent of any other ownership imbued within it. The\n /// Value must be paired with a consuming operation that ends the SSA\n /// value's lifetime exactly once along all paths through the program.\n case owned\n \n /// A Value with `guaranteed` ownership kind is an independent value that\n /// is guaranteed to be live over a specific region of the program. This\n /// region can come in several forms:\n ///\n /// 1. @guaranteed function argument. This guarantees that a value will\n /// outlive a function.\n ///\n /// 2. A shared borrow region. This is a region denoted by a\n /// begin_borrow/load_borrow instruction and an end_borrow instruction. The\n /// SSA value must not be destroyed or taken inside the borrowed region.\n ///\n /// Any value with guaranteed ownership must be paired with an end_borrow\n /// instruction exactly once along any path through the program.\n case guaranteed\n \n /// A Value with `none` ownership kind is an independent value outside of\n /// the ownership system. It is used to model values that are statically\n /// determined to be trivial. This includes trivially typed values as well\n /// as trivial cases of non-trivial enums. Naturally `none` can be merged with\n /// any ownership, allowing us to naturally model merge and branch\n /// points in the SSA graph, where more information about the value is\n /// statically available on some control flow paths.\n case none\n\n public var hasLifetime: Bool {\n switch self {\n case .owned, .guaranteed:\n return true\n case .unowned, .none:\n return false\n }\n }\n\n public init(bridged: BridgedValue.Ownership) {\n switch bridged {\n case .Unowned: self = .unowned\n case .Owned: self = .owned\n case .Guaranteed: self = .guaranteed\n case .None: self = .none\n default:\n fatalError("unsupported ownership")\n }\n }\n\n public var _bridged: BridgedValue.Ownership {\n switch self {\n case .unowned: return BridgedValue.Ownership.Unowned\n case .owned: return BridgedValue.Ownership.Owned\n case .guaranteed: return BridgedValue.Ownership.Guaranteed\n case .none: return BridgedValue.Ownership.None\n }\n }\n}\n\nextension Value {\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n\n public var uses: UseList { UseList(bridged.getFirstUse()) }\n \n // Default implementation for all values which have a parent block, like instructions and arguments.\n public var parentFunction: Function { parentBlock.parentFunction }\n\n public var type: Type { bridged.getType().type }\n\n /// True if the value has a trivial type.\n public var hasTrivialType: Bool { type.isTrivial(in: parentFunction) }\n\n /// True if the value has a trivial type which is and does not contain a Builtin.RawPointer.\n public var hasTrivialNonPointerType: Bool { type.isTrivialNonPointer(in: parentFunction) }\n\n public var ownership: Ownership {\n switch bridged.getOwnership() {\n case .Unowned: return .unowned\n case .Owned: return .owned\n case .Guaranteed: return .guaranteed\n case .None: return .none\n default:\n fatalError("unsupported ownership")\n }\n }\n\n /// Return true if the object type conforms to Escapable.\n ///\n /// Note: noescape function types conform to Escapable, use mayEscape instead to exclude them.\n public var isEscapable: Bool {\n type.objectType.isEscapable(in: parentFunction)\n }\n\n /// Return true only if this value's lifetime is unconstrained by an outer lifetime. Requires all of the following:\n /// - the object type conforms to Escapable\n /// - the type is not a noescape function\n /// - the value is not the direct result of a partial_apply with a noescape (inout_aliasable) capture.\n public var mayEscape: Bool {\n if !type.objectType.mayEscape(in: parentFunction) {\n return false\n }\n // A noescape partial_apply has an escaping function type if it has not been promoted to on_stack, but it's value\n // still cannot "escape" its captures.\n //\n // TODO: This would be much more robust if pai.hasNoescapeCapture simply implied !pai.type.isEscapable\n if let pai = self as? PartialApplyInst {\n return pai.mayEscape\n }\n return true\n }\n\n public var definingInstructionOrTerminator: Instruction? {\n if let def = definingInstruction {\n return def\n } else if let result = TerminatorResult(self) {\n return result.terminator\n }\n return nil\n }\n\n public var nextInstruction: Instruction {\n if self is Argument {\n return parentBlock.instructions.first!\n }\n // Block terminators do not directly produce values.\n return definingInstruction!.next!\n }\n\n public var hashable: HashableValue { ObjectIdentifier(self) }\n\n public var bridged: BridgedValue {\n BridgedValue(obj: SwiftObject(self as AnyObject))\n }\n}\n\npublic typealias HashableValue = ObjectIdentifier\n\n// We can't make `Value` inherit from `Equatable`, since `Equatable` is a PAT,\n// and we do use `Value` existentials around the codebase. Thus functions from\n// `Equatable` are declared separately.\npublic func ==(_ lhs: Value, _ rhs: Value) -> Bool {\n return lhs === rhs\n}\n\npublic func !=(_ lhs: Value, _ rhs: Value) -> Bool {\n return !(lhs === rhs)\n}\n\nextension CollectionLikeSequence where Element == Value {\n public func contains(_ element: Element) -> Bool {\n return self.contains { $0 == element }\n }\n}\n\n/// A projected value, which is defined by the original value and a projection path.\n///\n/// For example, if the `value` is of type `struct S { var x: Int }` and `path` is `s0`,\n/// then the projected value represents field `x` of the original value.\n/// An empty path means represents the "whole" original value.\n///\npublic struct ProjectedValue {\n public let value: Value\n public let path: SmallProjectionPath\n}\n\nextension Value {\n /// Returns a projected value, defined by this value and `path`.\n public func at(_ path: SmallProjectionPath) -> ProjectedValue {\n ProjectedValue(value: self, path: path)\n }\n\n /// Returns a projected value, defined by this value and path containing a single field of `kind` and `index`.\n public func at(_ kind: SmallProjectionPath.FieldKind, index: Int = 0) -> ProjectedValue {\n ProjectedValue(value: self, path: SmallProjectionPath(kind, index: index))\n }\n\n /// Projects all "contained" addresses of this value.\n ///\n /// If this value is an address, projects all sub-fields of the address, e.g. struct fields.\n ///\n /// If this value is not an address, projects all "interior" pointers of the value:\n /// If this value is a class, "interior" pointer means: an address of any stored property of the class instance.\n /// If this value is a struct or another value type, "interior" pointers refer to any stored propery addresses of\n /// any class references in the struct or value type. For example:\n ///\n /// class C { var x: Int; var y: Int }\n /// struct S { var c1: C; var c2: C }\n /// let s: S\n ///\n /// `s.allContainedAddresss` refers to `s.c1.x`, `s.c1.y`, `s.c2.x` and `s.c2.y`\n ///\n public var allContainedAddresss: ProjectedValue {\n if type.isAddress {\n // This is the regular case: the path selects any sub-fields of an address.\n return at(SmallProjectionPath(.anyValueFields))\n }\n if type.isClass {\n // If the value is a (non-address) reference it means: all addresses within the class instance.\n return at(SmallProjectionPath(.anyValueFields).push(.anyClassField))\n }\n // Any other non-address value means: all addresses of any referenced class instances within the value.\n return at(SmallProjectionPath(.anyValueFields).push(.anyClassField).push(.anyValueFields))\n }\n}\n\n\nextension BridgedValue {\n public var value: Value {\n // Doing the type check in C++ is much faster than a conformance lookup with `as! Value`.\n // And it makes a difference because this is a time critical function.\n switch getKind() {\n case .SingleValueInstruction:\n return obj.getAs(SingleValueInstruction.self)\n case .Argument:\n return obj.getAs(Argument.self)\n case .MultipleValueInstructionResult:\n return obj.getAs(MultipleValueInstructionResult.self)\n case .Undef:\n return obj.getAs(Undef.self)\n default:\n fatalError("unknown Value type")\n }\n }\n}\n\npublic final class Undef : Value {\n public var definingInstruction: Instruction? { nil }\n\n public var parentFunction: Function { bridged.SILUndef_getParentFunction().function }\n\n public var parentBlock: BasicBlock {\n // By convention, undefs are considered to be defined at the entry of the function.\n parentFunction.entryBlock\n }\n\n /// Undef has not parent function, therefore the default `hasTrivialType` does not work.\n /// Return the conservative default in this case.\n public var hasTrivialType: Bool { false }\n\n /// Undef has not parent function, therefore the default `hasTrivialNonPointerType` does not work.\n /// Return the conservative default in this case.\n public var hasTrivialNonPointerType: Bool { false }\n\n public var isLexical: Bool { false }\n}\n\nfinal class PlaceholderValue : Value {\n public var definingInstruction: Instruction? { nil }\n\n public var parentBlock: BasicBlock {\n fatalError("PlaceholderValue has no defining block")\n }\n\n public var isLexical: Bool { false }\n\n public var parentFunction: Function { bridged.PlaceholderValue_getParentFunction().function }\n}\n\nextension OptionalBridgedValue {\n public var value: Value? { obj.getAs(AnyObject.self) as? Value }\n}\n\nextension Optional where Wrapped == Value {\n public var bridged: OptionalBridgedValue {\n OptionalBridgedValue(obj: self?.bridged.obj)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Bridging Utilities\n//===----------------------------------------------------------------------===//\n\nextension Array where Element == Value {\n public func withBridgedValues<T>(_ c: (BridgedValueArray) -> T) -> T {\n return self.withUnsafeBufferPointer { bufPtr in\n assert(bufPtr.count == self.count)\n return bufPtr.withMemoryRebound(to: BridgeValueExistential.self) { valPtr in\n return c(BridgedValueArray(base: valPtr.baseAddress, count: self.count))\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Value.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_Value.swift
Swift
12,298
0.95
0.142012
0.367133
node-utils
710
2025-04-28T11:35:59.069012
Apache-2.0
false
cc4ce48fe0d19cc89b2dbf47c8634bd5
//===--- VTable.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\npublic struct VTable : CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedVTable\n\n public init(bridged: BridgedVTable) { self.bridged = bridged }\n\n public struct Entry : CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedVTableEntry\n\n public enum Kind {\n /// The vtable entry is for a method defined directly in this class.\n case normal\n /// The vtable entry is inherited from the superclass.\n case inherited\n /// The vtable entry is inherited from the superclass, and overridden in this class.\n case overridden\n }\n\n fileprivate init(bridged: BridgedVTableEntry) {\n self.bridged = bridged\n }\n\n public init(kind: Kind, isNonOverridden: Bool, methodDecl: DeclRef, implementation: Function) {\n let bridgedKind: BridgedVTableEntry.Kind\n switch kind {\n case .normal: bridgedKind = .Normal\n case .inherited: bridgedKind = .Inherited\n case .overridden: bridgedKind = .Override\n }\n self.bridged = BridgedVTableEntry.create(bridgedKind, isNonOverridden,\n methodDecl.bridged, implementation.bridged)\n }\n\n public var kind: Kind {\n switch bridged.getKind() {\n case .Normal: return .normal\n case .Inherited: return .inherited\n case .Override: return .overridden\n default: fatalError()\n }\n }\n\n public var isNonOverridden: Bool { bridged.isNonOverridden() }\n\n public var methodDecl: DeclRef { DeclRef(bridged: bridged.getMethodDecl()) }\n\n public var implementation: Function { bridged.getImplementation().function }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n }\n\n public struct EntryArray : BridgedRandomAccessCollection {\n fileprivate let bridgedTable: BridgedVTable\n public let count: Int\n \n init(vTable: VTable) {\n self.bridgedTable = vTable.bridged\n self.count = vTable.bridged.getNumEntries()\n }\n\n public var startIndex: Int { return 0 }\n public var endIndex: Int { return count }\n \n public subscript(_ index: Int) -> Entry {\n assert(index >= startIndex && index < endIndex)\n return Entry(bridged: bridgedTable.getEntry(index))\n }\n }\n\n public var entries: EntryArray { EntryArray(vTable: self) }\n\n public var `class`: ClassDecl { bridged.getClass().getAs(ClassDecl.self) }\n\n /// Returns the concrete class type if this is a specialized vTable.\n public var specializedClassType: Type? { bridged.getSpecializedClassType().typeOrNil }\n\n public var isSpecialized: Bool { specializedClassType != nil }\n\n /// A lookup for a specific method with O(1) complexity.\n public func lookup(method: DeclRef) -> Entry? {\n let bridgedEntryOrNil = bridged.lookupMethod(method.bridged)\n if bridgedEntryOrNil.hasEntry {\n return Entry(bridged: bridgedEntryOrNil.entry)\n }\n return nil\n }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n}\n\nextension OptionalBridgedVTable {\n public var vTable: VTable? {\n if let table {\n return VTable(bridged: BridgedVTable(vTable: table))\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_VTable.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_VTable.swift
Swift
3,773
0.95
0.12069
0.172043
python-kit
786
2024-02-03T04:22:43.418765
GPL-3.0
false
dc833a0d762e8a9018ca3a8119a008e7
//===--- WitnessTable.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport AST\nimport SILBridging\n\npublic struct WitnessTable : CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedWitnessTable\n\n public init(bridged: BridgedWitnessTable) { self.bridged = bridged }\n\n public enum Entry : CustomStringConvertible, NoReflectionChildren {\n\n case invalid\n\n /// A witness table entry describing the witness for a method.\n /// The witness can be nil in case dead function elimination has removed the method\n /// or if the method was not serialized (for de-serialized witness tables).\n case method(requirement: DeclRef, witness: Function?)\n\n /// A witness table entry describing the witness for an associated type.\n case associatedType(requirement: AssociatedTypeDecl, witness: CanonicalType)\n\n /// A witness table entry describing the witness for an associated type's protocol requirement.\n case associatedConformance(requirement: CanonicalType, witness: Conformance)\n\n /// A witness table entry referencing the protocol conformance for a refined base protocol.\n case baseProtocol(requirement: ProtocolDecl, witness: Conformance)\n\n fileprivate init(bridged: BridgedWitnessTableEntry) {\n switch bridged.getKind() {\n case .invalid:\n self = .invalid\n case .method:\n self = .method(requirement: DeclRef(bridged: bridged.getMethodRequirement()),\n witness: bridged.getMethodWitness().function)\n case .associatedType:\n self = .associatedType(requirement: bridged.getAssociatedTypeRequirement().getAs(AssociatedTypeDecl.self),\n witness: CanonicalType(bridged: bridged.getAssociatedTypeWitness()))\n case .associatedConformance:\n self = .associatedConformance(requirement: CanonicalType(bridged: bridged.getAssociatedConformanceRequirement()),\n witness: Conformance(bridged: bridged.getAssociatedConformanceWitness()))\n case .baseProtocol:\n self = .baseProtocol(requirement: bridged.getBaseProtocolRequirement().getAs(ProtocolDecl.self),\n witness: Conformance(bridged: bridged.getBaseProtocolWitness()))\n default:\n fatalError("invalid witness table entry")\n }\n }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n\n public var bridged: BridgedWitnessTableEntry {\n switch self {\n case .invalid:\n return BridgedWitnessTableEntry.createInvalid()\n case .method(let requirement, let witness):\n return BridgedWitnessTableEntry.createMethod(requirement.bridged,\n OptionalBridgedFunction(obj: witness?.bridged.obj))\n case .associatedType(let requirement, let witness):\n return BridgedWitnessTableEntry.createAssociatedType(requirement.bridged, witness.bridged)\n case .associatedConformance(let requirement, let witness):\n return BridgedWitnessTableEntry.createAssociatedConformance(requirement.bridged,\n witness.bridged)\n case .baseProtocol(let requirement, let witness):\n return BridgedWitnessTableEntry.createBaseProtocol(requirement.bridged, witness.bridged)\n }\n }\n }\n\n public struct EntryArray : BridgedRandomAccessCollection {\n fileprivate let bridgedTable: BridgedWitnessTable\n public let count: Int\n \n init(witnessTable: WitnessTable) {\n self.bridgedTable = witnessTable.bridged\n self.count = witnessTable.bridged.getNumEntries()\n }\n\n public var startIndex: Int { 0 }\n public var endIndex: Int { count }\n\n public subscript(_ index: Int) -> Entry {\n precondition(index >= startIndex && index < endIndex)\n return Entry(bridged: bridgedTable.getEntry(index))\n }\n }\n\n /// A lookup for a specific method with O(n) complexity.\n public func lookup(method: DeclRef) -> Function? {\n for entry in entries {\n if case .method(let req, let impl) = entry, req == method {\n return impl\n }\n }\n return nil\n }\n\n public var entries: EntryArray { EntryArray(witnessTable: self) }\n\n public var isDefinition: Bool { !bridged.isDeclaration() }\n\n // True, if this is a specialized witness table (currently only used in embedded mode).\n public var isSpecialized: Bool { bridged.isSpecialized() }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n}\n\npublic struct DefaultWitnessTable : CustomStringConvertible, NoReflectionChildren {\n public let bridged: BridgedDefaultWitnessTable\n\n public init(bridged: BridgedDefaultWitnessTable) { self.bridged = bridged }\n\n public typealias Entry = WitnessTable.Entry\n\n public struct EntryArray : BridgedRandomAccessCollection {\n fileprivate let bridgedTable: BridgedDefaultWitnessTable\n public let count: Int\n\n init(witnessTable: DefaultWitnessTable) {\n self.bridgedTable = witnessTable.bridged\n self.count = witnessTable.bridged.getNumEntries()\n }\n\n public var startIndex: Int { 0 }\n public var endIndex: Int { count }\n\n public subscript(_ index: Int) -> Entry {\n precondition(index >= startIndex && index < endIndex)\n return Entry(bridged: bridgedTable.getEntry(index))\n }\n }\n\n public var entries: EntryArray { EntryArray(witnessTable: self) }\n\n public var description: String {\n return String(taking: bridged.getDebugDescription())\n }\n}\n\nextension OptionalBridgedWitnessTable {\n public var witnessTable: WitnessTable? {\n if let table = table {\n return WitnessTable(bridged: BridgedWitnessTable(table: table))\n }\n return nil\n }\n}\n\nextension OptionalBridgedDefaultWitnessTable {\n public var defaultWitnessTable: DefaultWitnessTable? {\n if let table = table {\n return DefaultWitnessTable(bridged: BridgedDefaultWitnessTable(table: table))\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_SwiftCompilerSources_Sources_SIL_WitnessTable.swift
cpp_apple_swift_SwiftCompilerSources_Sources_SIL_WitnessTable.swift
Swift
6,434
0.95
0.105882
0.137681
react-lib
48
2024-01-13T13:43:47.172262
BSD-3-Clause
false
36394ae48b04e106de033d47d798c236
// swift-tools-version:5.3\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\nimport class Foundation.ProcessInfo\n\nlet package = Package(\n name: "swift-inspect",\n products: [\n .library(name: "SwiftInspectClient", type: .dynamic, targets: ["SwiftInspectClient"]),\n ],\n targets: [\n // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n // Targets can depend on other targets in this package, and on products in packages which this package depends on.\n .target(\n name: "swift-inspect",\n dependencies: [\n "SymbolicationShims",\n .product(name: "ArgumentParser", package: "swift-argument-parser"),\n .target(name: "SwiftInspectClient", condition: .when(platforms: [.windows])),\n .target(name: "SwiftInspectClientInterface", condition: .when(platforms: [.windows])),\n .target(name: "SwiftInspectLinux", condition: .when(platforms: [.linux, .android])),\n .target(name: "AndroidCLib", condition: .when(platforms: [.android])),\n ],\n swiftSettings: [.unsafeFlags(["-parse-as-library"])]),\n .target(name: "SwiftInspectClient"),\n .target(\n name: "SwiftInspectLinux",\n dependencies: ["LinuxSystemHeaders"],\n path: "Sources/SwiftInspectLinux",\n exclude: ["SystemHeaders"],\n cSettings: [.define("_GNU_SOURCE", to: "1")]),\n .systemLibrary(\n name: "LinuxSystemHeaders",\n path: "Sources/SwiftInspectLinux/SystemHeaders"),\n .target(\n name: "AndroidCLib",\n path: "Sources/AndroidCLib",\n publicHeadersPath: "include",\n cSettings: [.unsafeFlags(["-fPIC"])]),\n .systemLibrary(\n name: "SwiftInspectClientInterface"),\n .testTarget(\n name: "swiftInspectTests",\n dependencies: ["swift-inspect"]),\n .systemLibrary(\n name: "SymbolicationShims")\n ]\n)\n\nif ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {\n package.dependencies += [\n .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0"),\n ]\n} else {\n package.dependencies += [.package(path: "../../../swift-argument-parser")]\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Package.swift
cpp_apple_swift_tools_swift-inspect_Package.swift
Swift
2,424
0.95
0.035088
0.074074
python-kit
561
2024-11-03T21:18:32.785542
BSD-3-Clause
false
8e78f07b2230d93397c631dd7bc8fc15
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(Android)\n\nimport AndroidCLib\nimport Foundation\nimport LinuxSystemHeaders\nimport SwiftInspectLinux\nimport SwiftRemoteMirror\n\nextension MemoryMap.Entry {\n public func isHeapRegion() -> Bool {\n guard let name = self.pathname else { return false }\n // The heap region naming convention is found in AOSP's libmemunreachable at\n // android/platform/system/memory/libmemunreachable/MemUnreachable.cpp.\n if name == "[anon:libc_malloc]" { return true }\n if name.hasPrefix("[anon:scudo:") { return true }\n if name.hasPrefix("[anon:GWP-ASan") { return true }\n return false\n }\n}\n\ninternal final class AndroidRemoteProcess: LinuxRemoteProcess {\n enum RemoteProcessError: Error {\n case missingSymbol(_ name: String)\n case heapIterationFailed\n }\n\n struct RemoteSymbol {\n let addr: UInt64?\n let name: String\n init(_ name: String, _ symbolCache: SymbolCache) {\n self.name = name\n if let symbolRange = symbolCache.address(of: name) {\n self.addr = symbolRange.start\n } else {\n self.addr = nil\n }\n }\n }\n\n // We call mmap/munmap in the remote process to alloc/free memory for our own\n // use without impacting existing allocations in the remote process.\n lazy var mmapSymbol: RemoteSymbol = RemoteSymbol("mmap", self.symbolCache)\n lazy var munmapSymbol: RemoteSymbol = RemoteSymbol("munmap", self.symbolCache)\n\n // We call malloc_iterate in the remote process to enumerate all items in the\n // remote process' heap. We use malloc_disable/malloc_enable to ensure no\n // malloc/free requests can race with malloc_iterate.\n lazy var mallocDisableSymbol: RemoteSymbol = RemoteSymbol("malloc_disable", self.symbolCache)\n lazy var mallocEnableSymbol: RemoteSymbol = RemoteSymbol("malloc_enable", self.symbolCache)\n lazy var mallocIterateSymbol: RemoteSymbol = RemoteSymbol("malloc_iterate", self.symbolCache)\n\n // Linux and Android have no supported method to enumerate allocations in the\n // heap of a remote process. Android does, however, support the malloc_iterate\n // API, which enumerates allocations in the current process. We leverage this\n // API by invoking it in the remote process with ptrace and using simple IPC\n // (SIGTRAP and process_vm_readv and process_vm_writev) to fetch the results.\n override internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) {\n var regionCount = 0\n var allocCount = 0\n do {\n try withPTracedProcess(pid: self.processIdentifier) { ptrace in\n for entry in self.memoryMap.entries {\n // Limiting malloc_iterate calls to only memory regions that are known\n // to contain heap allocations is not strictly necessary but it does\n // significantly improve the speed of heap iteration.\n guard entry.isHeapRegion() else { continue }\n\n // collect all of the allocations in this heap region\n let allocations: [(base: swift_addr_t, len: UInt64)]\n allocations = try self.iterateHeapRegion(ptrace, region: entry)\n regionCount += 1\n allocCount += allocations.count\n\n // process all of the collected allocations\n for alloc in allocations { body(alloc.base, alloc.len) }\n }\n }\n } catch {\n print("failed iterating remote heap: \(error)")\n return\n }\n\n if regionCount == 0 {\n // This condition most likely indicates the MemoryMap.Entry.isHeapRegion\n // filtering is needs to be modified to support a new heap region naming\n // convention in a newer Android version.\n print("WARNING: no heap regions found")\n print("swift-inspect may need to be updated for a newer Android version")\n } else if allocCount == 0 {\n print("WARNING: no heap items enumerated")\n }\n }\n\n // Iterate a single heap region in the remote process and return an array\n // of (base, len) pairs describing each heap allocation in the region.\n internal func iterateHeapRegion(_ ptrace: borrowing PTrace, region: MemoryMap.Entry) throws -> [(\n base: swift_addr_t, len: UInt64\n )] {\n // Allocate a page-sized buffer in the remote process that malloc_iterate\n // will populaate with metadata describing each heap entry it enumerates.\n let dataLen = sysconf(Int32(_SC_PAGESIZE))\n let remoteDataAddr = try self.mmapRemote(\n ptrace, len: dataLen, prot: PROT_READ | PROT_WRITE, flags: MAP_ANON | MAP_PRIVATE)\n defer {\n _ = try? self.munmapRemote(ptrace, addr: remoteDataAddr, len: dataLen)\n }\n\n // Allocate and inialize a local buffer that will be used to copy metadata\n // to/from the target process.\n let buffer = UnsafeMutableRawPointer.allocate(\n byteCount: dataLen, alignment: MemoryLayout<UInt64>.alignment)\n defer { buffer.deallocate() }\n guard heap_iterate_metadata_init(buffer, dataLen) else {\n throw RemoteProcessError.heapIterationFailed\n }\n try self.process.writeMem(remoteAddr: remoteDataAddr, localAddr: buffer, len: UInt(dataLen))\n\n // Allocate an rwx region to hold the malloc_iterate callback that will be\n // executed in the remote process.\n let codeLen = heap_iterate_callback_len()\n let remoteCodeAddr = try mmapRemote(\n ptrace, len: codeLen, prot: PROT_READ | PROT_WRITE | PROT_EXEC, flags: MAP_ANON | MAP_PRIVATE)\n defer {\n _ = try? self.munmapRemote(ptrace, addr: remoteCodeAddr, len: codeLen)\n }\n\n // Copy the malloc_iterate callback implementation to the remote process.\n let codeStart = heap_iterate_callback_start()!\n try self.process.writeMem(\n remoteAddr: remoteCodeAddr, localAddr: codeStart, len: UInt(codeLen))\n\n guard let mallocIterateAddr = self.mallocIterateSymbol.addr else {\n throw RemoteProcessError.missingSymbol(self.mallocIterateSymbol.name)\n }\n\n // Disable malloc/free while enumerating the region to get a consistent\n // snapshot of existing allocations.\n try self.mallocDisableRemote(ptrace)\n defer {\n _ = try? self.mallocEnableRemote(ptrace)\n }\n\n // Collects (base, len) pairs describing each heap allocation in the remote\n // process.\n var allocations: [(base: swift_addr_t, len: UInt64)] = []\n\n let regionLen = region.endAddr - region.startAddr\n let args = [region.startAddr, regionLen, remoteCodeAddr, remoteDataAddr]\n _ = try ptrace.jump(to: mallocIterateAddr, with: args) { ptrace in\n // This callback is invoked when a SIGTRAP is encountered in the remote\n // process. In this context, this signal indicates there is no more room\n // in the allocated metadata region (see AndroidCLib/heap.c).\n // Immediately read the heap metadata from the remote process, skip past\n // the trap/break instruction, and resume the remote process.\n try self.process.readMem(remoteAddr: remoteDataAddr, localAddr: buffer, len: UInt(dataLen))\n allocations.append(contentsOf: try self.processHeapMetadata(buffer: buffer, len: dataLen))\n\n guard heap_iterate_metadata_init(buffer, dataLen) else {\n throw RemoteProcessError.heapIterationFailed\n }\n try self.process.writeMem(remoteAddr: remoteDataAddr, localAddr: buffer, len: UInt(dataLen))\n\n var regs = try ptrace.getRegSet()\n regs.step(RegisterSet.trapInstructionSize)\n\n try ptrace.setRegSet(regSet: regs)\n try ptrace.cont()\n }\n\n try self.process.readMem(remoteAddr: remoteDataAddr, localAddr: buffer, len: UInt(dataLen))\n allocations.append(contentsOf: try self.processHeapMetadata(buffer: buffer, len: dataLen))\n\n return allocations\n }\n\n // Process heap metadata generated by our malloc_iterate callback in the\n // remote process and return an array of (base, len) pairs describing each\n // heap allocation.\n internal func processHeapMetadata(buffer: UnsafeMutableRawPointer, len: Int) throws -> [(\n base: UInt64, len: UInt64\n )] {\n let callback: @convention(c) (UnsafeMutableRawPointer?, UInt64, UInt64) -> Void = {\n let allocationsPointer = $0!.assumingMemoryBound(to: [(UInt64, UInt64)].self)\n allocationsPointer.pointee.append(($1, $2))\n }\n\n var allocations: [(UInt64, UInt64)] = []\n try withUnsafeMutablePointer(to: &allocations) {\n let context = UnsafeMutableRawPointer($0)\n if !heap_iterate_metadata_process(buffer, Int(len), context, callback) {\n throw RemoteProcessError.heapIterationFailed\n }\n }\n\n return allocations\n }\n\n // call mmap in the remote process with the provided arguments\n internal func mmapRemote(_ ptrace: borrowing PTrace, len: Int, prot: Int32, flags: Int32) throws\n -> UInt64\n {\n guard let sym = self.mmapSymbol.addr else {\n throw RemoteProcessError.missingSymbol(self.mmapSymbol.name)\n }\n let args = [0, UInt64(len), UInt64(prot), UInt64(flags)]\n return try ptrace.jump(to: sym, with: args)\n }\n\n // call munmap in the remote process with the provdied arguments\n internal func munmapRemote(_ ptrace: borrowing PTrace, addr: UInt64, len: Int) throws -> UInt64 {\n guard let sym = self.munmapSymbol.addr else {\n throw RemoteProcessError.missingSymbol(self.munmapSymbol.name)\n }\n let args: [UInt64] = [addr, UInt64(len)]\n return try ptrace.jump(to: sym, with: args)\n }\n\n // call malloc_disable in the remote process\n internal func mallocDisableRemote(_ ptrace: borrowing PTrace) throws {\n guard let sym = self.mallocDisableSymbol.addr else {\n throw RemoteProcessError.missingSymbol(self.mallocDisableSymbol.name)\n }\n _ = try ptrace.jump(to: sym)\n }\n\n // call malloc_enable in the remote process\n internal func mallocEnableRemote(_ ptrace: borrowing PTrace) throws {\n guard let sym = self.mallocEnableSymbol.addr else {\n throw RemoteProcessError.missingSymbol(self.mallocEnableSymbol.name)\n }\n _ = try ptrace.jump(to: sym)\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_AndroidRemoteProcess.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_AndroidRemoteProcess.swift
Swift
10,299
0.95
0.165992
0.269767
vue-tools
383
2024-11-05T02:09:32.751269
MIT
false
84bd5747bfae41fb93fa89a558e5d518
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftRemoteMirror\n\ninternal enum BacktraceStyle {\n case oneline\n case long\n}\n\ninternal func backtrace(_ stack: [swift_reflection_ptr_t], style: BacktraceStyle,\n _ symbolicate: (swift_addr_t) -> (module: String?, symbol: String?)) -> String {\n func entry(_ address: swift_reflection_ptr_t) -> String {\n let (module, symbol) = symbolicate(swift_addr_t(address))\n return "\(hex: address) (\(module ?? "<unknown>")) \(symbol ?? "<unknown>")"\n }\n\n // The pointers to the locations in the backtrace are stored from deepest to\n // shallowest, so `main` will be somewhere near the end.\n switch style {\n case .oneline:\n return stack.reversed().map { entry($0) }.joined(separator: " | ")\n case .long:\n return stack.reversed().enumerated().map {\n " \(String(repeating: " ", count: $0 + 1))\(entry($1))"\n }.joined(separator: "\n")\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Backtrace.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Backtrace.swift
Swift
1,405
0.95
0.081081
0.393939
node-utils
89
2023-11-21T01:36:31.337831
BSD-3-Clause
false
13eba5c19e438cc81e1dd565d546d02e
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n\nimport SwiftRemoteMirror\nimport SymbolicationShims\n\ninternal final class DarwinRemoteProcess: RemoteProcess {\n public typealias ProcessIdentifier = pid_t\n public typealias ProcessHandle = task_t\n\n private var task: task_t\n internal var processIdentifier: ProcessIdentifier\n internal lazy var processName = getProcessName(processId: processIdentifier) ?? "<unknown process>"\n\n public var process: ProcessHandle { task }\n public private(set) var context: SwiftReflectionContextRef!\n private var symbolicator: CSSymbolicatorRef\n\n private var swiftCore: CSTypeRef\n private let swiftConcurrency: CSTypeRef\n\n private lazy var threadInfos = getThreadInfos()\n\n static var QueryDataLayout: QueryDataLayoutFunction {\n return { (context, type, _, output) in\n guard let output = output else { return 0 }\n\n switch type {\n case DLQ_GetPointerSize, DLQ_GetSizeSize:\n let size = UInt8(MemoryLayout<UnsafeRawPointer>.stride)\n output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetPtrAuthMask:\n let mask = GetPtrauthMask()\n output.storeBytes(of: mask, toByteOffset: 0, as: UInt.self)\n return 1\n\n case DLQ_GetObjCReservedLowBits:\n var size: UInt8 = 0\n#if os(macOS)\n // Only 64-bit macOS reserves pointer bit-packing.\n if MemoryLayout<UnsafeRawPointer>.stride == 8 { size = 1 }\n#endif\n output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetLeastValidPointerValue:\n var value: UInt64 = 0x1000\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n // 64-bit Apple platforms reserve the low 4GiB.\n if MemoryLayout<UnsafeRawPointer>.stride == 8 { value = 0x1_0000_0000 }\n#endif\n output.storeBytes(of: value, toByteOffset: 0, as: UInt64.self)\n return 1\n\n default:\n return 0\n }\n }\n }\n\n func read(address: swift_addr_t, size: Int) -> UnsafeRawPointer? {\n return task_peek(task, address, mach_vm_size_t(size))\n }\n\n func getAddr(symbolName: String) -> swift_addr_t {\n // FIXME: use `__USER_LABEL_PREFIX__` instead of the hardcoded `_`.\n let fullName = "_\(symbolName)"\n var symbol = CSSymbolOwnerGetSymbolWithMangledName(swiftCore, fullName)\n if CSIsNull(symbol) {\n symbol = CSSymbolOwnerGetSymbolWithMangledName(swiftConcurrency, fullName)\n }\n let range = CSSymbolGetRange(symbol)\n return swift_addr_t(range.location)\n }\n\n static var Free: FreeFunction? { return nil }\n\n static var ReadBytes: ReadBytesFunction {\n return { (context, address, size, _) in\n let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)\n return process.read(address: address, size: Int(size))\n }\n }\n\n static var GetStringLength: GetStringLengthFunction {\n return { (context, address) in\n let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)\n if let str = task_peek_string(process.task, address) {\n return UInt64(strlen(str))\n }\n return 0\n }\n }\n\n static var GetSymbolAddress: GetSymbolAddressFunction {\n return { (context, symbol, length) in\n let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)\n guard let symbol = symbol else { return 0 }\n let name: String = symbol.withMemoryRebound(to: UInt8.self, capacity: Int(length)) {\n let buffer = UnsafeBufferPointer(start: $0, count: Int(length))\n return String(decoding: buffer, as: UTF8.self)\n }\n return process.getAddr(symbolName: name)\n }\n }\n\n init?(processId: ProcessIdentifier, forkCorpse: Bool) {\n processIdentifier = processId\n var task: task_t = task_t()\n let taskResult = task_for_pid(mach_task_self_, processId, &task)\n guard taskResult == KERN_SUCCESS else {\n print("unable to get task for pid \(processId): \(String(cString: mach_error_string(taskResult))) \(hex: taskResult)",\n to: &Std.err)\n return nil\n }\n\n // Consult with VMUProcInfo to determine if we should force forkCorpse.\n let forceForkCorpse: Bool\n if let procInfoClass = getVMUProcInfoClass() {\n let procInfo = procInfoClass.init(task: task)\n forceForkCorpse = procInfo.shouldAnalyzeWithCorpse\n } else {\n // Default to not forcing forkCorpse.\n forceForkCorpse = false\n }\n\n if forkCorpse || forceForkCorpse {\n var corpse = task_t()\n let maxRetry = 6\n for retry in 0..<maxRetry {\n let corpseResult = task_generate_corpse(task, &corpse)\n if corpseResult == KERN_SUCCESS {\n task_stop_peeking(task)\n mach_port_deallocate(mach_task_self_, task)\n task = corpse\n break\n }\n if corpseResult != KERN_RESOURCE_SHORTAGE || retry == maxRetry {\n print("unable to fork corpse for pid \(processId): \(String(cString: mach_error_string(corpseResult))) \(hex: corpseResult)",\n to: &Std.err)\n return nil\n }\n sleep(UInt32(1 << retry))\n }\n }\n\n self.task = task\n\n self.symbolicator = CSSymbolicatorCreateWithTask(self.task)\n self.swiftCore =\n CSSymbolicatorGetSymbolOwnerWithNameAtTime(self.symbolicator,\n "libswiftCore.dylib", kCSNow)\n if CSIsNull(self.swiftCore) {\n print("pid \(processId) does not have libswiftCore.dylib loaded")\n return nil\n }\n\n self.swiftConcurrency = CSSymbolicatorGetSymbolOwnerWithNameAtTime(\n symbolicator, "libswift_Concurrency.dylib", kCSNow)\n _ = task_start_peeking(self.task)\n\n guard let context =\n swift_reflection_createReflectionContextWithDataLayout(self.toOpaqueRef(),\n Self.QueryDataLayout,\n Self.Free,\n Self.ReadBytes,\n Self.GetStringLength,\n Self.GetSymbolAddress) else {\n return nil\n }\n self.context = context\n\n _ = CSSymbolicatorForeachSymbolOwnerAtTime(self.symbolicator, kCSNow, { owner in\n let address = CSSymbolOwnerGetBaseAddress(owner)\n _ = swift_reflection_addImage(self.context, address)\n })\n }\n\n deinit {\n task_stop_peeking(self.task)\n CSRelease(self.symbolicator)\n mach_port_deallocate(mach_task_self_, self.task)\n }\n\n func symbolicate(_ address: swift_addr_t) -> (module: String?, symbol: String?) {\n let symbol =\n CSSymbolicatorGetSymbolWithAddressAtTime(self.symbolicator, address, kCSNow)\n\n let module = CSSymbolGetSymbolOwner(symbol)\n return (CSSymbolOwnerGetName(module), CSSymbolGetName(symbol))\n }\n\n internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) {\n withoutActuallyEscaping(body) {\n withUnsafePointer(to: $0) {\n task_enumerate_malloc_blocks(self.task,\n UnsafeMutableRawPointer(mutating: $0),\n CUnsignedInt(MALLOC_PTR_IN_USE_RANGE_TYPE),\n { (task, context, type, ranges, count) in\n let callback: (swift_addr_t, UInt64) -> Void =\n context!.assumingMemoryBound(to: ((swift_addr_t, UInt64) -> Void).self).pointee\n for i in 0..<Int(count) {\n let range = ranges[i]\n callback(swift_addr_t(range.address), UInt64(range.size))\n }\n })\n }\n }\n }\n}\n\nextension DarwinRemoteProcess {\n private class PortList: Sequence {\n let buffer: UnsafeBufferPointer<mach_port_t>\n\n init?(task: task_t) {\n var threadList: UnsafeMutablePointer<mach_port_t>?\n var threadCount: mach_msg_type_number_t = 0\n\n let result = task_threads(task, &threadList, &threadCount)\n guard result == KERN_SUCCESS else {\n print("unable to gather threads for process: \(String(cString: mach_error_string(result))) (0x\(String(result, radix: 16)))")\n return nil\n }\n\n buffer = UnsafeBufferPointer(start: threadList, count: Int(threadCount))\n }\n\n deinit {\n // Deallocate the port rights for the threads.\n for thread in self {\n mach_port_deallocate(mach_task_self_, thread)\n }\n\n // Deallocate the thread list.\n let pointer = vm_address_t(truncatingIfNeeded: Int(bitPattern: buffer.baseAddress))\n let size = vm_size_t(MemoryLayout<mach_port_t>.size) * vm_size_t(buffer.count)\n\n vm_deallocate(mach_task_self_, pointer, size)\n }\n\n func makeIterator() -> UnsafeBufferPointer<thread_t>.Iterator {\n return buffer.makeIterator()\n }\n }\n\n private struct ThreadInfo {\n var threadID: UInt64\n var tlsStart: UInt64\n var kernelObject: UInt32?\n }\n\n private func getThreadInfos() -> [ThreadInfo] {\n guard let threads = PortList(task: self.task) else {\n return []\n }\n return threads.compactMap {\n guard let info = getThreadInfo(thread: $0) else {\n return nil\n }\n guard let kernelObj = getKernelObject(task: mach_task_self_, port: $0) else {\n return nil\n }\n return ThreadInfo(threadID: info.thread_id,\n tlsStart: info.thread_handle,\n kernelObject: kernelObj)\n }\n }\n\n private func getKernelObject(task: task_t, port: mach_port_t) -> UInt32? {\n var object: UInt32 = 0\n var type: UInt32 = 0\n let result = mach_port_kernel_object(task, port, &type, &object)\n guard result == KERN_SUCCESS else {\n return nil\n }\n return object\n }\n\n private func getThreadInfo(thread: thread_t) -> thread_identifier_info_data_t? {\n let THREAD_IDENTIFIER_INFO_COUNT =\n MemoryLayout<thread_identifier_info_data_t>.size / MemoryLayout<natural_t>.size\n var info = thread_identifier_info_data_t()\n var infoCount = mach_msg_type_number_t(THREAD_IDENTIFIER_INFO_COUNT)\n var result: kern_return_t = 0\n\n withUnsafeMutablePointer(to: &info) {\n $0.withMemoryRebound(to: integer_t.self, capacity: THREAD_IDENTIFIER_INFO_COUNT) {\n result = thread_info(thread, thread_flavor_t(THREAD_IDENTIFIER_INFO),\n $0, &infoCount)\n }\n }\n guard result == KERN_SUCCESS else {\n print("unable to get info for thread port \(thread): \(String(cString: mach_error_string(result))) (0x\(String(result, radix: 16)))")\n return nil\n }\n return info\n }\n}\n\nextension DarwinRemoteProcess {\n internal var currentTasks: [(threadID: UInt64, currentTask: swift_addr_t)] {\n return threadInfos.compactMap {\n let tlsStart = $0.tlsStart\n if tlsStart == 0 { return nil }\n\n let SWIFT_CONCURRENCY_TASK_KEY = 103\n let currentTaskPointer = tlsStart + UInt64(SWIFT_CONCURRENCY_TASK_KEY * MemoryLayout<UnsafeRawPointer>.size)\n guard let pointer = read(address: currentTaskPointer, size: MemoryLayout<UnsafeRawPointer>.size) else {\n return nil\n }\n let currentTask = pointer.load(as: UInt.self)\n return (threadID: $0.threadID, currentTask: swift_addr_t(currentTask))\n }\n }\n\n internal func getThreadID(remotePort: thread_t) -> UInt64? {\n guard let remoteThreadObj = getKernelObject(task: self.task, port: remotePort) else {\n return nil\n }\n return threadInfos.first{ $0.kernelObject == remoteThreadObj }?.threadID\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_DarwinRemoteProcess.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_DarwinRemoteProcess.swift
Swift
11,985
0.95
0.079882
0.082759
react-lib
910
2024-04-15T14:03:48.807315
GPL-3.0
false
ae3b8e94fceb3326e95b9aad36439ee0
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(Linux) || os(Android)\n import Foundation\n import SwiftInspectLinux\n import SwiftRemoteMirror\n\n internal class LinuxRemoteProcess: RemoteProcess {\n public typealias ProcessIdentifier = pid_t\n public typealias ProcessHandle = SwiftInspectLinux.Process\n\n public private(set) var process: ProcessHandle\n public private(set) var context: SwiftReflectionContextRef!\n public private(set) var processIdentifier: ProcessIdentifier\n public private(set) var processName: String = "<unknown process>"\n\n let memoryMap: SwiftInspectLinux.MemoryMap\n let symbolCache: SwiftInspectLinux.SymbolCache\n\n static var QueryDataLayout: QueryDataLayoutFunction {\n return { (context, type, _, output) in\n guard let output = output else { return 0 }\n\n switch type {\n case DLQ_GetPointerSize:\n let size = UInt8(MemoryLayout<UnsafeRawPointer>.stride)\n output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetSizeSize:\n let size = UInt8(MemoryLayout<UInt>.stride) // UInt is word-size like size_t\n output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetLeastValidPointerValue:\n let value: UInt64 = 0x1000\n output.storeBytes(of: value, toByteOffset: 0, as: UInt64.self)\n return 1\n\n default: return 0\n }\n }\n }\n\n static var Free: FreeFunction? {\n return { (_, bytes, _) in free(UnsafeMutableRawPointer(mutating: bytes)) }\n }\n\n static var ReadBytes: ReadBytesFunction {\n return { (context, address, size, _) in\n let process: LinuxRemoteProcess = LinuxRemoteProcess.fromOpaque(context!)\n\n guard\n let byteArray: [UInt8] = try? process.process.readArray(\n address: address, upToCount: UInt(size)), let buffer = malloc(byteArray.count)\n else { return nil }\n\n byteArray.withUnsafeBytes {\n buffer.copyMemory(from: $0.baseAddress!, byteCount: byteArray.count)\n }\n\n return UnsafeRawPointer(buffer)\n }\n }\n\n static var GetStringLength: GetStringLengthFunction {\n return { (context, address) in\n let process: LinuxRemoteProcess = LinuxRemoteProcess.fromOpaque(context!)\n\n // copy the string from the remote proces to get its length\n guard let bytes = try? process.process.readRawString(address: address),\n let len = UInt64(exactly: bytes.count)\n else { return 0 }\n return len\n }\n }\n\n static var GetSymbolAddress: GetSymbolAddressFunction {\n return { (context, symbol, length) in\n let process: LinuxRemoteProcess = LinuxRemoteProcess.fromOpaque(context!)\n\n guard let symbol = symbol else { return 0 }\n let name: String = symbol.withMemoryRebound(to: UInt8.self, capacity: Int(length)) {\n let buffer = UnsafeBufferPointer(start: $0, count: Int(length))\n return String(decoding: buffer, as: UTF8.self)\n }\n\n guard let (startAddr, _) = process.symbolCache.address(of: name) else { return 0 }\n return startAddr\n }\n }\n\n init?(processId: ProcessIdentifier) {\n self.processIdentifier = processId\n\n if let processName = SwiftInspectLinux.ProcFS.loadFileAsString(for: processId, "cmdline") {\n self.processName = processName\n }\n\n do {\n self.process = try SwiftInspectLinux.Process(processId)\n self.symbolCache = try SwiftInspectLinux.SymbolCache(for: process)\n self.memoryMap = try SwiftInspectLinux.MemoryMap(for: processId)\n } catch {\n fatalError("failed initialization for process \(processId): \(error)")\n return nil\n }\n\n guard\n let context = swift_reflection_createReflectionContextWithDataLayout(\n self.toOpaqueRef(), Self.QueryDataLayout, Self.Free, Self.ReadBytes, Self.GetStringLength,\n Self.GetSymbolAddress)\n else { return nil }\n self.context = context\n }\n\n func symbolicate(_ address: swift_addr_t) -> (module: String?, symbol: String?) {\n let moduleName: String?\n let symbolName: String?\n if let symbol = self.symbolCache.symbol(for: address) {\n moduleName = symbol.module\n symbolName = symbol.name\n } else if let mapEntry = memoryMap.findEntry(containing: address) {\n // found no name for the symbol, but there is a memory region containing\n // the address so use its name as the module name\n moduleName = mapEntry.pathname\n symbolName = nil\n } else {\n moduleName = nil\n symbolName = nil\n }\n\n // return only the basename of the module path to keep callstacks brief\n let moduleBaseName: String?\n if let filePath = moduleName, let url = URL(string: filePath) {\n moduleBaseName = url.lastPathComponent\n } else {\n moduleBaseName = moduleName\n }\n\n return (moduleBaseName, symbolName)\n }\n\n internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) {\n fatalError("heap iteration is not supported on Linux")\n }\n }\n#endif // os(Linux)\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_LinuxRemoteProcess.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_LinuxRemoteProcess.swift
Swift
5,653
0.95
0.132911
0.129771
python-kit
54
2025-04-17T09:30:25.350067
GPL-3.0
false
6ac8a7e9f8f90163b032ce0077a25972
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport SwiftRemoteMirror\nimport Foundation\n\n\ninternal struct UniversalOptions: ParsableArguments {\n @Argument(help: "The pid or partial name of the target process")\n var nameOrPid: String?\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n @Flag(help: ArgumentHelp(\n "Fork a corpse of the target process",\n discussion: "Creates a low-level copy of the target process, allowing " +\n "the target to immediately resume execution before " +\n "swift-inspect has completed its work."))\n#endif\n var forkCorpse: Bool = false\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n @Flag(help: "Run on all processes")\n#endif\n var all: Bool = false\n\n mutating func validate() throws {\n if nameOrPid != nil && all || nameOrPid == nil && !all {\n #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n throw ValidationError("Please specify partial process name, pid or --all")\n #else\n throw ValidationError("Please specify partial process name or pid")\n #endif\n }\n if all {\n // Fork corpse is enabled if all is specified\n forkCorpse = true\n }\n }\n}\n\ninternal struct BacktraceOptions: ParsableArguments {\n @Flag(help: "Show the backtrace for each allocation")\n var backtrace: Bool = false\n\n @Flag(help: "Show a long-form backtrace for each allocation")\n var backtraceLong: Bool = false\n\n var style: BacktraceStyle? {\n if backtraceLong { return .long }\n if backtrace { return .oneline }\n return nil\n }\n}\n\ninternal struct GenericMetadataOptions: ParsableArguments {\n @Flag(help: "Show allocations in mangled form")\n var mangled: Bool = false\n\n @Flag(help: "Output JSON")\n var json: Bool = false\n\n #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n @Flag(help: "Print out a summary from all process output")\n #endif\n var summary: Bool = false\n\n @Option(help: "Output to a file")\n var outputFile: String? = nil\n}\n\ninternal func inspect(options: UniversalOptions,\n _ body: (any RemoteProcess) throws -> Void) throws {\n if let nameOrPid = options.nameOrPid {\n guard let processId = process(matching: nameOrPid) else {\n print("No process found matching \(nameOrPid)", to: &Std.err)\n return\n }\n guard let process = getRemoteProcess(processId: processId,\n options: options) else {\n print("Failed to create inspector for process id \(processId)", to: &Std.err)\n return\n }\n try body(process)\n }\n else {\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n if let processIdentifiers = getAllProcesses(options: options) {\n let totalCount = processIdentifiers.count\n var successfulCount = 0\n for (index, processIdentifier) in processIdentifiers.enumerated() {\n let progress = "[\(successfulCount)/\(index + 1)/\(totalCount)]"\n if let remoteProcess = getRemoteProcess(processId: processIdentifier, options: options) {\n do {\n print(progress, "\(remoteProcess.processName)(\(remoteProcess.processIdentifier))",\n terminator: "", to: &Std.err)\n try body(remoteProcess)\n successfulCount += 1\n } catch {\n print(" - \(error)", terminator: "", to: &Std.err)\n }\n remoteProcess.release() // break retain cycle\n } else {\n print(progress, " - failed to create inspector for process id \(processIdentifier)",\n terminator: "\n", to: &Std.err)\n }\n print("\u{01B}[0K", terminator: "\r", to: &Std.err)\n }\n print("", to: &Std.err)\n } else {\n print("Failed to get list of processes", to: &Std.err)\n }\n#endif\n }\n}\n\n@main\ninternal struct SwiftInspect: ParsableCommand {\n // DumpArrays and DumpConcurrency cannot be reliably be ported outside of\n // Darwin due to the need to iterate the heap.\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n static let subcommands: [ParsableCommand.Type] = [\n DumpConformanceCache.self,\n DumpRawMetadata.self,\n DumpGenericMetadata.self,\n DumpCacheNodes.self,\n DumpArrays.self,\n DumpConcurrency.self,\n ]\n#elseif os(Windows) || os(Android)\n static let subcommands: [ParsableCommand.Type] = [\n DumpConformanceCache.self,\n DumpRawMetadata.self,\n DumpGenericMetadata.self,\n DumpCacheNodes.self,\n DumpArrays.self,\n ]\n#else\n static let subcommands: [ParsableCommand.Type] = [\n DumpConformanceCache.self,\n DumpRawMetadata.self,\n DumpGenericMetadata.self,\n DumpCacheNodes.self,\n ]\n#endif\n\n static let configuration = CommandConfiguration(\n abstract: "Swift runtime debug tool",\n subcommands: subcommands)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_main.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_main.swift
Swift
5,203
0.95
0.150943
0.202797
react-lib
79
2024-11-03T04:02:15.925892
GPL-3.0
false
6d963c6c905add07241eb167887884fa
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if !os(Linux)\n\nimport ArgumentParser\nimport SwiftRemoteMirror\n\ninternal struct DumpArrays: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print information about array objects in the target.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n func run() throws {\n try inspect(options: options) { process in\n print("Address", "Size", "Count", "Is Class", separator: "\t")\n process.iterateHeap { (allocation, size) in\n let metadata: UInt =\n swift_reflection_metadataForObject(process.context, UInt(allocation))\n if metadata == 0 { return }\n\n guard process.context.isContiguousArray(swift_reflection_ptr_t(metadata)) else {\n return\n }\n\n let ReadBytes: RemoteProcess.ReadBytesFunction =\n type(of: process).ReadBytes\n let this = process.toOpaqueRef()\n\n let isClass = process.context.isArrayOfClass(swift_reflection_ptr_t(metadata))\n let count = process.context.arrayCount(swift_reflection_ptr_t(allocation),\n { ReadBytes(this, $0, UInt64($1), nil) })\n print("\(hex: swift_reflection_ptr_t(allocation))\t\(size)\t\(count.map(String.init) ?? "<unknown>")\t\(isClass)")\n }\n }\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpArray.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpArray.swift
Swift
1,804
0.95
0.1
0.317073
node-utils
94
2023-12-26T10:04:00.458659
GPL-3.0
false
e1fa9cda5ef3fbd4e27284a2c057fe28
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport SwiftRemoteMirror\n\ninternal struct DumpCacheNodes: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print the target's metadata cache nodes.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n func run() throws {\n try inspect(options: options) { process in\n print("Address", "Tag", "Tag Name", "Size", "Left", "Right", separator: "\t")\n try process.context.allocations.forEach {\n var node: swift_metadata_cache_node_t = swift_metadata_cache_node_t()\n if swift_reflection_metadataAllocationCacheNode(process.context, $0, &node) == 0 {\n return\n }\n\n let name: String = process.context.name(allocation: $0.tag) ?? "<unknown>"\n print("\(hex: $0.ptr)\t\($0.tag)\t\(name)\t\($0.size)\t\(hex: node.Left)\t\(hex: node.Right)")\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpCacheNodes.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpCacheNodes.swift
Swift
1,383
0.95
0.135135
0.34375
awesome-app
388
2025-07-04T18:03:10.470695
MIT
false
7662b67831f5f75d37bdf8f0ea2616f9
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n\nimport ArgumentParser\nimport SwiftRemoteMirror\n#if canImport(string_h)\nimport string_h\n#endif\n\nstruct DumpConcurrency: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print information about the target's concurrency runtime.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n func run() throws {\n try inspect(options: options) { process in\n let dumper = ConcurrencyDumper(context: process.context,\n process: process as! DarwinRemoteProcess)\n dumper.dumpTasks()\n dumper.dumpActors()\n dumper.dumpThreads()\n }\n }\n}\n\nfileprivate class ConcurrencyDumper {\n let context: SwiftReflectionContextRef\n let process: DarwinRemoteProcess\n let jobMetadata: swift_reflection_ptr_t?\n let taskMetadata: swift_reflection_ptr_t?\n\n struct TaskInfo {\n var address: swift_reflection_ptr_t\n var kind: UInt32\n var enqueuePriority: UInt32\n var isChildTask: Bool\n var isFuture: Bool\n var isGroupChildTask: Bool\n var isAsyncLetTask: Bool\n var maxPriority: UInt32\n var isCancelled: Bool\n var isStatusRecordLocked: Bool\n var isEscalated: Bool\n var hasIsRunning: Bool\n var isRunning: Bool\n var isEnqueued: Bool\n var threadPort: UInt32?\n var id: UInt64\n var runJob: swift_reflection_ptr_t\n var allocatorSlabPtr: swift_reflection_ptr_t\n var allocatorTotalSize: Int\n var allocatorTotalChunks: Int\n var childTasks: [swift_reflection_ptr_t]\n var asyncBacktrace: [swift_reflection_ptr_t]\n var parent: swift_reflection_ptr_t?\n }\n\n struct HeapInfo {\n var tasks: [swift_reflection_ptr_t] = []\n var jobs: [swift_reflection_ptr_t] = []\n var actors: [swift_reflection_ptr_t] = []\n }\n\n lazy var heapInfo: HeapInfo = gatherHeapInfo()\n\n lazy var threadCurrentTasks = process.currentTasks.filter{ $0.currentTask != 0 }\n\n lazy var tasks: [swift_reflection_ptr_t: TaskInfo] = gatherTasks()\n\n var actors: [swift_reflection_ptr_t] {\n heapInfo.actors\n }\n\n var metadataIsActorCache: [swift_reflection_ptr_t: Bool] = [:]\n var metadataNameCache: [swift_reflection_ptr_t: String?] = [:]\n\n init(context: SwiftReflectionContextRef, process: DarwinRemoteProcess) {\n self.context = context\n self.process = process\n\n func getMetadata(symbolName: String) -> swift_reflection_ptr_t? {\n let addr = process.getAddr(symbolName: symbolName)\n if let ptr = process.read(address: addr, size: MemoryLayout<UInt>.size) {\n return swift_reflection_ptr_t(ptr.load(as: UInt.self))\n }\n return nil\n }\n jobMetadata = getMetadata(symbolName: "_swift_concurrency_debug_jobMetadata")\n taskMetadata = getMetadata(symbolName: "_swift_concurrency_debug_asyncTaskMetadata")\n }\n\n func gatherHeapInfo() -> HeapInfo {\n var result = HeapInfo()\n\n process.iterateHeap { (pointer, size) in\n let metadata = swift_reflection_ptr_t(swift_reflection_metadataForObject(context, UInt(pointer)))\n if metadata == jobMetadata {\n result.jobs.append(swift_reflection_ptr_t(pointer))\n } else if metadata == taskMetadata {\n result.tasks.append(swift_reflection_ptr_t(pointer))\n } else if isActorMetadata(metadata) {\n result.actors.append(swift_reflection_ptr_t(pointer))\n }\n }\n\n return result\n }\n\n func gatherTasks() -> [swift_reflection_ptr_t: TaskInfo] {\n var map: [swift_reflection_ptr_t: TaskInfo] = [:]\n var tasksToScan: Set<swift_reflection_ptr_t> = []\n tasksToScan.formUnion(heapInfo.tasks)\n tasksToScan.formUnion(threadCurrentTasks.map{ swift_reflection_ptr_t($0.currentTask) }.filter{ $0 != 0 })\n\n while !tasksToScan.isEmpty {\n let taskToScan = tasksToScan.removeFirst()\n if let info = info(forTask: taskToScan) {\n map[taskToScan] = info\n for child in info.childTasks {\n let childMetadata = swift_reflection_metadataForObject(context, UInt(child))\n if let taskMetadata = taskMetadata, childMetadata != taskMetadata {\n print("Inconsistent data detected! Child task \(hex: child) has unknown metadata \(hex: taskMetadata)")\n }\n if map[child] == nil {\n tasksToScan.insert(child)\n }\n }\n }\n }\n\n for (task, info) in map {\n for child in info.childTasks {\n map[child]?.parent = task\n }\n }\n\n return map\n }\n\n func isActorMetadata(_ metadata: swift_reflection_ptr_t) -> Bool {\n if let cached = metadataIsActorCache[metadata] {\n return cached\n }\n let result = swift_reflection_metadataIsActor(context, metadata) != 0\n metadataIsActorCache[metadata] = result\n return result\n }\n\n func name(metadata: swift_reflection_ptr_t) -> String? {\n if let cached = metadataNameCache[metadata] {\n return cached\n }\n\n let name = context.name(type: metadata)\n metadataNameCache[metadata] = name\n return name\n }\n\n func info(forTask task: swift_reflection_ptr_t) -> TaskInfo? {\n let reflectionInfo = swift_reflection_asyncTaskInfo(context, task)\n if let error = reflectionInfo.Error {\n print("Error getting info for async task \(hex: task): \(String(cString: error))")\n return nil\n }\n\n // These arrays are temporary pointers which we must copy out before we call\n // into Remote Mirror again.\n let children = Array(UnsafeBufferPointer(\n start: reflectionInfo.ChildTasks,\n count: Int(reflectionInfo.ChildTaskCount)))\n let asyncBacktraceFrames = Array(UnsafeBufferPointer(\n start: reflectionInfo.AsyncBacktraceFrames,\n count: Int(reflectionInfo.AsyncBacktraceFramesCount)))\n\n var allocatorSlab = reflectionInfo.AllocatorSlabPtr\n var allocatorTotalSize = 0\n var allocatorTotalChunks = 0\n while allocatorSlab != 0 {\n let allocations = swift_reflection_asyncTaskSlabAllocations(context,\n allocatorSlab)\n guard allocations.Error == nil else { break }\n allocatorTotalSize += Int(allocations.SlabSize)\n allocatorTotalChunks += Int(allocations.ChunkCount)\n\n allocatorSlab = allocations.NextSlab\n }\n\n return TaskInfo(\n address: task,\n kind: reflectionInfo.Kind,\n enqueuePriority: reflectionInfo.EnqueuePriority,\n isChildTask: reflectionInfo.IsChildTask,\n isFuture: reflectionInfo.IsFuture,\n isGroupChildTask: reflectionInfo.IsGroupChildTask,\n isAsyncLetTask: reflectionInfo.IsAsyncLetTask,\n maxPriority: reflectionInfo.MaxPriority,\n isCancelled: reflectionInfo.IsCancelled,\n isStatusRecordLocked: reflectionInfo.IsStatusRecordLocked,\n isEscalated: reflectionInfo.IsEscalated,\n hasIsRunning: reflectionInfo.HasIsRunning,\n isRunning: reflectionInfo.IsRunning,\n isEnqueued: reflectionInfo.IsEnqueued,\n threadPort: reflectionInfo.HasThreadPort\n ? reflectionInfo.ThreadPort\n : nil,\n id: reflectionInfo.Id,\n runJob: reflectionInfo.RunJob,\n allocatorSlabPtr: reflectionInfo.AllocatorSlabPtr,\n allocatorTotalSize: allocatorTotalSize,\n allocatorTotalChunks: allocatorTotalChunks,\n childTasks: children,\n asyncBacktrace: asyncBacktraceFrames\n )\n }\n\n func taskHierarchy() -> [(level: Int, lastChild: Bool, task: TaskInfo)] {\n var hierarchy: [(level: Int, lastChild: Bool, task: TaskInfo)] = []\n\n let topLevelTasks = tasks.values.filter{ $0.parent == nil }\n for top in topLevelTasks.sorted(by: { $0.id < $1.id }) {\n var stack: [(index: Int, task: TaskInfo)] = [(0, top)]\n hierarchy.append((0, true, top))\n\n while let (index, task) = stack.popLast() {\n if index < task.childTasks.count {\n stack.append((index + 1, task))\n let childPtr = task.childTasks[index]\n let childTask = tasks[childPtr]!\n hierarchy.append((stack.count, index == task.childTasks.count - 1, childTask))\n stack.append((0, childTask))\n }\n }\n }\n return hierarchy\n }\n\n func remove(from: String, upTo: String) -> String {\n from.withCString {\n if let found = strstr($0, upTo) {\n return String(cString: found + strlen(upTo))\n }\n return from\n }\n }\n\n func symbolicateBacktracePointer(ptr: swift_reflection_ptr_t) -> String {\n guard let name = process.symbolicate(swift_addr_t(ptr)).symbol else {\n return "<\(hex: ptr)>"\n }\n\n return remove(from: name, upTo: " resume partial function for ")\n }\n\n func decodeTaskFlags(_ info: TaskInfo) -> String {\n var flags: [String] = []\n if info.isChildTask { flags.append("childTask") }\n if info.isFuture { flags.append("future") }\n if info.isGroupChildTask { flags.append("groupChildTask") }\n if info.isAsyncLetTask { flags.append("asyncLetTask") }\n if info.isCancelled { flags.append("cancelled") }\n if info.isStatusRecordLocked { flags.append("statusRecordLocked") }\n if info.isEscalated { flags.append("escalated") }\n if info.hasIsRunning && info.isRunning { flags.append("running") }\n if info.isEnqueued { flags.append("enqueued") }\n\n let flagsStr = flags.isEmpty ? "0" : flags.joined(separator: "|")\n return flagsStr\n }\n\n func decodeActorFlags(_ info: swift_actor_info_t) -> (\n state: String,\n flags: String,\n maxPriority: UInt8\n ) {\n let states: [UInt8: String] = [\n 0: "idle",\n 1: "scheduled",\n 2: "running",\n 3: "zombie-latching",\n 4: "zombie-ready-for-deallocation"\n ]\n\n var flags: [String] = []\n if info.IsPriorityEscalated { flags.append("priorityEscalated") }\n if info.IsDistributedRemote { flags.append("distributedRemote") }\n let flagsStr = flags.isEmpty ? "0" : flags.joined(separator: "|")\n\n return (\n state: states[info.State] ?? "unknown(\(info.State))",\n flags: flagsStr,\n maxPriority: info.MaxPriority\n )\n }\n\n func dumpTasks() {\n print("TASKS")\n\n let missingIsRunning = tasks.contains(where: { !$1.hasIsRunning })\n if missingIsRunning {\n print("warning: unable to decode is-running state of target tasks, running state and async backtraces will not be printed")\n }\n\n let taskToThread: [swift_addr_t: UInt64] =\n Dictionary(threadCurrentTasks.map{ ($1, $0) }, uniquingKeysWith: { $1 })\n\n var lastChildFlags: [Bool] = []\n\n let hierarchy = taskHierarchy()\n for (i, (level, lastChild, task)) in hierarchy.enumerated() {\n lastChildFlags.removeSubrange(level...)\n lastChildFlags.append(lastChild)\n\n let prevEntry = i > 0 ? hierarchy[i - 1] : nil\n\n let levelDidIncrease = level > (prevEntry?.level ?? -1)\n\n var prefix = ""\n for lastChildFlag in lastChildFlags {\n prefix += lastChildFlag ? " " : " | "\n }\n prefix += " "\n let firstPrefix = String(prefix.dropLast(5) + (\n level == 0 ? " " :\n lastChild ? "`--" :\n "+--"))\n if levelDidIncrease {\n print(prefix)\n }\n\n var firstLine = true\n func output(_ str: String) {\n print((firstLine ? firstPrefix : prefix) + str)\n firstLine = false\n }\n\n let runJobSymbol = process.symbolicate(swift_addr_t(task.runJob))\n let runJobLibrary = runJobSymbol.module ?? "<unknown>"\n\n let symbolicatedBacktrace = task.asyncBacktrace.map(symbolicateBacktracePointer)\n\n let flags = decodeTaskFlags(task)\n\n output("Task \(task.id) - flags=\(flags) enqueuePriority=\(hex: task.enqueuePriority) maxPriority=\(hex: task.maxPriority) address=\(hex: task.address)")\n if let thread = taskToThread[swift_addr_t(task.address)] {\n output("current task on thread \(hex: thread)")\n }\n if let parent = task.parent {\n output("parent: \(hex: parent)")\n }\n if let threadPort = task.threadPort, threadPort != 0 {\n if let threadID = process.getThreadID(remotePort: threadPort) {\n output("waiting on thread: port=\(hex: threadPort) id=\(hex: threadID)")\n }\n }\n\n if let first = symbolicatedBacktrace.first {\n output("async backtrace: \(first)")\n for entry in symbolicatedBacktrace.dropFirst() {\n output(" \(entry)")\n }\n }\n\n output("resume function: \(symbolicateBacktracePointer(ptr: task.runJob)) in \(runJobLibrary)")\n output("task allocator: \(task.allocatorTotalSize) bytes in \(task.allocatorTotalChunks) chunks")\n\n if task.childTasks.count > 0 {\n let s = task.childTasks.count > 1 ? "s" : ""\n output("* \(task.childTasks.count) child task\(s)")\n }\n\n if (task.childTasks.isEmpty) && i < hierarchy.count - 1 {\n print(prefix)\n }\n }\n\n print("")\n }\n\n func dumpActors() {\n print("ACTORS")\n\n for actor in actors {\n let metadata = swift_reflection_metadataForObject(context, UInt(actor))\n let metadataName = name(metadata: swift_reflection_ptr_t(metadata)) ?? "<unknown class name>"\n let info = swift_reflection_actorInfo(context, actor)\n if let error = info.Error {\n print(String(utf8String: error) ?? "<unknown error>")\n continue\n }\n\n let flags = decodeActorFlags(info)\n\n print(" \(hex: actor) \(metadataName) state=\(flags.state) flags=\(flags.flags) maxPriority=\(hex: flags.maxPriority)")\n if info.HasThreadPort && info.ThreadPort != 0 {\n if let threadID = process.getThreadID(remotePort: info.ThreadPort) {\n print(" waiting on thread: port=\(hex: info.ThreadPort) id=\(hex: threadID)")\n } else {\n print(" waiting on thread: port=\(hex: info.ThreadPort) (unknown thread ID)")\n }\n }\n\n func jobStr(_ job: swift_reflection_ptr_t) -> String {\n if let task = tasks[job] {\n return "Task \(task.id) \(symbolicateBacktracePointer(ptr: task.runJob))"\n }\n return "<internal job \(hex: job)>"\n }\n\n var job = info.FirstJob\n if job == 0 {\n print(" no jobs queued")\n } else {\n print(" job queue: \(jobStr(job))")\n let limit = 1000\n for i in 1 ... limit {\n job = swift_reflection_nextJob(context, job);\n if job != 0 {\n print(" \(jobStr(job))")\n } else {\n break\n }\n\n if i == limit {\n print(" ...truncated...")\n }\n }\n }\n print("")\n }\n }\n\n func dumpThreads() {\n print("THREADS")\n if threadCurrentTasks.isEmpty {\n print(" no threads with active tasks")\n return\n }\n\n for (thread, task) in threadCurrentTasks {\n let taskStr: String\n if let info = tasks[swift_reflection_ptr_t(task)] {\n taskStr = "\(info.id)"\n } else {\n taskStr = "<unknown task \(hex: task)>"\n }\n print(" Thread \(hex: thread) - current task: \(taskStr)")\n }\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpConcurrency.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpConcurrency.swift
Swift
15,421
0.95
0.142241
0.043038
react-lib
875
2024-11-15T06:21:18.986669
Apache-2.0
false
48e5647bfa99755dc7eaed76682566b0
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\ninternal struct DumpConformanceCache: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print the contents of the target's protocol conformance cache.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n func run() throws {\n try inspect(options: options) { process in\n try process.context.iterateConformanceCache { type, proto in\n let type: String = process.context.name(type: type) ?? "<unknown>"\n let conformance: String = process.context.name(protocol: proto) ?? "<unknown>"\n print("Conformance: \(type): \(conformance)")\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpConformanceCache.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpConformanceCache.swift
Swift
1,153
0.95
0.129032
0.407407
vue-tools
127
2025-03-15T19:08:07.484955
Apache-2.0
false
6fdcda411d9e997c94a451fa7fdf18a5
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport SwiftRemoteMirror\nimport Foundation\n\nprivate struct Metadata: Encodable {\n let ptr: swift_reflection_ptr_t\n var allocation: swift_metadata_allocation_t?\n let name: String\n let isArrayOfClass: Bool\n var garbage: Bool = false\n var offset: Int? { allocation.map { Int(self.ptr - $0.ptr) } }\n var backtrace: String?\n\n enum CodingKeys: String, CodingKey {\n case ptr = "address"\n case allocation\n case name\n case isArrayOfClass\n case garbage\n case offset\n case backtrace\n }\n\n func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(ptr, forKey: .ptr)\n try container.encode(name, forKey: .name)\n if isArrayOfClass {\n try container.encode(isArrayOfClass, forKey: .isArrayOfClass)\n }\n if garbage {\n try container.encode(garbage, forKey: .garbage)\n }\n if let offset {\n try container.encode(offset, forKey: .offset)\n }\n if let backtrace {\n try container.encode(backtrace, forKey: .backtrace)\n }\n if let allocation {\n try container.encode(allocation, forKey: .allocation)\n }\n }\n}\n\nprivate struct ProcessMetadata: Encodable {\n var name: String\n var pid: ProcessIdentifier\n var metadata: [Metadata]\n}\n\nprivate struct MetadataSummary: Encodable {\n var totalSize: Int\n var processes: Set<String>\n}\n\ninternal struct Output: TextOutputStream {\n let fileHandle: FileHandle\n init(_ outputFile: String? = nil) throws {\n if let outputFile {\n if FileManager().createFile(atPath: outputFile, contents: nil) {\n self.fileHandle = FileHandle(forWritingAtPath: outputFile)!\n } else {\n print("Unable to create file \(outputFile)", to: &Std.err)\n exit(1)\n }\n } else {\n self.fileHandle = FileHandle.standardOutput\n }\n }\n\n mutating func write(_ string: String) {\n if let encodedString = string.data(using: .utf8) {\n fileHandle.write(encodedString)\n }\n }\n}\n\ninternal struct DumpGenericMetadata: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print the target's generic metadata allocations.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n @OptionGroup()\n var backtraceOptions: BacktraceOptions\n\n @OptionGroup()\n var genericMetadataOptions: GenericMetadataOptions\n\n func run() throws {\n disableStdErrBuffer()\n var metadataSummary = [String: MetadataSummary]()\n var allProcesses = [ProcessMetadata]()\n try inspect(options: options) { process in\n let allocations: [swift_metadata_allocation_t] =\n try process.context.allocations.sorted()\n\n let stacks: [swift_reflection_ptr_t:[swift_reflection_ptr_t]] =\n backtraceOptions.style == nil\n ? [swift_reflection_ptr_t:[swift_reflection_ptr_t]]()\n : try process.context.allocationStacks\n\n let generics: [Metadata] = allocations.compactMap { allocation -> Metadata? in\n let pointer = swift_reflection_allocationMetadataPointer(process.context, allocation)\n if pointer == 0 { return nil }\n let allocation = allocations.last(where: { pointer >= $0.ptr && pointer < $0.ptr + swift_reflection_ptr_t($0.size) })\n let garbage = (allocation == nil && swift_reflection_ownsAddressStrict(process.context, UInt(pointer)) == 0)\n var currentBacktrace: String?\n if let style = backtraceOptions.style, let allocation, let stack = stacks[allocation.ptr] {\n currentBacktrace = backtrace(stack, style: style, process.symbolicate)\n }\n\n return Metadata(ptr: pointer,\n allocation: allocation,\n name: process.context.name(type: pointer, mangled: genericMetadataOptions.mangled) ?? "<unknown>",\n isArrayOfClass: process.context.isArrayOfClass(pointer),\n garbage: garbage,\n backtrace: currentBacktrace)\n } // generics\n\n // Update summary\n generics.forEach { metadata in\n if let allocation = metadata.allocation {\n let name = metadata.name\n if metadataSummary.keys.contains(name) {\n metadataSummary[name]!.totalSize += allocation.size\n metadataSummary[name]!.processes.insert(process.processName)\n } else {\n metadataSummary[name] = MetadataSummary(totalSize: allocation.size,\n processes: Set([process.processName]))\n }\n }\n }\n\n if genericMetadataOptions.json {\n let processMetadata = ProcessMetadata(name: process.processName,\n pid: process.processIdentifier as! ProcessIdentifier,\n metadata: generics)\n allProcesses.append(processMetadata)\n } else if !genericMetadataOptions.summary {\n try dumpText(process: process, generics: generics)\n }\n } // inspect\n\n if genericMetadataOptions.json {\n if genericMetadataOptions.summary {\n try dumpJson(of: metadataSummary)\n } else {\n try dumpJson(of: allProcesses)\n }\n } else if genericMetadataOptions.summary {\n try dumpTextSummary(of: metadataSummary)\n }\n }\n\n private func dumpText(process: any RemoteProcess, generics: [Metadata]) throws {\n var erroneousMetadata: [(ptr: swift_reflection_ptr_t, name: String)] = []\n var output = try Output(genericMetadataOptions.outputFile)\n print("\(process.processName)(\(process.processIdentifier)):\n", to: &output)\n print("Address", "Allocation", "Size", "Offset", "isArrayOfClass", "Name", separator: "\t", to: &output)\n generics.forEach {\n print("\(hex: $0.ptr)", terminator: "\t", to: &output)\n if let allocation = $0.allocation, let offset = $0.offset {\n print("\(hex: allocation.ptr)\t\(allocation.size)\t\(offset)", terminator: "\t", to: &output)\n } else {\n if $0.garbage {\n erroneousMetadata.append((ptr: $0.ptr, name: $0.name))\n }\n print("???\t??\t???", terminator: "\t", to: &output)\n }\n print($0.isArrayOfClass, terminator: "\t", to: &output)\n print($0.name, to: &output)\n if let _ = backtraceOptions.style, let _ = $0.allocation {\n print($0.backtrace ?? " No stacktrace available", to: &output)\n }\n }\n\n if erroneousMetadata.count > 0 {\n print("Warning: The following metadata was not found in any DATA or AUTH segments, may be garbage.", to: &output)\n erroneousMetadata.forEach {\n print("\(hex: $0.ptr)\t\($0.name)", to: &output)\n }\n }\n print("", to: &output)\n }\n\n private func dumpJson(of: (any Encodable)) throws {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let data = try encoder.encode(of)\n let jsonOutput = String(data: data, encoding: .utf8)!\n if let outputFile = genericMetadataOptions.outputFile {\n try jsonOutput.write(toFile: outputFile, atomically: true, encoding: .utf8)\n } else {\n print(jsonOutput)\n }\n }\n\n private func dumpTextSummary(of: [String: MetadataSummary]) throws {\n var output = try Output(genericMetadataOptions.outputFile)\n print("Size", "Owners", "Name", separator: "\t", to: &output)\n var totalSize = 0\n var unknownSize = 0\n of.sorted { first, second in\n first.value.processes.count > second.value.processes.count\n }\n .forEach { summary in\n totalSize += summary.value.totalSize\n if summary.key == "<unknown>" {\n unknownSize += summary.value.totalSize\n }\n print(summary.value.totalSize, summary.value.processes.count, summary.key,\n separator: "\t", to: &output)\n }\n print("\nTotal size:\t\(totalSize / 1024) KiB", to: &output)\n print("Unknown size:\t\(unknownSize / 1024) KiB", to: &output)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpGenericMetadata.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpGenericMetadata.swift
Swift
8,390
0.95
0.185345
0.057416
vue-tools
477
2025-06-20T12:47:11.862014
MIT
false
8a1c1dd705faa767237337175b5a7508
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport SwiftRemoteMirror\n\ninternal struct DumpRawMetadata: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "Print the target's metadata allocations.")\n\n @OptionGroup()\n var options: UniversalOptions\n\n @OptionGroup()\n var backtraceOptions: BacktraceOptions\n\n func run() throws {\n try inspect(options: options) { process in\n let stacks: [swift_reflection_ptr_t:[swift_reflection_ptr_t]]? =\n backtraceOptions.style == nil\n ? nil\n : try process.context.allocationStacks\n\n try process.context.allocations.forEach { allocation in\n let name: String = process.context.name(allocation: allocation.tag) ?? "<unknown>"\n print("Metadata allocation at: \(hex: allocation.ptr) size: \(allocation.size) tag: \(allocation.tag) (\(name))")\n if let style = backtraceOptions.style {\n if let stack = stacks?[allocation.ptr] {\n print(backtrace(stack, style: style, process.symbolicate))\n } else {\n print(" No stack trace available")\n }\n }\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpRawMetadata.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Operations_DumpRawMetadata.swift
Swift
1,647
0.95
0.152174
0.275
react-lib
479
2023-08-08T23:58:29.982677
Apache-2.0
false
4ea0562a111c62e26601632335b6ec07
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\nimport Darwin\n\ninternal typealias ProcessIdentifier = DarwinRemoteProcess.ProcessIdentifier\n\ninternal func process(matching: String) -> ProcessIdentifier? {\n if refersToSelf(matching) {\n return getpid()\n } else {\n return pidFromHint(matching)\n }\n}\n\nprivate func refersToSelf(_ str: String) -> Bool {\n guard let myPath = CommandLine.arguments.first else {\n return false\n }\n\n // If string matches the full path, success.\n if myPath == str {\n return true\n }\n\n // If there's a slash in the string, compare with the component following the\n // slash.\n if let slashIndex = myPath.lastIndex(of: "/") {\n let myName = myPath[slashIndex...].dropFirst()\n return myName == str\n }\n\n // No match.\n return false\n}\n\ninternal func getRemoteProcess(processId: ProcessIdentifier,\n options: UniversalOptions) -> (any RemoteProcess)? {\n return DarwinRemoteProcess(processId: processId,\n forkCorpse: options.forkCorpse)\n}\n\ninternal func getProcessName(processId: ProcessIdentifier) -> String? {\n var info = proc_bsdinfo()\n let bsdinfoSize = Int32(MemoryLayout<proc_bsdinfo>.stride)\n let size = proc_pidinfo(processId, PROC_PIDTBSDINFO, 0, &info, bsdinfoSize)\n if (size != bsdinfoSize) {\n return nil\n }\n let processName = withUnsafeBytes(of: info.pbi_name) { buffer in\n let nonnullBuffer = buffer.prefix { $0 != 0 }\n return String(decoding: nonnullBuffer, as: UTF8.self)\n }\n return processName\n}\n\ninternal func getAllProcesses(options: UniversalOptions) -> [ProcessIdentifier]? {\n var ProcessIdentifiers = [ProcessIdentifier]()\n let kinfo_stride = MemoryLayout<kinfo_proc>.stride\n var bufferSize: Int = 0\n var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL]\n\n guard sysctl(&name, u_int(name.count), nil, &bufferSize, nil, 0) == 0 else {\n return nil\n }\n let count = bufferSize / kinfo_stride\n var buffer = Array(repeating: kinfo_proc(), count: count)\n guard sysctl(&name, u_int(name.count), &buffer, &bufferSize, nil, 0) == 0 else {\n return nil\n }\n let newCount = bufferSize / kinfo_stride\n if count > newCount {\n buffer.dropLast(count - newCount)\n }\n let sorted = buffer.sorted { first, second in\n first.kp_proc.p_pid > second.kp_proc.p_pid\n }\n let myPid = getpid()\n for kinfo in sorted {\n let pid = kinfo.kp_proc.p_pid\n if pid <= 1 {\n break\n }\n if pid == myPid { // skip self\n continue\n }\n ProcessIdentifiers.append(pid)\n }\n return ProcessIdentifiers\n}\n\n#elseif os(Windows)\nimport WinSDK\n\ninternal typealias ProcessIdentifier = WindowsRemoteProcess.ProcessIdentifier\n\ninternal func process(matching: String) -> ProcessIdentifier? {\n if let dwProcess = DWORD(matching) {\n return dwProcess\n }\n\n let hSnapshot = CreateToolhelp32Snapshot(DWORD(TH32CS_SNAPPROCESS), 0)\n if hSnapshot == INVALID_HANDLE_VALUE {\n return nil\n }\n defer { CloseHandle(hSnapshot) }\n\n var entry: PROCESSENTRY32W = PROCESSENTRY32W()\n entry.dwSize = DWORD(MemoryLayout<PROCESSENTRY32W>.size)\n\n if !Process32FirstW(hSnapshot, &entry) {\n return nil\n }\n\n var matches: [(ProcessIdentifier, String)] = []\n repeat {\n let executable: String = withUnsafePointer(to: entry.szExeFile) {\n $0.withMemoryRebound(to: WCHAR.self,\n capacity: MemoryLayout.size(ofValue: $0) / MemoryLayout<WCHAR>.size) {\n String(decodingCString: $0, as: UTF16.self)\n }\n }\n if executable.hasPrefix(matching) {\n matches.append((entry.th32ProcessID, executable))\n }\n } while Process32NextW(hSnapshot, &entry)\n\n return matches.first?.0\n}\n\ninternal func getRemoteProcess(processId: ProcessIdentifier,\n options: UniversalOptions) -> (any RemoteProcess)? {\n return WindowsRemoteProcess(processId: processId)\n}\n\n#elseif os(Linux)\nimport Foundation\n\ninternal typealias ProcessIdentifier = LinuxRemoteProcess.ProcessIdentifier\n\ninternal func process(matching: String) -> ProcessIdentifier? {\n guard let processId = LinuxRemoteProcess.ProcessIdentifier(matching) else {\n return nil\n }\n\n let procfs_path = "/proc/\(processId)"\n var isDirectory: Bool = false\n guard FileManager.default.fileExists(atPath: procfs_path, isDirectory: &isDirectory)\n && isDirectory else {\n return nil\n }\n\n return processId\n}\n\ninternal func getRemoteProcess(processId: ProcessIdentifier,\n options: UniversalOptions) -> (any RemoteProcess)? {\n return LinuxRemoteProcess(processId: processId)\n}\n\n#elseif os(Android)\nimport Foundation\n\ninternal typealias ProcessIdentifier = AndroidRemoteProcess.ProcessIdentifier\n\ninternal func process(matching: String) -> ProcessIdentifier? {\n guard let processId = AndroidRemoteProcess.ProcessIdentifier(matching) else {\n return nil\n }\n\n let procfsPath = "/proc/\(processId)"\n var isDirectory: Bool = false\n guard FileManager.default.fileExists(atPath: procfsPath, isDirectory: &isDirectory)\n && isDirectory else {\n return nil\n }\n\n return processId\n}\n\ninternal func getRemoteProcess(processId: ProcessIdentifier,\n options: UniversalOptions) -> (any RemoteProcess)? {\n return AndroidRemoteProcess(processId: processId)\n}\n\n#else\n#error("Unsupported platform")\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Process.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Process.swift
Swift
5,835
0.95
0.080808
0.133333
node-utils
13
2023-12-08T10:19:39.150620
BSD-3-Clause
false
5527da255ab6ac6f22a64579e91f3a98
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftRemoteMirror\n\nextension swift_metadata_allocation_t: @retroactive Encodable {\n internal var tag: swift_metadata_allocation_tag_t { return self.Tag }\n internal var ptr: swift_reflection_ptr_t { return self.Ptr }\n internal var size: Int { return Int(self.Size) }\n enum CodingKeys: String, CodingKey {\n case tag\n case ptr = "address"\n case size\n }\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(tag, forKey: .tag)\n try container.encode(ptr, forKey: .ptr)\n try container.encode(size, forKey: .size)\n }\n}\n\nextension swift_metadata_allocation_t: @retroactive Comparable {\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.ptr == rhs.ptr\n }\n\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.ptr < rhs.ptr\n }\n}\n\nextension SwiftReflectionContextRef {\n struct Error: Swift.Error, CustomStringConvertible {\n var description: String\n\n init(cString: UnsafePointer<CChar>) {\n description = String(cString: cString)\n }\n }\n}\n\nextension SwiftReflectionContextRef {\n typealias ConformanceIterationCallback = (swift_reflection_ptr_t, swift_reflection_ptr_t) -> Void\n typealias MetadataAllocationIterationCallback = (swift_metadata_allocation_t) -> Void\n typealias MetadataAllocationBacktraceIterationCallback = (swift_reflection_ptr_t, Int, UnsafePointer<swift_reflection_ptr_t>) -> Void\n\n internal var allocations: [swift_metadata_allocation_t] {\n get throws {\n var allocations: [swift_metadata_allocation_t] = []\n try iterateMetadataAllocations {\n allocations.append($0)\n }\n return allocations\n }\n }\n\n internal var allocationStacks: [swift_reflection_ptr_t:[swift_reflection_ptr_t]] {\n get throws {\n var stacks: [swift_reflection_ptr_t:[swift_reflection_ptr_t]] = [:]\n try iterateMetadataAllocationBacktraces { allocation, count, stack in\n stacks[allocation] =\n Array(UnsafeBufferPointer(start: stack, count: count))\n }\n return stacks\n }\n }\n\n internal func name(type: swift_reflection_ptr_t, mangled: Bool = false) -> String? {\n let typeref = swift_reflection_typeRefForMetadata(self, UInt(type))\n if typeref == 0 { return nil }\n\n guard let name = swift_reflection_copyNameForTypeRef(self, typeref, mangled) else {\n return nil\n }\n defer { free(name) }\n\n return String(cString: name)\n }\n\n internal func name(protocol: swift_reflection_ptr_t) -> String? {\n guard let name = swift_reflection_copyDemangledNameForProtocolDescriptor(self, `protocol`) else {\n return nil\n }\n defer { free(name) }\n\n return String(cString: name)\n }\n\n internal func name(allocation tag: swift_metadata_allocation_tag_t) -> String? {\n return swift_reflection_metadataAllocationTagName(self, tag).map(String.init(cString:))\n }\n\n internal func isContiguousArray(_ array: swift_reflection_ptr_t) -> Bool {\n guard let name = name(type: array) else { return false }\n return name.hasPrefix("Swift._ContiguousArrayStorage")\n }\n\n internal func isArrayOfClass(_ array: swift_reflection_ptr_t) -> Bool {\n guard isContiguousArray(array) else { return false }\n\n let typeref = swift_reflection_typeRefForMetadata(self, UInt(array))\n if typeref == 0 { return false }\n\n let count = swift_reflection_genericArgumentCountOfTypeRef(typeref)\n guard count == 1 else { return false }\n\n let argument = swift_reflection_genericArgumentOfTypeRef(typeref, 0)\n if argument == 0 { return false }\n\n let info = swift_reflection_infoForTypeRef(self, argument)\n return info.Kind == SWIFT_STRONG_REFERENCE\n }\n\n internal func arrayCount(_ array: swift_reflection_ptr_t,\n _ read: (swift_addr_t, Int) -> UnsafeRawPointer?) -> UInt? {\n // Array layout is: metadata, refCount, count\n let size = MemoryLayout<UInt>.stride * 3\n guard let pointer = read(swift_addr_t(array), size) else { return nil }\n let words = pointer.bindMemory(to: UInt.self, capacity: 3)\n return words[2]\n }\n\n internal func iterateConformanceCache(_ body: @escaping ConformanceIterationCallback) throws {\n var body = body\n if let error = withUnsafeMutablePointer(to: &body, {\n swift_reflection_iterateConformanceCache(self, {\n $2!.bindMemory(to: ConformanceIterationCallback.self, capacity: 1).pointee($0, $1)\n }, $0)\n }) {\n throw Error(cString: error)\n }\n }\n\n internal func iterateMetadataAllocations(_ body: @escaping MetadataAllocationIterationCallback) throws {\n var body = body\n if let error = withUnsafeMutablePointer(to: &body, {\n swift_reflection_iterateMetadataAllocations(self, {\n $1!.bindMemory(to: MetadataAllocationIterationCallback.self, capacity: 1).pointee($0)\n }, $0)\n }) {\n throw Error(cString: error)\n }\n }\n\n internal func iterateMetadataAllocationBacktraces(_ body: @escaping MetadataAllocationBacktraceIterationCallback) throws {\n var body = body\n if let error = withUnsafeMutablePointer(to: &body, {\n swift_reflection_iterateMetadataAllocationBacktraces(self, {\n $3!.bindMemory(to: MetadataAllocationBacktraceIterationCallback.self, capacity: 1).pointee($0, $1, $2!)\n }, $0)\n }) {\n throw Error(cString: error)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_RemoteMirror+Extensions.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_RemoteMirror+Extensions.swift
Swift
5,859
0.95
0.078788
0.085714
node-utils
899
2024-02-01T08:05:58.898145
Apache-2.0
false
893addba89ce41e50598837bbd2bbdc8
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftRemoteMirror\n\ninternal protocol RemoteProcess: AnyObject {\n associatedtype ProcessIdentifier\n associatedtype ProcessHandle\n\n var process: ProcessHandle { get }\n var context: SwiftReflectionContextRef! { get }\n var processIdentifier: ProcessIdentifier { get }\n var processName: String { get }\n\n typealias QueryDataLayoutFunction =\n @convention(c) (UnsafeMutableRawPointer?, DataLayoutQueryType,\n UnsafeMutableRawPointer?, UnsafeMutableRawPointer?) -> CInt\n typealias FreeFunction =\n @convention(c) (UnsafeMutableRawPointer?, UnsafeRawPointer?,\n UnsafeMutableRawPointer?) -> Void\n typealias ReadBytesFunction =\n @convention(c) (UnsafeMutableRawPointer?, swift_addr_t, UInt64,\n UnsafeMutablePointer<UnsafeMutableRawPointer?>?) -> UnsafeRawPointer?\n typealias GetStringLengthFunction =\n @convention(c) (UnsafeMutableRawPointer?, swift_addr_t) -> UInt64\n typealias GetSymbolAddressFunction =\n @convention(c) (UnsafeMutableRawPointer?, UnsafePointer<CChar>?, UInt64) -> swift_addr_t\n\n static var QueryDataLayout: QueryDataLayoutFunction { get }\n static var Free: FreeFunction? { get }\n static var ReadBytes: ReadBytesFunction { get }\n static var GetStringLength: GetStringLengthFunction { get }\n static var GetSymbolAddress: GetSymbolAddressFunction { get }\n\n func symbolicate(_ address: swift_addr_t) -> (module: String?, symbol: String?)\n func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void)\n}\n\nextension RemoteProcess {\n internal func toOpaqueRef() -> UnsafeMutableRawPointer {\n return Unmanaged.passRetained(self).toOpaque()\n }\n\n internal static func fromOpaque(_ ptr: UnsafeRawPointer) -> Self {\n return Unmanaged.fromOpaque(ptr).takeUnretainedValue()\n }\n\n internal func release() {\n Unmanaged.passUnretained(self).release()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_RemoteProcess.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_RemoteProcess.swift
Swift
2,386
0.95
0.033333
0.215686
awesome-app
482
2023-11-11T20:38:27.255687
BSD-3-Clause
false
5d758c11d907d96ffd70a2ba61b6c119
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftRemoteMirror\nimport Foundation\n\nextension DefaultStringInterpolation {\n mutating func appendInterpolation<T>(hex: T) where T: BinaryInteger {\n appendInterpolation("0x")\n appendInterpolation(String(hex, radix: 16))\n }\n}\n\nenum Std {\n struct File: TextOutputStream {\n\n#if os(Android)\n typealias File = OpaquePointer\n#else\n typealias File = UnsafeMutablePointer<FILE>\n#endif\n\n var underlying: File\n\n mutating func write(_ string: String) {\n fputs(string, underlying)\n }\n }\n\n static var err = File(underlying: stderr)\n}\n\ninternal func disableStdErrBuffer() {\n setvbuf(stderr, nil, Int32(_IONBF), 0)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_String+Extensions.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_String+Extensions.swift
Swift
1,160
0.95
0.068182
0.388889
node-utils
916
2024-04-18T07:43:18.808210
GPL-3.0
false
6c26f28ffa2aa1970dc12046ddff213c
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)\n\nimport Foundation\nimport SymbolicationShims\n\nprivate let symbolicationPath =\n "/System/Library/PrivateFrameworks/Symbolication.framework/Symbolication"\nprivate let symbolicationHandle = dlopen(symbolicationPath, RTLD_LAZY)!\n\nprivate let coreSymbolicationPath =\n "/System/Library/PrivateFrameworks/CoreSymbolication.framework/CoreSymbolication"\nprivate let coreSymbolicationHandle = dlopen(coreSymbolicationPath, RTLD_LAZY)!\n\nprivate func symbol<T>(_ handle: UnsafeMutableRawPointer, _ name: String) -> T {\n guard let result = dlsym(handle, name) else {\n fatalError("Unable to look up \(name) in Symbolication")\n }\n return unsafeBitCast(result, to: T.self)\n}\n\nprivate func objcClass<T>(_ name: String) -> T? {\n guard let result = objc_getClass(name) as? AnyClass else {\n return nil\n }\n return unsafeBitCast(result, to: T.self)\n}\n\nenum Sym {\n static let pidFromHint: @convention(c) (AnyObject) -> pid_t =\n symbol(symbolicationHandle, "pidFromHint")\n static let CSRelease: @convention(c) (CSTypeRef) -> Void =\n symbol(coreSymbolicationHandle, "CSRelease")\n static let CSSymbolicatorCreateWithTask: @convention(c) (task_t) -> CSTypeRef =\n symbol(coreSymbolicationHandle, "CSSymbolicatorCreateWithTask")\n static let CSSymbolicatorGetSymbolOwnerWithNameAtTime:\n @convention(c) (CSTypeRef, UnsafePointer<CChar>, CSMachineTime) -> CSTypeRef =\n symbol(coreSymbolicationHandle, "CSSymbolicatorGetSymbolOwnerWithNameAtTime")\n static let CSSymbolOwnerForeachSymbol:\n @convention(c) (CSTypeRef, @convention(block) (CSTypeRef) -> Void) -> UInt =\n symbol(coreSymbolicationHandle, "CSSymbolOwnerForeachSymbol")\n static let CSSymbolOwnerGetSymbolWithMangledName: @convention(c)\n (CSTypeRef, UnsafePointer<CChar>) -> CSTypeRef =\n symbol(coreSymbolicationHandle, "CSSymbolOwnerGetSymbolWithMangledName")\n static let CSSymbolGetName: @convention(c) (CSTypeRef) -> UnsafePointer<CChar>? =\n symbol(coreSymbolicationHandle, "CSSymbolGetName")\n static let CSSymbolGetMangledName: @convention(c) (CSTypeRef) -> UnsafePointer<CChar>? =\n symbol(coreSymbolicationHandle, "CSSymbolGetMangledName")\n static let CSSymbolGetSymbolOwner: @convention(c)\n (CSSymbolRef) -> CSSymbolOwnerRef =\n symbol(coreSymbolicationHandle, "CSSymbolGetSymbolOwner")\n static let CSSymbolIsFunction: @convention(c) (CSTypeRef) -> CBool =\n symbol(coreSymbolicationHandle, "CSSymbolIsFunction")\n static let CSSymbolGetRange: @convention(c) (CSTypeRef) -> Range =\n symbol(coreSymbolicationHandle, "CSSymbolGetRange")\n static let CSSymbolOwnerGetName: @convention(c) (CSSymbolOwnerRef) -> UnsafePointer<CChar>? =\n symbol(coreSymbolicationHandle, "CSSymbolOwnerGetName")\n static let CSSymbolicatorGetSymbolWithAddressAtTime: @convention(c)\n (CSSymbolicatorRef, mach_vm_address_t, CSMachineTime) -> CSSymbolRef =\n symbol(coreSymbolicationHandle, "CSSymbolicatorGetSymbolWithAddressAtTime")\n static let CSSymbolicatorForeachSymbolOwnerAtTime:\n @convention(c) (CSSymbolicatorRef, CSMachineTime, @convention(block) (CSSymbolOwnerRef) -> Void) -> UInt =\n symbol(coreSymbolicationHandle, "CSSymbolicatorForeachSymbolOwnerAtTime")\n static let CSSymbolOwnerGetBaseAddress: @convention(c) (CSSymbolOwnerRef) -> mach_vm_address_t =\n symbol(symbolicationHandle, "CSSymbolOwnerGetBaseAddress")\n static let CSIsNull: @convention(c) (CSTypeRef) -> CBool =\n symbol(coreSymbolicationHandle, "CSIsNull")\n static let task_start_peeking: @convention(c) (task_t) -> kern_return_t =\n symbol(symbolicationHandle, "task_start_peeking")\n static let task_peek: @convention(c) (task_t, mach_vm_address_t, mach_vm_size_t,\n UnsafeMutablePointer<UnsafeRawPointer?>) ->\n kern_return_t =\n symbol(symbolicationHandle, "task_peek")\n static let task_peek_string: @convention(c) (task_t, mach_vm_address_t) ->\n UnsafeMutablePointer<CChar>? =\n symbol(symbolicationHandle, "task_peek_string")\n static let task_stop_peeking: @convention(c) (task_t) -> kern_return_t =\n symbol(symbolicationHandle, "task_stop_peeking")\n\n typealias vm_range_recorder_t =\n @convention(c) (task_t, UnsafeMutableRawPointer?, CUnsignedInt,\n UnsafeMutablePointer<vm_range_t>, CUnsignedInt) -> Void\n static let task_enumerate_malloc_blocks:\n @convention(c) (task_t, UnsafeMutableRawPointer?, CUnsignedInt, vm_range_recorder_t)\n -> Void =\n symbol(symbolicationHandle, "task_enumerate_malloc_blocks")\n}\n\ntypealias CSMachineTime = UInt64\nlet kCSNow = CSMachineTime(Int64.max) + 1\n\ntypealias CSSymbolicatorRef = CSTypeRef\ntypealias CSSymbolRef = CSTypeRef\ntypealias CSSymbolOwnerRef = CSTypeRef\n\n// Declare just enough of VMUProcInfo for our purposes. It does not actually\n// conform to this protocol, but ObjC protocol method dispatch is based entirely\n// around msgSend and the presence of the method on the class, not conformance.\n@objc protocol VMUProcInfo {\n @objc(initWithTask:)\n init(task: task_read_t)\n\n var shouldAnalyzeWithCorpse: Bool { get }\n}\n\nfunc pidFromHint(_ hint: String) -> pid_t? {\n let result = Sym.pidFromHint(hint as NSString)\n return result == 0 ? nil : result\n}\n\nfunc CSRelease(_ sym: CSTypeRef) -> Void {\n Sym.CSRelease(sym)\n}\n\nfunc CSSymbolicatorCreateWithTask(_ task: task_t) -> CSTypeRef {\n Sym.CSSymbolicatorCreateWithTask(task)\n}\n\nfunc CSSymbolicatorGetSymbolOwnerWithNameAtTime(\n _ symbolicator: CSTypeRef,\n _ name: String,\n _ time: CSMachineTime\n) -> CSTypeRef {\n Sym.CSSymbolicatorGetSymbolOwnerWithNameAtTime(symbolicator, name, time)\n}\n\n@discardableResult\nfunc CSSymbolOwnerForeachSymbol(\n _ symbolOwner: CSTypeRef,\n _ iterator: (CSTypeRef) -> Void\n) -> UInt {\n Sym.CSSymbolOwnerForeachSymbol(symbolOwner, iterator)\n}\n\nfunc CSSymbolOwnerGetSymbolWithMangledName(\n _ owner: CSTypeRef,\n _ name: String\n) -> CSTypeRef {\n Sym.CSSymbolOwnerGetSymbolWithMangledName(owner, name)\n}\n\nfunc CSSymbolGetName(_ sym: CSTypeRef) -> String? {\n let name = Sym.CSSymbolGetName(sym)\n return name.map{ String(cString: $0) }\n}\n\nfunc CSSymbolGetMangledName(_ sym: CSTypeRef) -> String? {\n let name = Sym.CSSymbolGetMangledName(sym)\n return name.map{ String(cString: $0) }\n}\n\nfunc CSSymbolIsFunction(_ sym: CSTypeRef) -> Bool {\n Sym.CSSymbolIsFunction(sym)\n}\n\nfunc CSSymbolGetRange(_ sym: CSTypeRef) -> Range {\n Sym.CSSymbolGetRange(sym)\n}\n\nfunc CSSymbolGetSymbolOwner(_ sym: CSTypeRef) -> CSSymbolOwnerRef {\n Sym.CSSymbolGetSymbolOwner(sym)\n}\n\nfunc CSSymbolOwnerGetName(_ sym: CSTypeRef) -> String? {\n Sym.CSSymbolOwnerGetName(sym)\n .map(String.init(cString:))\n}\n\nfunc CSSymbolicatorGetSymbolWithAddressAtTime(\n _ symbolicator: CSSymbolicatorRef,\n _ address: mach_vm_address_t,\n _ time: CSMachineTime\n) -> CSSymbolRef {\n Sym.CSSymbolicatorGetSymbolWithAddressAtTime(symbolicator, address, time)\n}\n\nfunc CSSymbolicatorForeachSymbolOwnerAtTime(\n _ symbolicator: CSSymbolicatorRef,\n _ time: CSMachineTime,\n _ symbolIterator: (CSSymbolOwnerRef) -> Void\n ) -> UInt {\n return Sym.CSSymbolicatorForeachSymbolOwnerAtTime(symbolicator, time,\n symbolIterator)\n}\n\nfunc CSSymbolOwnerGetBaseAddress(_ symbolOwner: CSSymbolOwnerRef) -> mach_vm_address_t {\n return Sym.CSSymbolOwnerGetBaseAddress(symbolOwner)\n}\n\nfunc CSIsNull(_ symbol: CSTypeRef) -> Bool {\n Sym.CSIsNull(symbol)\n}\n\nfunc task_start_peeking(_ task: task_t) -> Bool {\n let result = Sym.task_start_peeking(task)\n if result == KERN_SUCCESS {\n return true\n }\n\n print("task_start_peeking failed: \(machErrStr(result))", to: &Std.err)\n return false\n}\n\nfunc task_peek(\n _ task: task_t, _ start: mach_vm_address_t, _ size: mach_vm_size_t\n) -> UnsafeRawPointer? {\n var ptr: UnsafeRawPointer? = nil\n let result = Sym.task_peek(task, start, size, &ptr)\n if result != KERN_SUCCESS {\n return nil\n }\n return ptr\n}\n\nfunc task_peek_string(\n _ task: task_t, _ addr: mach_vm_address_t\n) -> UnsafeMutablePointer<CChar>? {\n Sym.task_peek_string(task, addr)\n}\n\nfunc task_stop_peeking(_ task: task_t) {\n _ = Sym.task_stop_peeking(task)\n}\n\nfunc task_enumerate_malloc_blocks(\n _ task: task_t,\n _ context: UnsafeMutableRawPointer?,\n _ type_mask: CUnsignedInt,\n _ recorder: Sym.vm_range_recorder_t\n) {\n Sym.task_enumerate_malloc_blocks(task, context, type_mask, recorder)\n}\n\nfunc machErrStr(_ kr: kern_return_t) -> String {\n let errStr = String(cString: mach_error_string(kr))\n let errHex = String(kr, radix: 16)\n return "\(errStr) (0x\(errHex))"\n}\n\nfunc getVMUProcInfoClass() -> VMUProcInfo.Type? {\n return objcClass("VMUProcInfo")\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Symbolication+Extensions.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_Symbolication+Extensions.swift
Swift
9,240
0.95
0.027451
0.073394
python-kit
673
2024-09-22T05:44:22.006435
Apache-2.0
false
a4a17857a03b0febff1d9abf8256a90f