From a86b7ccfe489453314d3608ec13d4de29b515a9b Mon Sep 17 00:00:00 2001 From: Erik Eckstein Date: Thu, 5 Oct 2023 16:04:03 +0200 Subject: [PATCH 1/3] AST: fix missing header files `ForeignAsyncConvention.h` and `ForeignErrorConvention.h` must be included in `Decl.h`, because those types are used in an `llvm::Optional` in `Decl.h`. --- include/swift/AST/Decl.h | 4 ++-- lib/AST/Decl.cpp | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 87631f3000eb9..5f5545edbe204 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -26,6 +26,8 @@ #include "swift/AST/DefaultArgumentKind.h" #include "swift/AST/DiagnosticConsumer.h" #include "swift/AST/DiagnosticEngine.h" +#include "swift/AST/ForeignAsyncConvention.h" +#include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/FreestandingMacroExpansion.h" #include "swift/AST/GenericParamKey.h" #include "swift/AST/IfConfigClause.h" @@ -72,8 +74,6 @@ namespace swift { struct ExternalSourceLocs; class CaptureListExpr; class DeclRefExpr; - class ForeignAsyncConvention; - class ForeignErrorConvention; class LiteralExpr; class BraceStmt; class DeclAttributes; diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 2cd962f266755..4a89214c7172c 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -27,8 +27,6 @@ #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/ExistentialLayout.h" #include "swift/AST/Expr.h" -#include "swift/AST/ForeignAsyncConvention.h" -#include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/Initializer.h" From 2dbd6cc56bb29db3d23dcd3c85d83f75ddc8bfab Mon Sep 17 00:00:00 2001 From: Erik Eckstein Date: Fri, 6 Oct 2023 20:19:24 +0200 Subject: [PATCH 2/3] SwiftCompilerSources: rework bridging Introduce two modes of bridging: * inline mode: this is basically how it worked so far. Using full C++ interop which allows bridging functions to be inlined. * pure mode: bridging functions are not inlined but compiled in a cpp file. This allows to reduce the C++ interop requirements to a minimum. No std/llvm/swift headers are imported. This change requires a major refactoring of bridging sources. The implementation of bridging functions go to two separate files: SILBridgingImpl.h and OptimizerBridgingImpl.h. Depending on the mode, those files are either included in the corresponding header files (inline mode), or included in the c++ file (pure mode). The mode can be selected with the BRIDGING_MODE cmake variable. By default it is set to the inline mode (= existing behavior). The pure mode is only selected in certain configurations to work around C++ interop issues: * In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). * On windows to workaround a build problem. --- CMakeLists.txt | 18 + SwiftCompilerSources/CMakeLists.txt | 14 +- .../Sources/AST/DiagnosticEngine.swift | 40 +- .../Sources/Basic/SourceLoc.swift | 40 +- .../Sources/Basic/Utils.swift | 64 +- .../Optimizer/Analysis/AliasAnalysis.swift | 4 +- .../Optimizer/Analysis/CalleeAnalysis.swift | 8 +- .../FunctionPasses/MergeCondFails.swift | 2 +- .../FunctionPasses/ObjectOutliner.swift | 14 +- .../SimplifyCondBranch.swift | 6 +- .../SimplifyCondFail.swift | 5 +- .../SimplifyLoad.swift | 11 +- .../Optimizer/PassManager/Context.swift | 13 +- .../PassManager/ModulePassContext.swift | 6 +- .../PassManager/PassRegistration.swift | 6 +- .../Sources/Optimizer/Utilities/Test.swift | 4 +- .../Optimizer/Utilities/WalkUtils.swift | 16 +- .../Sources/Parse/Regex.swift | 2 +- .../Sources/SIL/BasicBlock.swift | 3 +- .../Sources/SIL/Builder.swift | 8 +- .../Sources/SIL/Function.swift | 21 +- .../Sources/SIL/GlobalVariable.swift | 9 +- .../Sources/SIL/Instruction.swift | 20 +- .../Sources/SIL/Location.swift | 7 +- .../Sources/SIL/Registration.swift | 2 +- .../Sources/SIL/SubstitutionMap.swift | 8 +- SwiftCompilerSources/Sources/SIL/Type.swift | 46 +- SwiftCompilerSources/Sources/SIL/VTable.swift | 8 +- SwiftCompilerSources/Sources/SIL/Value.swift | 3 +- .../Sources/SIL/WitnessTable.swift | 15 +- cmake/modules/SwiftSharedCMakeConfig.cmake | 4 + include/module.modulemap | 13 - include/swift/AST/ASTBridging.h | 64 +- include/swift/Basic/BasicBridging.h | 83 +- include/swift/Parse/RegexParserBridging.h | 2 +- include/swift/SIL/SILBridging.h | 1882 +++++------------ include/swift/SIL/SILBridgingImpl.h | 1402 ++++++++++++ include/swift/SIL/SILLocation.h | 2 - .../swift/SILOptimizer/OptimizerBridging.h | 556 ++--- .../SILOptimizer/OptimizerBridgingImpl.h | 405 ++++ lib/AST/ASTBridging.cpp | 45 +- lib/Basic/BasicBridging.cpp | 25 +- lib/Parse/ParseRegex.cpp | 2 +- lib/SIL/IR/SILBasicBlock.cpp | 1 - lib/SIL/IR/SILFunction.cpp | 7 +- lib/SIL/IR/SILLocation.cpp | 18 - lib/SIL/Utils/SILBridging.cpp | 157 +- lib/SILOptimizer/PassManager/PassManager.cpp | 317 --- lib/SILOptimizer/PassManager/Passes.cpp | 8 +- lib/SILOptimizer/SILCombiner/SILCombine.cpp | 4 +- lib/SILOptimizer/Utils/CMakeLists.txt | 1 + lib/SILOptimizer/Utils/OptimizerBridging.cpp | 332 +++ 52 files changed, 3396 insertions(+), 2357 deletions(-) create mode 100644 include/swift/SIL/SILBridgingImpl.h create mode 100644 include/swift/SILOptimizer/OptimizerBridgingImpl.h create mode 100644 lib/SILOptimizer/Utils/OptimizerBridging.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 38b9f214e467b..4bbc0f923ee87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -346,6 +346,13 @@ How to build the swift compiler modules. Possible values are compiler, provided in `SWIFT_NATIVE_SWIFT_TOOLS_PATH` ]=] OFF) +option(BRIDGING_MODE [=[ +How swift-C++ bridging code is compiled: + INLINE: uses full swift C++ interop and briding functions are inlined + PURE: uses limited C++ interp an bridging functions are not inlined + DEFAULT: based on the build configuration +]=] DEFAULT) + # The following only works with the Ninja generator in CMake >= 3.0. set(SWIFT_PARALLEL_LINK_JOBS "" CACHE STRING "Define the maximum number of linker jobs for swift.") @@ -390,6 +397,17 @@ set(SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY ${SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY_default} CACHE STRING "MSVC Runtime Library for the standard library") + +if(BRIDGING_MODE STREQUAL "DEFAULT" OR NOT BRIDGING_MODE) + if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") + # In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). + # On windows to workaround a build problem. + set(BRIDGING_MODE "PURE") + else() + set(BRIDGING_MODE "INLINE") + endif() +endif() + is_build_type_optimized("${SWIFT_STDLIB_BUILD_TYPE}" swift_optimized) if(swift_optimized) set(SWIFT_STDLIB_ASSERTIONS_default FALSE) diff --git a/SwiftCompilerSources/CMakeLists.txt b/SwiftCompilerSources/CMakeLists.txt index 138d208d9a3a9..e962132dec50e 100644 --- a/SwiftCompilerSources/CMakeLists.txt +++ b/SwiftCompilerSources/CMakeLists.txt @@ -76,6 +76,7 @@ function(add_swift_compiler_modules_library name) "-Xfrontend" "-validate-tbd-against-ir=none" "-Xfrontend" "-enable-experimental-cxx-interop" "-Xcc" "-std=c++17" + "-Xcc" "-DCOMPILED_WITH_SWIFT" "-Xcc" "-UIBOutlet" "-Xcc" "-UIBAction" "-Xcc" "-UIBInspectable") if (NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") list(APPEND swift_compile_options "-Xfrontend" "-disable-implicit-string-processing-module-import") @@ -91,6 +92,10 @@ function(add_swift_compiler_modules_library name) list(APPEND swift_compile_options "-Xcc" "-DNDEBUG") endif() + if("${BRIDGING_MODE}" STREQUAL "PURE") + list(APPEND swift_compile_options "-Xcc" "-DPURE_BRIDGING_MODE") + endif() + if(NOT SWIFT_STDLIB_SUPPORT_BACK_DEPLOYMENT) list(APPEND swift_compile_options "-Xfrontend" "-disable-legacy-type-info") endif() @@ -237,16 +242,11 @@ else() # defined in include/swift/module.modulemap file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/HeaderDependencies.cpp.tmp" " -#include \"Basic/BridgedSwiftObject.h\" -#include \"Basic/BasicBridging.h\" -#include \"Basic/SourceLoc.h\" +#define COMPILED_WITH_SWIFT +#include \"Basic/BasicBridging.h\" #include \"AST/ASTBridging.h\" -#include \"AST/DiagnosticEngine.h\" -#include \"AST/DiagnosticConsumer.h\" - #include \"SIL/SILBridging.h\" - #include \"SILOptimizer/OptimizerBridging.h\" #include \"Parse/RegexParserBridging.h\" diff --git a/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift b/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift index 69d4c8b77f8a7..1073ff0392b92 100644 --- a/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift +++ b/SwiftCompilerSources/Sources/AST/DiagnosticEngine.swift @@ -17,16 +17,16 @@ import Basic public typealias DiagID = BridgedDiagID public protocol DiagnosticArgument { - func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) + func _withBridgedDiagnosticArgument(_ fn: (BridgedDiagnosticArgument) -> Void) } extension String: DiagnosticArgument { - public func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) { - _withStringRef { fn(swift.DiagnosticArgument($0)) } + public func _withBridgedDiagnosticArgument(_ fn: (BridgedDiagnosticArgument) -> Void) { + _withBridgedStringRef { fn(BridgedDiagnosticArgument($0)) } } } extension Int: DiagnosticArgument { - public func _withBridgedDiagnosticArgument(_ fn: (swift.DiagnosticArgument) -> Void) { - fn(swift.DiagnosticArgument(Int32(self))) + public func _withBridgedDiagnosticArgument(_ fn: (BridgedDiagnosticArgument) -> Void) { + fn(BridgedDiagnosticArgument(self)) } } @@ -41,12 +41,11 @@ public struct DiagnosticFixIt { self.text = text } - func withBridgedDiagnosticFixIt(_ fn: (swift.DiagnosticInfo.FixIt) -> Void) { - text._withStringRef { bridgedTextRef in - let bridgedDiagnosticFixIt = swift.DiagnosticInfo.FixIt( - swift.CharSourceRange(start.bridged, UInt32(byteLength)), - bridgedTextRef, - ArrayRefOfDiagnosticArgument()) + func withBridgedDiagnosticFixIt(_ fn: (BridgedDiagnosticFixIt) -> Void) { + text._withBridgedStringRef { bridgedTextRef in + let bridgedDiagnosticFixIt = BridgedDiagnosticFixIt( + start.bridged, UInt32(byteLength), + bridgedTextRef) fn(bridgedDiagnosticFixIt) } } @@ -71,10 +70,18 @@ public struct DiagnosticEngine { highlight: CharSourceRange? = nil, fixIts: [DiagnosticFixIt] = []) { - let bridgedSourceLoc: swift.SourceLoc = position.bridged - let bridgedHighlightRange: swift.CharSourceRange = highlight.bridged - var bridgedArgs: [swift.DiagnosticArgument] = [] - var bridgedFixIts: [swift.DiagnosticInfo.FixIt] = [] + let bridgedSourceLoc: BridgedSourceLoc = position.bridged + let highlightStart: BridgedSourceLoc + let highlightLength: UInt32 + if let highlight = highlight { + highlightStart = highlight.start.bridged + highlightLength = highlight.byteLength + } else { + highlightStart = BridgedSourceLoc() + highlightLength = 0 + } + var bridgedArgs: [BridgedDiagnosticArgument] = [] + var bridgedFixIts: [BridgedDiagnosticFixIt] = [] // Build a higher-order function to wrap every 'withBridgedXXX { ... }' // calls, so we don't escape anything from the closure. 'bridgedArgs' and @@ -86,7 +93,8 @@ public struct DiagnosticEngine { bridgedFixIts.withBridgedArrayRef { bridgedFixItsRef in DiagnosticEngine_diagnose(bridged, bridgedSourceLoc, id, bridgedArgsRef, - bridgedHighlightRange, bridgedFixItsRef) + highlightStart, highlightLength, + bridgedFixItsRef) } } } diff --git a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift index aa1094dd78679..9f831ec3e0f0f 100644 --- a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift +++ b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift @@ -23,19 +23,15 @@ public struct SourceLoc { self.locationInFile = locationInFile } - public init?(bridged: swift.SourceLoc) { + public init?(bridged: BridgedSourceLoc) { guard bridged.isValid() else { return nil } -#if $NewCxxMethodSafetyHeuristics - self.locationInFile = bridged.getOpaquePointerValue().assumingMemoryBound(to: UInt8.self) -#else - self.locationInFile = bridged.__getOpaquePointerValueUnsafe().assumingMemoryBound(to: UInt8.self) -#endif + self.locationInFile = bridged.opaquePointer! } - public var bridged: swift.SourceLoc { - .init(llvm.SMLoc.getFromPointer(locationInFile)) + public var bridged: BridgedSourceLoc { + .init(opaquePointer: locationInFile) } } @@ -46,40 +42,24 @@ extension SourceLoc { } extension Optional where Wrapped == SourceLoc { - public var bridged: swift.SourceLoc { + public var bridged: BridgedSourceLoc { self?.bridged ?? .init() } } public struct CharSourceRange { - private let start: SourceLoc - private let byteLength: UInt32 + public let start: SourceLoc + public let byteLength: UInt32 public init(start: SourceLoc, byteLength: UInt32) { self.start = start self.byteLength = byteLength } - public init?(bridged: swift.CharSourceRange) { -#if $NewCxxMethodSafetyHeuristics - guard let start = SourceLoc(bridged: bridged.getStart()) else { + public init?(bridgedStart: BridgedSourceLoc, byteLength: UInt32) { + guard let start = SourceLoc(bridged: bridgedStart) else { return nil } -#else - guard let start = SourceLoc(bridged: bridged.__getStartUnsafe()) else { - return nil - } -#endif - self.init(start: start, byteLength: bridged.getByteLength()) - } - - public var bridged: swift.CharSourceRange { - .init(start.bridged, byteLength) - } -} - -extension Optional where Wrapped == CharSourceRange { - public var bridged: swift.CharSourceRange { - self?.bridged ?? .init(.init(), 0) + self.init(start: start, byteLength: byteLength) } } diff --git a/SwiftCompilerSources/Sources/Basic/Utils.swift b/SwiftCompilerSources/Sources/Basic/Utils.swift index 853d3835faa80..511fe58f00b3b 100644 --- a/SwiftCompilerSources/Sources/Basic/Utils.swift +++ b/SwiftCompilerSources/Sources/Basic/Utils.swift @@ -58,42 +58,31 @@ public extension NoReflectionChildren { //===----------------------------------------------------------------------===// public struct StringRef : CustomStringConvertible, NoReflectionChildren { - let _bridged: llvm.StringRef + let _bridged: BridgedStringRef - public init(bridged: llvm.StringRef) { self._bridged = bridged } + public init(bridged: BridgedStringRef) { self._bridged = bridged } - public var string: String { _bridged.string } + public var string: String { String(_bridged) } public var description: String { string } public var count: Int { -#if $NewCxxMethodSafetyHeuristics - Int(_bridged.bytes_end() - _bridged.bytes_begin()) -#else - Int(_bridged.__bytes_endUnsafe() - _bridged.__bytes_beginUnsafe()) -#endif + Int(_bridged.size()) } public subscript(index: Int) -> UInt8 { -#if $NewCxxMethodSafetyHeuristics - let buffer = UnsafeBufferPointer(start: _bridged.bytes_begin(), - count: count) -#else - let buffer = UnsafeBufferPointer(start: _bridged.__bytes_beginUnsafe(), - count: count) -#endif + let buffer = UnsafeBufferPointer(start: _bridged.uintData(), count: count) return buffer[index] } + public static func ==(lhs: StringRef, rhs: StringRef) -> Bool { + let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) + let rhsBuffer = UnsafeBufferPointer(start: rhs._bridged.uintData(), count: rhs.count) + if lhsBuffer.count != rhsBuffer.count { return false } + return lhsBuffer.elementsEqual(rhsBuffer, by: ==) + } + public static func ==(lhs: StringRef, rhs: StaticString) -> Bool { -#if $NewCxxMethodSafetyHeuristics - let lhsBuffer = UnsafeBufferPointer( - start: lhs._bridged.bytes_begin(), - count: lhs.count) -#else - let lhsBuffer = UnsafeBufferPointer( - start: lhs._bridged.__bytes_beginUnsafe(), - count: lhs.count) -#endif + let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) return rhs.withUTF8Buffer { (rhsBuffer: UnsafeBufferPointer) in if lhsBuffer.count != rhsBuffer.count { return false } return lhsBuffer.elementsEqual(rhsBuffer, by: ==) @@ -101,6 +90,7 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { } public static func !=(lhs: StringRef, rhs: StaticString) -> Bool { !(lhs == rhs) } + public static func !=(lhs: StringRef, rhs: StringRef) -> Bool { !(lhs == rhs) } public static func ~=(pattern: StaticString, value: StringRef) -> Bool { value == pattern } } @@ -109,27 +99,23 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { // Bridging Utilities //===----------------------------------------------------------------------===// -extension llvm.StringRef { - public var string: String { - String(_cxxString: self.str()) - } -} - extension String { - /// Underscored to avoid name collision with Swift LLVM Bindings. - /// To be replaced with a bindings call once bindings are a dependency. - public func _withStringRef(_ c: (llvm.StringRef) -> T) -> T { + public func _withBridgedStringRef(_ c: (BridgedStringRef) -> T) -> T { var str = self return str.withUTF8 { buffer in - return c(llvm.StringRef(buffer.baseAddress, buffer.count)) + return c(BridgedStringRef(buffer.baseAddress, buffer.count)) } } - /// Underscored to avoid name collision with the std overlay. - /// To be replaced with an overlay call once the CI uses SDKs built with Swift 5.8. - public init(_cxxString s: std.string) { - self.init(cString: s.__c_strUnsafe()) - withExtendedLifetime(s) {} + public init(_ s: BridgedStringRef) { + let buffer = UnsafeBufferPointer(start: s.uintData(), count: Int(s.size())) + self.init(decoding: buffer, as: UTF8.self) + } + + public init(taking s: BridgedOwnedString) { + let buffer = UnsafeBufferPointer(start: s.uintData(), count: s.size()) + self.init(decoding: buffer, as: UTF8.self) + s.destroy() } } diff --git a/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift b/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift index 21a0c2ce5116e..c2a880cd9b29a 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift @@ -36,7 +36,7 @@ struct AliasAnalysis { static func register() { BridgedAliasAnalysis.registerAnalysis( // getMemEffectsFn - { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> swift.MemoryBehavior in + { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> BridgedMemoryBehavior in let context = FunctionPassContext(_bridged: bridgedCtxt) let inst = bridgedInst.instruction let val = bridgedVal.value @@ -255,7 +255,7 @@ private struct IsIndirectResultWalker: AddressDefUseWalker { } private extension SideEffects.Memory { - var bridged: swift.MemoryBehavior { + var bridged: BridgedMemoryBehavior { switch (read, write) { case (false, false): return .None case (true, false): return .MayRead diff --git a/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift b/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift index 18f0640d4a958..fc55ceb9393e9 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift @@ -23,7 +23,7 @@ public struct CalleeAnalysis { return inst.instruction.isDeinitBarrier(bca.analysis) }, // getMemBehaviorFn - { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> swift.MemoryBehavior in + { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> BridgedMemoryBehavior in let apply = bridgedApply.instruction as! ApplySite let e = bca.analysis.getSideEffects(ofApply: apply) return e.getMemBehavior(observeRetains: observeRetains) @@ -126,13 +126,13 @@ extension Instruction { } public struct FunctionArray : RandomAccessCollection, FormattedLikeArray { - fileprivate let bridged: swift.CalleeList + fileprivate let bridged: BridgedCalleeAnalysis.CalleeList public var startIndex: Int { 0 } - public var endIndex: Int { Int(bridged.getCount()) } + public var endIndex: Int { bridged.getCount() } public subscript(_ index: Int) -> Function { - return BridgedCalleeAnalysis.getCallee(bridged, index).function + return bridged.getCallee(index).function } } // Bridging utilities diff --git a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift index 7338d8f865093..64b0bfe1e6693 100644 --- a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift +++ b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift @@ -86,7 +86,7 @@ private func mergeCondFails(_ condFailToMerge: inout Stack, // Create a new cond_fail using the merged condition. _ = builder.createCondFail(condition: mergedCond!, - message: lastCFI.message) + message: lastCFI.message.string) while let cfi = condFailToMerge.pop() { context.erase(instruction: cfi) diff --git a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift index 849729d1159b8..b8eb6b1de9af7 100644 --- a/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift +++ b/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift @@ -159,10 +159,11 @@ private func findStores(toTailAddress tailAddr: Value, tailElementIndex: Int, st for use in tailAddr.uses { switch use.instruction { case let indexAddr as IndexAddrInst: - guard let indexLiteral = indexAddr.index as? IntegerLiteralInst else { + guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, + let tailIdx = indexLiteral.value else + { return false } - let tailIdx = Int(indexLiteral.value.getZExtValue()) if !findStores(toTailAddress: indexAddr, tailElementIndex: tailElementIndex + tailIdx, stores: &stores) { return false } @@ -399,11 +400,12 @@ private extension AllocRefInstBase { } // The number of tail allocated elements must be constant. - guard let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, - tailCountLiteral.value.getActiveBits() <= 20 else { - return nil + if let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, + let count = tailCountLiteral.value + { + return count } - return Int(tailCountLiteral.value.getZExtValue()); + return nil } var numClassFields: Int { diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift index 69a799e908711..8b71648f1e08b 100644 --- a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift @@ -20,11 +20,13 @@ extension CondBranchInst : OnoneSimplifyable { private extension CondBranchInst { func tryConstantFold(_ context: SimplifyContext) { - guard let literal = condition as? IntegerLiteralInst else { + guard let literal = condition as? IntegerLiteralInst, + let conditionValue = literal.value else + { return } let builder = Builder(before: self, context) - if literal.value.isZero() { + if conditionValue == 0 { builder.createBranch(to: falseBlock, arguments: Array(falseOperands.map { $0.value })) } else { builder.createBranch(to: trueBlock, arguments: Array(trueOperands.map { $0.value })) diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift index 9a423cae55b5b..b7ef2f29d300d 100644 --- a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift @@ -21,8 +21,9 @@ extension CondFailInst : OnoneSimplifyable { /// cond_fail %0, "message" /// ``` if let literal = condition as? IntegerLiteralInst, - literal.value.isZero() { - + let value = literal.value, + value == 0 + { context.erase(instruction: self) } } diff --git a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift index 0596b9402a040..8d61c21544e7f 100644 --- a/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift +++ b/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift @@ -284,10 +284,11 @@ private extension Value { func getBaseAddressAndOffset() -> (baseAddress: Value, offset: Int)? { if let indexAddr = self as? IndexAddrInst { guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, - indexLiteral.value.getActiveBits() <= 32 else { + let indexValue = indexLiteral.value else + { return nil } - return (baseAddress: indexAddr.base, offset: Int(indexLiteral.value.getZExtValue())) + return (baseAddress: indexAddr.base, offset: indexValue) } return (baseAddress: self, offset: 0) } @@ -297,9 +298,11 @@ private extension Instruction { var isShiftRightByAtLeastOne: Bool { guard let bi = self as? BuiltinInst, bi.id == .LShr, - let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst else { + let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst, + let shiftValue = shiftLiteral.value else + { return false } - return shiftLiteral.value.isStrictlyPositive() + return shiftValue > 0 } } diff --git a/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift b/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift index 325124c670314..d4f692ea2b8db 100644 --- a/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift +++ b/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift @@ -219,7 +219,7 @@ struct FunctionPassContext : MutatingContext { func loadFunction(name: StaticString, loadCalleesRecursively: Bool) -> Function? { return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in - let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) + let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) return _bridged.loadFunction(nameStr, loadCalleesRecursively).function } } @@ -237,7 +237,7 @@ struct FunctionPassContext : MutatingContext { /// Returns nil if no such function or multiple matching functions are found. func lookupStdlibFunction(name: StaticString) -> Function? { return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in - let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) + let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) return _bridged.lookupStdlibFunction(nameStr).function } } @@ -252,7 +252,7 @@ struct FunctionPassContext : MutatingContext { } func optimizeMemoryAccesses(in function: Function) -> Bool { - if swift.optimizeMemoryAccesses(function.bridged.getFunction()) { + if BridgedPassContext.optimizeMemoryAccesses(function.bridged) { notifyInstructionsChanged() return true } @@ -260,7 +260,7 @@ struct FunctionPassContext : MutatingContext { } func eliminateDeadAllocations(in function: Function) -> Bool { - if swift.eliminateDeadAllocations(function.bridged.getFunction()) { + if BridgedPassContext.eliminateDeadAllocations(function.bridged) { notifyInstructionsChanged() return true } @@ -293,12 +293,11 @@ struct FunctionPassContext : MutatingContext { } func mangleOutlinedVariable(from function: Function) -> String { - let stdString = _bridged.mangleOutlinedVariable(function.bridged) - return String(_cxxString: stdString) + return String(taking: _bridged.mangleOutlinedVariable(function.bridged)) } func createGlobalVariable(name: String, type: Type, isPrivate: Bool) -> GlobalVariable { - let gv = name._withStringRef { + let gv = name._withBridgedStringRef { _bridged.createGlobalVariable($0, type.bridged, isPrivate) } return gv.globalVar diff --git a/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift b/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift index f68dc5684864c..f2b7c26a8b91f 100644 --- a/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift +++ b/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift @@ -22,8 +22,7 @@ struct ModulePassContext : Context, CustomStringConvertible { let _bridged: BridgedPassContext public var description: String { - let stdString = _bridged.getModuleDescription() - return String(_cxxString: stdString) + return String(taking: _bridged.getModuleDescription()) } struct FunctionList : CollectionLikeSequence, IteratorProtocol { @@ -125,8 +124,7 @@ struct ModulePassContext : Context, CustomStringConvertible { } func mangleAsyncRemoved(from function: Function) -> String { - let stdString = _bridged.mangleAsyncRemoved(function.bridged) - return String(_cxxString: stdString) + return String(taking: _bridged.mangleAsyncRemoved(function.bridged)) } } diff --git a/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift b/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift index 41e7825ec755e..8860b7b284ad5 100644 --- a/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift +++ b/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift @@ -26,7 +26,7 @@ public func initializeSwiftModules() { private func registerPass( _ pass: ModulePass, _ runFn: @escaping (@convention(c) (BridgedPassContext) -> ())) { - pass.name._withStringRef { nameStr in + pass.name._withBridgedStringRef { nameStr in SILPassManager_registerModulePass(nameStr, runFn) } } @@ -34,7 +34,7 @@ private func registerPass( private func registerPass( _ pass: FunctionPass, _ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) { - pass.name._withStringRef { nameStr in + pass.name._withBridgedStringRef { nameStr in SILPassManager_registerFunctionPass(nameStr, runFn) } } @@ -55,7 +55,7 @@ private func run(_ instType: InstType.Type, private func registerForSILCombine( _ instType: InstType.Type, _ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) { - String(describing: instType)._withStringRef { instClassStr in + String(describing: instType)._withBridgedStringRef { instClassStr in SILCombine_registerInstructionPass(instClassStr, runFn) } } diff --git a/SwiftCompilerSources/Sources/Optimizer/Utilities/Test.swift b/SwiftCompilerSources/Sources/Optimizer/Utilities/Test.swift index a70ce095ea05a..06471b7c2e696 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Utilities/Test.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Utilities/Test.swift @@ -143,7 +143,7 @@ public func registerOptimizerTests() { private func registerFunctionTest(_ test: FunctionTest) { - test.name._withStringRef { ref in + test.name._withBridgedStringRef { ref in registerFunctionTest(ref, eraseInvocation(test.invocation)) } } @@ -207,7 +207,7 @@ FunctionTest(name: "test_specification_parsing") { function, arguments, context public mutating func write(_ string: String) { for c in string.utf8 { - _swift_stdlib_putc_stderr(CInt(c)) + writeCharToStderr(CInt(c)) } } } diff --git a/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift b/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift index 224feb63a6389..e9f1588fc3916 100644 --- a/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift +++ b/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift @@ -490,7 +490,7 @@ extension AddressDefUseWalker { } case let ia as IndexAddrInst: if let (pathIdx, subPath) = path.pop(kind: .indexedElement) { - if let idx = ia.constantSmallIndex, + if let idx = ia.constantIndex, idx == pathIdx { return walkDownUses(ofAddress: ia, path: subPath) } @@ -761,7 +761,7 @@ extension AddressUseDefWalker { case is BeginAccessInst, is MarkUnresolvedNonCopyableValueInst: return walkUp(address: (def as! Instruction).operands[0].value, path: path) case let ia as IndexAddrInst: - if let idx = ia.constantSmallIndex { + if let idx = ia.constantIndex { return walkUp(address: ia.base, path: path.push(.indexedElement, index: idx)) } else { return walkUp(address: ia.base, path: path.push(.anyIndexedElement, index: 0)) @@ -775,13 +775,11 @@ extension AddressUseDefWalker { } private extension IndexAddrInst { - var constantSmallIndex: Int? { - guard let literal = index as? IntegerLiteralInst else { - return nil - } - let index = literal.value - if index.isIntN(16) { - return Int(index.getSExtValue()) + var constantIndex: Int? { + if let literal = index as? IntegerLiteralInst, + let indexValue = literal.value + { + return indexValue } return nil } diff --git a/SwiftCompilerSources/Sources/Parse/Regex.swift b/SwiftCompilerSources/Sources/Parse/Regex.swift index a2229bc6fbc24..1b4f163fa1030 100644 --- a/SwiftCompilerSources/Sources/Parse/Regex.swift +++ b/SwiftCompilerSources/Sources/Parse/Regex.swift @@ -92,7 +92,7 @@ public func _RegexLiteralParsingFn( _ versionOut: UnsafeMutablePointer, _ captureStructureOut: UnsafeMutableRawPointer, _ captureStructureSize: CUnsignedInt, - _ bridgedDiagnosticBaseLoc: swift.SourceLoc, + _ bridgedDiagnosticBaseLoc: BridgedSourceLoc, _ bridgedDiagnosticEngine: BridgedDiagnosticEngine ) -> Bool { let str = String(cString: inputPtr) diff --git a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift index 6854ac57c7245..a2abd53250294 100644 --- a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift +++ b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift @@ -21,8 +21,7 @@ final public class BasicBlock : CustomStringConvertible, HasShortDescription, Eq public var parentFunction: Function { bridged.getFunction().function } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } public var shortDescription: String { name } diff --git a/SwiftCompilerSources/Sources/SIL/Builder.swift b/SwiftCompilerSources/Sources/SIL/Builder.swift index 0a28c4507b705..293c8fc6800f6 100644 --- a/SwiftCompilerSources/Sources/SIL/Builder.swift +++ b/SwiftCompilerSources/Sources/SIL/Builder.swift @@ -65,7 +65,7 @@ public struct Builder { public func createBuiltinBinaryFunction(name: String, operandType: Type, resultType: Type, arguments: [Value]) -> BuiltinInst { return arguments.withBridgedValues { valuesRef in - return name._withStringRef { nameStr in + return name._withBridgedStringRef { nameStr in let bi = bridged.createBuiltinBinaryFunction( nameStr, operandType.bridged, resultType.bridged, valuesRef) return notifyNew(bi.getAs(BuiltinInst.self)) @@ -74,7 +74,7 @@ public struct Builder { } public func createCondFail(condition: Value, message: String) -> CondFailInst { - return message._withStringRef { messageStr in + return message._withBridgedStringRef { messageStr in let cf = bridged.createCondFail(condition.bridged, messageStr) return notifyNew(cf.getAs(CondFailInst.self)) } @@ -199,7 +199,7 @@ public struct Builder { arguments: [Value], isNonThrowing: Bool = false, isNonAsync: Bool = false, - specializationInfo: ApplyInst.SpecializationInfo = nil + specializationInfo: ApplyInst.SpecializationInfo = ApplyInst.SpecializationInfo() ) -> ApplyInst { let apply = arguments.withBridgedValues { valuesRef in bridged.createApply(function.bridged, substitutionMap.bridged, valuesRef, @@ -314,7 +314,7 @@ public struct Builder { return notifyNew(initExistential.getAs(InitExistentialRefInst.self)) } - public func createMetatype(of type: Type, representation: swift.MetatypeRepresentation) -> MetatypeInst { + public func createMetatype(of type: Type, representation: Type.MetatypeRepresentation) -> MetatypeInst { let metatype = bridged.createMetatype(type.bridged, representation) return notifyNew(metatype.getAs(MetatypeInst.self)) } diff --git a/SwiftCompilerSources/Sources/SIL/Function.swift b/SwiftCompilerSources/Sources/SIL/Function.swift index b211a96b32f94..72e67e5682fc8 100644 --- a/SwiftCompilerSources/Sources/SIL/Function.swift +++ b/SwiftCompilerSources/Sources/SIL/Function.swift @@ -22,8 +22,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash } final public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } public var shortDescription: String { name.string } @@ -113,7 +112,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash public func hasSemanticsAttribute(_ attr: StaticString) -> Bool { attr.withUTF8Buffer { (buffer: UnsafeBufferPointer) in - bridged.hasSemanticsAttr(llvm.StringRef(buffer.baseAddress!, buffer.count)) + bridged.hasSemanticsAttr(BridgedStringRef(buffer.baseAddress!, buffer.count)) } } @@ -286,19 +285,19 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash } else { s = effects.description } - s._withStringRef { OStream_write(os, $0) } + s._withBridgedStringRef { $0.write(os) } }, // parseFn: - { (f: BridgedFunction, str: llvm.StringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in + { (f: BridgedFunction, str: BridgedStringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in do { - var parser = StringParser(str.string) + var parser = StringParser(String(str)) let function = f.function switch mode { case .argumentEffectsFromSource: - let paramToIdx = paramNames.withElements(ofType: llvm.StringRef.self) { - (buffer: UnsafeBufferPointer) -> Dictionary in - let keyValPairs = buffer.enumerated().lazy.map { ($0.1.string, $0.0) } + let paramToIdx = paramNames.withElements(ofType: BridgedStringRef.self) { + (buffer: UnsafeBufferPointer) -> Dictionary in + let keyValPairs = buffer.enumerated().lazy.map { (String($0.1), $0.0) } return Dictionary(uniqueKeysWithValues: keyValPairs) } let effect = try parser.parseEffectFromSource(for: function, params: paramToIdx) @@ -360,7 +359,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return BridgedFunction.EffectInfo(argumentIndex: -1, isDerived: false, isEmpty: true, isValid: false) }, // getMemBehaviorFn - { (f: BridgedFunction, observeRetains: Bool) -> swift.MemoryBehavior in + { (f: BridgedFunction, observeRetains: Bool) -> BridgedMemoryBehavior in let e = f.function.getSideEffects() return e.getMemBehavior(observeRetains: observeRetains) } @@ -395,7 +394,7 @@ extension OptionalBridgedFunction { } public extension SideEffects.GlobalEffects { - func getMemBehavior(observeRetains: Bool) -> swift.MemoryBehavior { + func getMemBehavior(observeRetains: Bool) -> BridgedMemoryBehavior { if allocates || ownership.destroy || (ownership.copy && observeRetains) { return .MayHaveSideEffects } diff --git a/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift b/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift index e231757bdf341..e30843b7cd50f 100644 --- a/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift +++ b/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift @@ -19,8 +19,7 @@ final public class GlobalVariable : CustomStringConvertible, HasShortDescription } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } public var shortDescription: String { name.string } @@ -163,8 +162,10 @@ private extension TupleExtractInst { let bi = tuple as? BuiltinInst, bi.id == .USubOver, bi.operands[1].value is IntegerLiteralInst, - let overFlowFlag = bi.operands[2].value as? IntegerLiteralInst, - overFlowFlag.value.isNullValue() { + let overflowLiteral = bi.operands[2].value as? IntegerLiteralInst, + let overflowValue = overflowLiteral.value, + overflowValue == 0 + { return true } return false diff --git a/SwiftCompilerSources/Sources/SIL/Instruction.swift b/SwiftCompilerSources/Sources/SIL/Instruction.swift index 8b32075528899..2dba4c1773985 100644 --- a/SwiftCompilerSources/Sources/SIL/Instruction.swift +++ b/SwiftCompilerSources/Sources/SIL/Instruction.swift @@ -34,8 +34,7 @@ public class Instruction : CustomStringConvertible, Hashable { final public var parentFunction: Function { parentBlock.parentFunction } final public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } final public var isDeleted: Bool { @@ -347,7 +346,7 @@ final public class CondFailInst : Instruction, UnaryInstruction { public var condition: Value { operand.value } public override var mayTrap: Bool { true } - public var message: String { bridged.CondFailInst_getMessage().string } + public var message: StringRef { StringRef(bridged: bridged.CondFailInst_getMessage()) } } final public class HopToExecutorInst : Instruction, UnaryInstruction {} @@ -478,7 +477,7 @@ final public class LoadUnownedInst : SingleValueInstruction, LoadInstruction {} final public class LoadBorrowInst : SingleValueInstruction, LoadInstruction {} final public class BuiltinInst : SingleValueInstruction { - public typealias ID = swift.BuiltinValueKind + public typealias ID = BridgedInstruction.BuiltinValueKind public var id: ID { return bridged.BuiltinInst_getID() @@ -622,11 +621,16 @@ final public class AllocGlobalInst : Instruction { } final public class IntegerLiteralInst : SingleValueInstruction { - public var value: llvm.APInt { bridged.IntegerLiteralInst_getValue() } + public var value: Int? { + let optionalInt = bridged.IntegerLiteralInst_getValue() + if optionalInt.hasValue { + return optionalInt.value + } + return nil + } } final public class FloatLiteralInst : SingleValueInstruction { - public var value: llvm.APFloat { bridged.FloatLiteralInst_getValue() } } final public class StringLiteralInst : SingleValueInstruction { @@ -789,7 +793,7 @@ final public class BridgeObjectToRefInst : SingleValueInstruction, final public class BridgeObjectToWordInst : SingleValueInstruction, ConversionInstruction {} -public typealias AccessKind = swift.SILAccessKind +public typealias AccessKind = BridgedInstruction.AccessKind // TODO: add support for begin_unpaired_access @@ -890,7 +894,7 @@ final public class ApplyInst : SingleValueInstruction, FullApplySite { public var isNonThrowing: Bool { bridged.ApplyInst_getNonThrowing() } public var isNonAsync: Bool { bridged.ApplyInst_getNonAsync() } - public typealias SpecializationInfo = UnsafePointer? + public typealias SpecializationInfo = BridgedGenericSpecializationInformation public var specializationInfo: SpecializationInfo { bridged.ApplyInst_getSpecializationInfo() } } diff --git a/SwiftCompilerSources/Sources/SIL/Location.swift b/SwiftCompilerSources/Sources/SIL/Location.swift index 6940eb5b130eb..7b2553e053f73 100644 --- a/SwiftCompilerSources/Sources/SIL/Location.swift +++ b/SwiftCompilerSources/Sources/SIL/Location.swift @@ -13,11 +13,10 @@ import SILBridging public struct Location: Equatable, CustomStringConvertible { - let bridged: swift.SILDebugLocation + let bridged: BridgedLocation public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } /// Keeps the debug scope but marks it as auto-generated. @@ -39,6 +38,6 @@ public struct Location: Equatable, CustomStringConvertible { } public static var artificialUnreachableLocation: Location { - Location(bridged: swift.SILDebugLocation.getArtificialUnreachableLocation()) + Location(bridged: BridgedLocation.getArtificialUnreachableLocation()) } } diff --git a/SwiftCompilerSources/Sources/SIL/Registration.swift b/SwiftCompilerSources/Sources/SIL/Registration.swift index f83b7f50f9c22..4ef4b55897d61 100644 --- a/SwiftCompilerSources/Sources/SIL/Registration.swift +++ b/SwiftCompilerSources/Sources/SIL/Registration.swift @@ -14,7 +14,7 @@ import Basic import SILBridging private func register(_ cl: T.Type) { - String(describing: cl)._withStringRef { nameStr in + String(describing: cl)._withBridgedStringRef { nameStr in let metatype = unsafeBitCast(cl, to: SwiftMetatype.self) registerBridgedClass(nameStr, metatype) } diff --git a/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift b/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift index f618f31b8ffaf..4d62f6c081b18 100644 --- a/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift +++ b/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift @@ -13,17 +13,17 @@ import SILBridging public struct SubstitutionMap { - public let bridged: swift.SubstitutionMap + public let bridged: BridgedSubstitutionMap - public init(_ bridged: swift.SubstitutionMap) { + public init(_ bridged: BridgedSubstitutionMap) { self.bridged = bridged } public init() { - self.bridged = swift.SubstitutionMap() + self.bridged = BridgedSubstitutionMap() } - public var isEmpty: Bool { bridged.empty() } + public var isEmpty: Bool { bridged.isEmpty() } public var replacementTypes: OptionalTypeArray { let types = BridgedTypeArray.fromReplacementTypes(bridged) diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index 1af31b3285add..7e34db5d69404 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -14,8 +14,8 @@ import Basic import SILBridging public struct Type : CustomStringConvertible, NoReflectionChildren { - public let bridged: swift.SILType - + public let bridged: BridgedType + public var isAddress: Bool { bridged.isAddress() } public var isObject: Bool { !isAddress } @@ -23,12 +23,12 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { public var objectType: Type { bridged.getObjectType().type } public func isTrivial(in function: Function) -> Bool { - return bridged.isTrivial(function.bridged.getFunction()) + return bridged.isTrivial(function.bridged) } /// Returns true if the type is a trivial type and is and does not contain a Builtin.RawPointer. public func isTrivialNonPointer(in function: Function) -> Bool { - return !bridged.isNonTrivialOrContainsRawPointer(function.bridged.getFunction()) + return !bridged.isNonTrivialOrContainsRawPointer(function.bridged) } /// True if this type is a value type (struct/enum) that requires deinitialization beyond @@ -36,11 +36,11 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { public var isValueTypeWithDeinit: Bool { bridged.isValueTypeWithDeinit() } public func isLoadable(in function: Function) -> Bool { - return bridged.isLoadable(function.bridged.getFunction()) + return bridged.isLoadable(function.bridged) } public func isReferenceCounted(in function: Function) -> Bool { - return bridged.isReferenceCounted(function.bridged.getFunction()) + return bridged.isReferenceCounted(function.bridged) } public var isUnownedStorageType: Bool { @@ -49,23 +49,23 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { public var hasArchetype: Bool { bridged.hasArchetype() } - public var isNominal: Bool { bridged.getNominalOrBoundGenericNominal() != nil } - public var isClass: Bool { bridged.getClassOrBoundGenericClass() != nil } - public var isStruct: Bool { bridged.getStructOrBoundGenericStruct() != nil } + public var isNominal: Bool { bridged.isNominalOrBoundGenericNominal() } + public var isClass: Bool { bridged.isClassOrBoundGenericClass() } + public var isStruct: Bool { bridged.isStructOrBoundGenericStruct() } public var isTuple: Bool { bridged.isTuple() } - public var isEnum: Bool { bridged.getEnumOrBoundGenericEnum() != nil } + public var isEnum: Bool { bridged.isEnumOrBoundGenericEnum() } public var isFunction: Bool { bridged.isFunction() } public var isMetatype: Bool { bridged.isMetatype() } public var isNoEscapeFunction: Bool { bridged.isNoEscapeFunction() } public var isAsyncFunction: Bool { bridged.isAsyncFunction() } - public var canBeClass: swift.TypeTraitResult { bridged.canBeClass() } + public var canBeClass: BridgedType.TraitResult { bridged.canBeClass() } public var isMoveOnly: Bool { bridged.isMoveOnly() } /// Can only be used if the type is in fact a nominal type (`isNominal` is true). public var nominal: NominalTypeDecl { - NominalTypeDecl(_bridged: BridgedNominalTypeDecl(decl: bridged.getNominalOrBoundGenericNominal())) + NominalTypeDecl(_bridged: bridged.getNominalOrBoundGenericNominal()) } public var isOrContainsObjectiveCClass: Bool { bridged.isOrContainsObjectiveCClass() } @@ -76,7 +76,7 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { public var builtinVectorElementType: Type { bridged.getBuiltinVectorElementType().type } public func isBuiltinInteger(withFixedWidth width: Int) -> Bool { - bridged.isBuiltinFixedWidthInteger(UInt32(width)) + bridged.isBuiltinFixedWidthInteger(width) } public func isExactSuperclass(of type: Type) -> Bool { @@ -89,12 +89,14 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { NominalFieldsArray(type: self, function: function) } + public typealias MetatypeRepresentation = BridgedType.MetatypeRepresentation + public func instanceTypeOfMetatype(in function: Function) -> Type { - bridged.getInstanceTypeOfMetatype(function.bridged.getFunction()).type + bridged.getInstanceTypeOfMetatype(function.bridged).type } - public func representationOfMetatype(in function: Function) -> swift.MetatypeRepresentation { - bridged.getRepresentationOfMetatype(function.bridged.getFunction()) + public func representationOfMetatype(in function: Function) -> MetatypeRepresentation { + bridged.getRepresentationOfMetatype(function.bridged) } public var isCalleeConsumedFunction: Bool { bridged.isCalleeConsumedFunction() } @@ -102,20 +104,20 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { public var isMarkedAsImmortal: Bool { bridged.isMarkedAsImmortal() } public func getIndexOfEnumCase(withName name: String) -> Int? { - let idx = name._withStringRef { + let idx = name._withBridgedStringRef { bridged.getCaseIdxOfEnumType($0) } return idx >= 0 ? idx : nil } public var description: String { - String(_cxxString: bridged.getDebugDescription()) + String(taking: bridged.getDebugDescription()) } } extension Type: Equatable { public static func ==(lhs: Type, rhs: Type) -> Bool { - lhs.bridged == rhs.bridged + lhs.bridged.opaqueValue == rhs.bridged.opaqueValue } } @@ -167,11 +169,11 @@ public struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray { public var endIndex: Int { Int(type.bridged.getNumNominalFields()) } public subscript(_ index: Int) -> Type { - type.bridged.getFieldType(index, function.bridged.getFunction()).type + type.bridged.getFieldType(index, function.bridged).type } public func getIndexOfField(withName name: String) -> Int? { - let idx = name._withStringRef { + let idx = name._withBridgedStringRef { type.bridged.getFieldIdxOfNominalType($0) } return idx >= 0 ? idx : nil @@ -193,7 +195,7 @@ public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { } } -extension swift.SILType { +extension BridgedType { var type: Type { Type(bridged: self) } var typeOrNil: Type? { isNull() ? nil : type } } diff --git a/SwiftCompilerSources/Sources/SIL/VTable.swift b/SwiftCompilerSources/Sources/SIL/VTable.swift index 95a6da9d9d4ff..42e37b219d7d0 100644 --- a/SwiftCompilerSources/Sources/SIL/VTable.swift +++ b/SwiftCompilerSources/Sources/SIL/VTable.swift @@ -23,8 +23,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { public var function: Function { bridged.getImplementation().function } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } } @@ -37,7 +36,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { public subscript(_ index: Int) -> Entry { assert(index >= startIndex && index < endIndex) - return Entry(bridged: BridgedVTableEntry(entry: base.entry + index)) + return Entry(bridged: base.advanceBy(index)) } } @@ -47,7 +46,6 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } } diff --git a/SwiftCompilerSources/Sources/SIL/Value.swift b/SwiftCompilerSources/Sources/SIL/Value.swift index b87399caf402b..9328f140ae3b2 100644 --- a/SwiftCompilerSources/Sources/SIL/Value.swift +++ b/SwiftCompilerSources/Sources/SIL/Value.swift @@ -99,8 +99,7 @@ public enum Ownership { extension Value { public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } public var uses: UseList { UseList(bridged.getFirstUse()) } diff --git a/SwiftCompilerSources/Sources/SIL/WitnessTable.swift b/SwiftCompilerSources/Sources/SIL/WitnessTable.swift index 4b4698f7618d4..f58277fb4208f 100644 --- a/SwiftCompilerSources/Sources/SIL/WitnessTable.swift +++ b/SwiftCompilerSources/Sources/SIL/WitnessTable.swift @@ -20,8 +20,8 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { public struct Entry : CustomStringConvertible, NoReflectionChildren { fileprivate let bridged: BridgedWitnessTableEntry - public typealias Kind = swift.SILWitnessTable.WitnessKind - + public typealias Kind = BridgedWitnessTableEntry.Kind + public var kind: Kind { return bridged.getKind() } @@ -32,8 +32,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } } @@ -46,7 +45,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { public subscript(_ index: Int) -> Entry { assert(index >= startIndex && index < endIndex) - return Entry(bridged: BridgedWitnessTableEntry(entry: base.entry + index)) + return Entry(bridged: base.advanceBy(index)) } } @@ -56,8 +55,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } } @@ -75,8 +73,7 @@ public struct DefaultWitnessTable : CustomStringConvertible, NoReflectionChildre } public var description: String { - let stdString = bridged.getDebugDescription() - return String(_cxxString: stdString) + return String(taking: bridged.getDebugDescription()) } } diff --git a/cmake/modules/SwiftSharedCMakeConfig.cmake b/cmake/modules/SwiftSharedCMakeConfig.cmake index 6679f404db2c2..4e7a033f40e1a 100644 --- a/cmake/modules/SwiftSharedCMakeConfig.cmake +++ b/cmake/modules/SwiftSharedCMakeConfig.cmake @@ -351,6 +351,10 @@ macro(swift_common_cxx_warnings) # Disallow calls to objc_msgSend() with no function pointer cast. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOBJC_OLD_DISPATCH_PROTOTYPES=0") + + if(BRIDGING_MODE STREQUAL "PURE") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPURE_BRIDGING_MODE") + endif() endmacro() # Like 'llvm_config()', but uses libraries from the selected build diff --git a/include/module.modulemap b/include/module.modulemap index 2e421469dd1dd..78fe887a51e4c 100644 --- a/include/module.modulemap +++ b/include/module.modulemap @@ -1,7 +1,5 @@ module BasicBridging { - header "swift/Basic/BridgedSwiftObject.h" header "swift/Basic/BasicBridging.h" - header "swift/Basic/SourceLoc.h" requires cplusplus export * } @@ -11,17 +9,7 @@ module CBasicBridging { } module ASTBridging { - header "swift/AST/AnyFunctionRef.h" header "swift/AST/ASTBridging.h" - header "swift/AST/Builtins.h" - header "swift/AST/DiagnosticEngine.h" - header "swift/AST/DiagnosticConsumer.h" - header "swift/AST/ForeignAsyncConvention.h" - header "swift/AST/ForeignErrorConvention.h" - header "swift/AST/SubstitutionMap.h" - - textual header "swift/AST/Builtins.def" - requires cplusplus export * } @@ -32,7 +20,6 @@ module CASTBridging { module SILBridging { header "swift/SIL/SILBridging.h" - header "swift/SIL/SILLocation.h" requires cplusplus export * } diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index d02968cf85c34..50985bf7ee7ef 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -13,15 +13,22 @@ #ifndef SWIFT_AST_ASTBRIDGING_H #define SWIFT_AST_ASTBRIDGING_H -#include "swift/AST/DiagnosticEngine.h" +// Do not add other C++/llvm/swift header files here! +// Function implementations should be placed into ASTBridging.cpp and required header files should be added there. +// #include "swift/Basic/BasicBridging.h" -#include "swift/Basic/Compiler.h" -#include "swift/Basic/Nullability.h" -#include -#include + +#ifdef USED_IN_CPP_SOURCE +#include "swift/AST/DiagnosticConsumer.h" +#include "swift/AST/DiagnosticEngine.h" +#endif SWIFT_BEGIN_NULLABILITY_ANNOTATIONS +namespace swift { + class DiagnosticArgument; +} + //===----------------------------------------------------------------------===// // Diagnostic Engine //===----------------------------------------------------------------------===// @@ -33,24 +40,55 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagID : uint32_t { #include "swift/AST/DiagnosticsAll.def" } BridgedDiagID; -typedef struct { +struct BridgedDiagnosticEngine { void * _Nonnull object; -} BridgedDiagnosticEngine; +}; -typedef struct { +struct BridgedOptionalDiagnosticEngine { void *_Nullable object; -} BridgedOptionalDiagnosticEngine; +}; + +class BridgedDiagnosticArgument { + int64_t storage[3]; + +public: +#ifdef USED_IN_CPP_SOURCE + BridgedDiagnosticArgument(const swift::DiagnosticArgument &arg) { + *reinterpret_cast(&storage) = arg; + } + const swift::DiagnosticArgument &get() const { + return *reinterpret_cast(&storage); + } +#endif + + BridgedDiagnosticArgument(SwiftInt i); + BridgedDiagnosticArgument(BridgedStringRef s); +}; + +class BridgedDiagnosticFixIt { + int64_t storage[6]; + +public: +#ifdef USED_IN_CPP_SOURCE + BridgedDiagnosticFixIt(const swift::DiagnosticInfo::FixIt &fixit){ + *reinterpret_cast(&storage) = fixit; + } + const swift::DiagnosticInfo::FixIt &get() const { + return *reinterpret_cast(&storage); + } +#endif + + BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text); +}; // FIXME: Can we bridge InFlightDiagnostic? -void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, swift::SourceLoc loc, +void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, BridgedSourceLoc loc, BridgedDiagID diagID, BridgedArrayRef arguments, - swift::CharSourceRange highlight, + BridgedSourceLoc highlightStart, uint32_t hightlightLength, BridgedArrayRef fixIts); bool DiagnosticEngine_hadAnyError(BridgedDiagnosticEngine); -using ArrayRefOfDiagnosticArgument = llvm::ArrayRef; - SWIFT_END_NULLABILITY_ANNOTATIONS #endif // SWIFT_AST_ASTBRIDGING_H diff --git a/include/swift/Basic/BasicBridging.h b/include/swift/Basic/BasicBridging.h index f11083e83a0ec..3ef3ac83913b2 100644 --- a/include/swift/Basic/BasicBridging.h +++ b/include/swift/Basic/BasicBridging.h @@ -13,31 +13,90 @@ #ifndef SWIFT_BASIC_BASICBRIDGING_H #define SWIFT_BASIC_BASICBRIDGING_H +#if !defined(COMPILED_WITH_SWIFT) || !defined(PURE_BRIDGING_MODE) +#define USED_IN_CPP_SOURCE +#endif + +// Do not add other C++/llvm/swift header files here! +// Function implementations should be placed into BasicBridging.cpp and required header files should be added there. +// +#include "swift/Basic/BridgedSwiftObject.h" +#include "swift/Basic/Compiler.h" + +#include +#include +#ifdef USED_IN_CPP_SOURCE // Workaround to avoid a compiler error because `cas::ObjectRef` is not defined // when including VirtualFileSystem.h #include #include "llvm/CAS/CASReference.h" -#include "swift/Basic/BridgedSwiftObject.h" -#include "swift/Basic/Nullability.h" -#include "swift/Basic/SourceLoc.h" -#include +#include "llvm/ADT/StringRef.h" +#include +#endif + +#ifdef PURE_BRIDGING_MODE +// In PURE_BRIDGING_MODE, briding functions are not inlined +#define BRIDGED_INLINE +#else +#define BRIDGED_INLINE inline +#endif SWIFT_BEGIN_NULLABILITY_ANNOTATIONS typedef intptr_t SwiftInt; typedef uintptr_t SwiftUInt; -typedef struct { - const void * _Nullable data; - size_t numElements; -} BridgedArrayRef; - -typedef struct { +struct BridgedOStream { void * _Nonnull streamAddr; -} BridgedOStream; +}; -void OStream_write(BridgedOStream os, llvm::StringRef str); +class BridgedStringRef { + const char * _Nonnull data; + size_t length; + +public: +#ifdef USED_IN_CPP_SOURCE + BridgedStringRef(llvm::StringRef sref) : data(sref.data()), length(sref.size()) {} + + llvm::StringRef get() const { return llvm::StringRef(data, length); } +#endif + + BridgedStringRef(const char * _Nullable data, size_t length) + : data(data), length(length) {} + + SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { + return (const uint8_t * _Nonnull)data; + } + SwiftInt size() const { return (SwiftInt)length; } + void write(BridgedOStream os) const; +}; + +class BridgedOwnedString { + char * _Nonnull data; + size_t length; + +public: +#ifdef USED_IN_CPP_SOURCE + BridgedOwnedString(const std::string &stringToCopy); +#endif + + SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { + return (const uint8_t * _Nonnull)(data ? data : ""); + } + SwiftInt size() const { return (SwiftInt)length; } + void destroy() const; +}; + +struct BridgedSourceLoc { + const uint8_t * _Nullable opaquePointer; + bool isValid() const { return opaquePointer != nullptr; } +}; + +struct BridgedArrayRef { + const void * _Nullable data; + size_t numElements; +}; SWIFT_END_NULLABILITY_ANNOTATIONS diff --git a/include/swift/Parse/RegexParserBridging.h b/include/swift/Parse/RegexParserBridging.h index 35ea10eeadbfc..44787b06032af 100644 --- a/include/swift/Parse/RegexParserBridging.h +++ b/include/swift/Parse/RegexParserBridging.h @@ -57,7 +57,7 @@ typedef bool (*RegexLiteralParsingFn)(/*InputPtr*/ const char *_Nonnull, /*VersionOut*/ unsigned *_Nonnull, /*CaptureStructureOut*/ void *_Nonnull, /*CaptureStructureSize*/ unsigned, - /*DiagnosticBaseLoc*/ swift::SourceLoc, + /*DiagnosticBaseLoc*/ BridgedSourceLoc, BridgedDiagnosticEngine); void Parser_registerRegexLiteralParsingFn(RegexLiteralParsingFn _Nullable fn); diff --git a/include/swift/SIL/SILBridging.h b/include/swift/SIL/SILBridging.h index 118e6c96dee94..86d9100d115a4 100644 --- a/include/swift/SIL/SILBridging.h +++ b/include/swift/SIL/SILBridging.h @@ -13,25 +13,17 @@ #ifndef SWIFT_SIL_SILBRIDGING_H #define SWIFT_SIL_SILBRIDGING_H -#include "swift/AST/Builtins.h" -#include "swift/AST/Decl.h" -#include "swift/AST/SubstitutionMap.h" +// Do not add other C++/llvm/swift header files here! +// Function implementations should be placed into SILBridgingImpl.h or SILBridging.cpp and +// required header files should be added there. +// #include "swift/Basic/BasicBridging.h" -#include "swift/Basic/BridgedSwiftObject.h" -#include "swift/Basic/Nullability.h" -#include "swift/SIL/ApplySite.h" -#include "swift/SIL/InstWrappers.h" -#include "swift/SIL/SILBuilder.h" -#include "swift/SIL/SILDefaultWitnessTable.h" -#include "swift/SIL/SILFunctionConventions.h" + +#ifdef USED_IN_CPP_SOURCE +#include "llvm/ADT/ArrayRef.h" #include "swift/SIL/SILInstruction.h" -#include "swift/SIL/SILLocation.h" -#include "swift/SIL/SILModule.h" -#include "swift/SIL/SILVTable.h" #include "swift/SIL/SILWitnessTable.h" -#include -#include -#include +#endif SWIFT_BEGIN_NULLABILITY_ANNOTATIONS @@ -39,11 +31,99 @@ struct BridgedInstruction; struct OptionalBridgedInstruction; struct OptionalBridgedOperand; struct OptionalBridgedSuccessor; +struct BridgedFunction; struct BridgedBasicBlock; struct BridgedSuccessorArray; struct OptionalBridgedBasicBlock; +struct BridgedNominalTypeDecl; + +namespace swift { +class ValueBase; +class Operand; +class SILFunction; +class SILBasicBlock; +class SILSuccessor; +class SILGlobalVariable; +class SILInstruction; +class SILArgument; +class MultipleValueInstructionResult; +class SILVTableEntry; +class SILVTable; +class SILWitnessTable; +class SILDefaultWitnessTable; +class NominalTypeDecl; +class SwiftPassInvocation; +class GenericSpecializationInformation; +} + +void registerBridgedClass(BridgedStringRef className, SwiftMetatype metatype); + +struct BridgedType { + void * _Nullable opaqueValue; + + enum class MetatypeRepresentation { + Thin, + Thick, + ObjC + }; + + enum class TraitResult { + IsNot, + CanBe, + Is + }; + +#ifdef USED_IN_CPP_SOURCE + BridgedType(swift::SILType t) : opaqueValue(t.getOpaqueValue()) {} + + swift::SILType get() const { + return swift::SILType::getFromOpaqueValue(opaqueValue); + } +#endif -void registerBridgedClass(llvm::StringRef className, SwiftMetatype metatype); + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOwnedString getDebugDescription() const; + BRIDGED_INLINE bool isNull() const; + BRIDGED_INLINE bool isAddress() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getAddressType() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getObjectType() const; + BRIDGED_INLINE bool isTrivial(BridgedFunction f) const; + BRIDGED_INLINE bool isNonTrivialOrContainsRawPointer(BridgedFunction f) const; + BRIDGED_INLINE bool isValueTypeWithDeinit() const; + BRIDGED_INLINE bool isLoadable(BridgedFunction f) const; + BRIDGED_INLINE bool isReferenceCounted(BridgedFunction f) const; + BRIDGED_INLINE bool isUnownedStorageType() const; + BRIDGED_INLINE bool hasArchetype() const; + BRIDGED_INLINE bool isNominalOrBoundGenericNominal() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getNominalOrBoundGenericNominal() const; + BRIDGED_INLINE bool isClassOrBoundGenericClass() const; + BRIDGED_INLINE bool isStructOrBoundGenericStruct() const; + BRIDGED_INLINE bool isTuple() const; + BRIDGED_INLINE bool isEnumOrBoundGenericEnum() const; + BRIDGED_INLINE bool isFunction() const; + BRIDGED_INLINE bool isMetatype() const; + BRIDGED_INLINE bool isNoEscapeFunction() const; + BRIDGED_INLINE bool isAsyncFunction() const; + BRIDGED_INLINE TraitResult canBeClass() const; + BRIDGED_INLINE bool isMoveOnly() const; + BRIDGED_INLINE bool isOrContainsObjectiveCClass() const; + BRIDGED_INLINE bool isBuiltinInteger() const; + BRIDGED_INLINE bool isBuiltinFloat() const; + BRIDGED_INLINE bool isBuiltinVector() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getBuiltinVectorElementType() const; + BRIDGED_INLINE bool isBuiltinFixedWidthInteger(SwiftInt width) const; + BRIDGED_INLINE bool isExactSuperclassOf(BridgedType t) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getInstanceTypeOfMetatype(BridgedFunction f) const; + BRIDGED_INLINE MetatypeRepresentation getRepresentationOfMetatype(BridgedFunction f) const; + BRIDGED_INLINE bool isCalleeConsumedFunction() const; + BRIDGED_INLINE bool isMarkedAsImmortal() const; + BRIDGED_INLINE SwiftInt getCaseIdxOfEnumType(BridgedStringRef name) const; + BRIDGED_INLINE SwiftInt getNumNominalFields() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getFieldType(SwiftInt idx, BridgedFunction f) const; + BRIDGED_INLINE SwiftInt getFieldIdxOfNominalType(BridgedStringRef name) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getFieldName(SwiftInt idx) const; + BRIDGED_INLINE SwiftInt getNumTupleElements() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getTupleElementType(SwiftInt idx) const; +}; struct BridgedValue { SwiftObject obj; @@ -64,53 +144,31 @@ struct BridgedValue { None }; - Kind getKind() const; - - swift::SILValue getSILValue() const { return static_cast(obj); } - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedOperand getFirstUse() const; - - SWIFT_IMPORT_UNSAFE - swift::SILType getType() const { return getSILValue()->getType(); } - - static Ownership castOwnership(swift::OwnershipKind ownership) { +#ifdef USED_IN_CPP_SOURCE + static swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { switch (ownership) { - case swift::OwnershipKind::Any: - llvm_unreachable("Invalid ownership for value"); - case swift::OwnershipKind::Unowned: return Ownership::Unowned; - case swift::OwnershipKind::Owned: return Ownership::Owned; - case swift::OwnershipKind::Guaranteed: return Ownership::Guaranteed; - case swift::OwnershipKind::None: return Ownership::None; + case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; + case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; + case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; + case BridgedValue::Ownership::None: return swift::OwnershipKind::None; } } +#endif - Ownership getOwnership() const { - return castOwnership(getSILValue()->getOwnershipKind()); - } + Kind getKind() const; + BRIDGED_INLINE swift::ValueBase * _Nonnull getSILValue() const; + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getFirstUse() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getType() const; + BRIDGED_INLINE Ownership getOwnership() const; }; struct OptionalBridgedValue { OptionalSwiftObject obj; - swift::SILValue getSILValue() const { - if (obj) - return static_cast(obj); - return swift::SILValue(); - } + BRIDGED_INLINE swift::ValueBase * _Nullable getSILValue() const; }; -inline swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { - switch (ownership) { - case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; - case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; - case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; - case BridgedValue::Ownership::None: return swift::OwnershipKind::None; - } -} - // This is the layout of a class existential. struct BridgeValueExistential { BridgedValue value; @@ -121,7 +179,9 @@ struct BridgedValueArray { const BridgeValueExistential * _Nullable base; size_t count; +#ifdef USED_IN_CPP_SOURCE llvm::ArrayRef getValues(llvm::SmallVectorImpl &storage); +#endif }; struct BridgedOperand { @@ -144,62 +204,23 @@ struct BridgedOperand { Reborrow }; - bool isTypeDependent() const { return op->isTypeDependent(); } - - bool isLifetimeEnding() const { return op->isLifetimeEnding(); } - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedOperand getNextUse() const; - - SWIFT_IMPORT_UNSAFE - BridgedValue getValue() const { return {op->get()}; } - - SWIFT_IMPORT_UNSAFE - inline BridgedInstruction getUser() const; - - OperandOwnership getOperandOwnership() const { - switch (op->getOperandOwnership()) { - case swift::OperandOwnership::NonUse: - return OperandOwnership::NonUse; - case swift::OperandOwnership::TrivialUse: - return OperandOwnership::TrivialUse; - case swift::OperandOwnership::InstantaneousUse: - return OperandOwnership::InstantaneousUse; - case swift::OperandOwnership::UnownedInstantaneousUse: - return OperandOwnership::UnownedInstantaneousUse; - case swift::OperandOwnership::ForwardingUnowned: - return OperandOwnership::ForwardingUnowned; - case swift::OperandOwnership::PointerEscape: - return OperandOwnership::PointerEscape; - case swift::OperandOwnership::BitwiseEscape: - return OperandOwnership::BitwiseEscape; - case swift::OperandOwnership::Borrow: - return OperandOwnership::Borrow; - case swift::OperandOwnership::DestroyingConsume: - return OperandOwnership::DestroyingConsume; - case swift::OperandOwnership::ForwardingConsume: - return OperandOwnership::ForwardingConsume; - case swift::OperandOwnership::InteriorPointer: - return OperandOwnership::InteriorPointer; - case swift::OperandOwnership::GuaranteedForwarding: - return OperandOwnership::GuaranteedForwarding; - case swift::OperandOwnership::EndBorrow: - return OperandOwnership::EndBorrow; - case swift::OperandOwnership::Reborrow: - return OperandOwnership::Reborrow; - } - } + BRIDGED_INLINE bool isTypeDependent() const; + BRIDGED_INLINE bool isLifetimeEnding() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getNextUse() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getValue() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getUser() const; + BRIDGED_INLINE OperandOwnership getOperandOwnership() const; }; struct OptionalBridgedOperand { swift::Operand * _Nullable op; // Assumes that `op` is not null. - SWIFT_IMPORT_UNSAFE - BridgedOperand advancedBy(SwiftInt index) const { return {op + index}; } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE + BridgedOperand advancedBy(SwiftInt index) const; // Assumes that `op` is not null. - SwiftInt distanceTo(BridgedOperand element) const { return element.op - op; } + BRIDGED_INLINE SwiftInt distanceTo(BridgedOperand element) const; }; struct BridgedOperandArray { @@ -211,160 +232,82 @@ struct BridgedOperandArray { // Currently it's not possible to switch over `SILArgumentConvention::ConventionType`, // because it's not a class enum. enum class BridgedArgumentConvention { - Indirect_In = swift::SILArgumentConvention::Indirect_In, - Indirect_In_Guaranteed = swift::SILArgumentConvention::Indirect_In_Guaranteed, - Indirect_Inout = swift::SILArgumentConvention::Indirect_Inout, - Indirect_InoutAliasable = swift::SILArgumentConvention::Indirect_InoutAliasable, - Indirect_Out = swift::SILArgumentConvention::Indirect_Out, - Direct_Owned = swift::SILArgumentConvention::Direct_Owned, - Direct_Unowned = swift::SILArgumentConvention::Direct_Unowned, - Direct_Guaranteed = swift::SILArgumentConvention::Direct_Guaranteed, - Pack_Owned = swift::SILArgumentConvention::Pack_Owned, - Pack_Inout = swift::SILArgumentConvention::Pack_Inout, - Pack_Guaranteed = swift::SILArgumentConvention::Pack_Guaranteed, - Pack_Out = swift::SILArgumentConvention::Pack_Out + Indirect_In, + Indirect_In_Guaranteed, + Indirect_Inout, + Indirect_InoutAliasable, + Indirect_Out, + Direct_Owned, + Direct_Unowned, + Direct_Guaranteed, + Pack_Owned, + Pack_Inout, + Pack_Guaranteed, + Pack_Out +}; + +enum class BridgedMemoryBehavior { + None, + MayRead, + MayWrite, + MayReadWrite, + MayHaveSideEffects }; -inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { - return static_cast(convention.Value); -} - struct BridgedFunction { SwiftObject obj; - SWIFT_IMPORT_UNSAFE - swift::SILFunction * _Nonnull getFunction() const { - return static_cast(obj); - } - - SWIFT_IMPORT_UNSAFE - llvm::StringRef getName() const { return getFunction()->getName(); } - - std::string getDebugDescription() const; - - bool hasOwnership() const { return getFunction()->hasOwnership(); } - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedBasicBlock getFirstBlock() const; - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedBasicBlock getLastBlock() const; - - SwiftInt getNumIndirectFormalResults() const { - return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); - } - - SwiftInt getNumParameters() const { - return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); - } - - SwiftInt getSelfArgumentIndex() const { - swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); - swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); - if (!fTy->hasSelfParam()) - return -1; - return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; - } - - SwiftInt getNumSILArguments() const { - return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); - } - - swift::SILType getSILArgumentType(SwiftInt idx) const { - swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); - return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); - } - - BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const { - swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); - return castToArgumentConvention(conv.getSILArgumentConvention(idx)); - } - - swift::SILType getSILResultType() const { - swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); - return conv.getSILResultType(getFunction()->getTypeExpansionContext()); - } - - bool isSwift51RuntimeAvailable() const { - if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) - return false; - - swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); - return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); - } - - bool isPossiblyUsedExternally() const { - return getFunction()->isPossiblyUsedExternally(); - } - - bool isAvailableExternally() const { - return getFunction()->isAvailableExternally(); - } - - bool isTransparent() const { - return getFunction()->isTransparent() == swift::IsTransparent; - } - - bool isAsync() const { - return getFunction()->isAsync(); - } - - bool isGlobalInitFunction() const { - return getFunction()->isGlobalInit(); - } - - bool isGlobalInitOnceFunction() const { - return getFunction()->isGlobalInitOnceFunction(); - } - - bool isDestructor() const { - if (auto *declCtxt = getFunction()->getDeclContext()) { - return llvm::isa(declCtxt); - } - return false; - } - - bool isGenericFunction() const { - return !getFunction()->getGenericSignature().isNull(); - } - - bool hasSemanticsAttr(llvm::StringRef attrName) const { - return getFunction()->hasSemanticsAttr(attrName); - } - - swift::EffectsKind getEffectAttribute() const { - return getFunction()->getEffectsKind(); - } + enum class EffectsKind { + ReadNone, + ReadOnly, + ReleaseNone, + ReadWrite, + Unspecified, + Custom + }; - swift::PerformanceConstraints getPerformanceConstraints() const { - return getFunction()->getPerfConstraints(); - } + enum class PerformanceConstraints { + None = 0, + NoAllocation = 1, + NoLocks = 2 + }; enum class InlineStrategy { - InlineDefault = swift::InlineDefault, - NoInline = swift::NoInline, - AlwaysInline = swift::AlwaysInline + InlineDefault, + NoInline, + AlwaysInline }; - InlineStrategy getInlineStrategy() const { - return (InlineStrategy)getFunction()->getInlineStrategy(); - } - - bool isSerialized() const { - return getFunction()->isSerialized(); - } - - bool hasValidLinkageForFragileRef() const { - return getFunction()->hasValidLinkageForFragileRef(); - } - - bool needsStackProtection() const { - return getFunction()->needsStackProtection(); - } - - void setNeedStackProtection(bool needSP) const { - getFunction()->setNeedStackProtection(needSP); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILFunction * _Nonnull getFunction() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + BRIDGED_INLINE bool hasOwnership() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getFirstBlock() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getLastBlock() const; + BRIDGED_INLINE SwiftInt getNumIndirectFormalResults() const; + BRIDGED_INLINE SwiftInt getNumParameters() const; + BRIDGED_INLINE SwiftInt getSelfArgumentIndex() const; + BRIDGED_INLINE SwiftInt getNumSILArguments() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILArgumentType(SwiftInt idx) const; + BRIDGED_INLINE BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILResultType() const; + BRIDGED_INLINE bool isSwift51RuntimeAvailable() const; + BRIDGED_INLINE bool isPossiblyUsedExternally() const; + BRIDGED_INLINE bool isAvailableExternally() const; + BRIDGED_INLINE bool isTransparent() const; + BRIDGED_INLINE bool isAsync() const; + BRIDGED_INLINE bool isGlobalInitFunction() const; + BRIDGED_INLINE bool isGlobalInitOnceFunction() const; + BRIDGED_INLINE bool isDestructor() const; + BRIDGED_INLINE bool isGenericFunction() const; + BRIDGED_INLINE bool hasSemanticsAttr(BridgedStringRef attrName) const; + BRIDGED_INLINE EffectsKind getEffectAttribute() const; + BRIDGED_INLINE PerformanceConstraints getPerformanceConstraints() const; + BRIDGED_INLINE InlineStrategy getInlineStrategy() const; + BRIDGED_INLINE bool isSerialized() const; + BRIDGED_INLINE bool hasValidLinkageForFragileRef() const; + BRIDGED_INLINE bool needsStackProtection() const; + BRIDGED_INLINE void setNeedStackProtection(bool needSP) const; enum class ParseEffectsMode { argumentEffectsFromSource, @@ -388,12 +331,12 @@ struct BridgedFunction { typedef void (* _Nonnull RegisterFn)(BridgedFunction f, void * _Nonnull data, SwiftInt size); typedef void (* _Nonnull WriteFn)(BridgedFunction, BridgedOStream, SwiftInt); typedef ParsingError (*_Nonnull ParseFn)(BridgedFunction, - llvm::StringRef, + BridgedStringRef, ParseEffectsMode, SwiftInt, BridgedArrayRef); typedef SwiftInt (* _Nonnull CopyEffectsFn)(BridgedFunction, BridgedFunction); typedef EffectInfo (* _Nonnull GetEffectInfoFn)(BridgedFunction, SwiftInt); - typedef swift::MemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); + typedef BridgedMemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); static void registerBridging(SwiftMetatype metatype, RegisterFn initFn, RegisterFn destroyFn, @@ -411,34 +354,15 @@ struct BridgedGlobalVar { SwiftObject obj; BridgedGlobalVar(SwiftObject obj) : obj(obj) {} - - SWIFT_IMPORT_UNSAFE - swift::SILGlobalVariable * _Nonnull getGlobal() const { - return static_cast(obj); - } - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - llvm::StringRef getName() const { return getGlobal()->getName(); } - - bool isLet() const { return getGlobal()->isLet(); } - - void setLet(bool value) const { getGlobal()->setLet(value); } - - bool isPossiblyUsedExternally() const { - return getGlobal()->isPossiblyUsedExternally(); - } - - bool isAvailableExternally() const { - return swift::isAvailableExternally(getGlobal()->getLinkage()); - } - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedInstruction getFirstStaticInitInst() const; - + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILGlobalVariable * _Nonnull getGlobal() const; + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; + BRIDGED_INLINE bool isLet() const; + BRIDGED_INLINE void setLet(bool value) const; + BRIDGED_INLINE bool isPossiblyUsedExternally() const; + BRIDGED_INLINE bool isAvailableExternally() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstStaticInitInst() const; bool canBeInitializedStatically() const; - bool mustBeInitializedStatically() const; }; @@ -449,136 +373,105 @@ struct OptionalBridgedGlobalVar { struct BridgedMultiValueResult { SwiftObject obj; - swift::MultipleValueInstructionResult * _Nonnull getMVResult() const { +#ifdef USED_IN_CPP_SOURCE + swift::MultipleValueInstructionResult * _Nonnull get() const { return static_cast(obj); } +#endif - SWIFT_IMPORT_UNSAFE - inline BridgedInstruction getParent() const; - - SwiftInt getIndex() const { - return (SwiftInt)getMVResult()->getIndex(); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getParent() const; + BRIDGED_INLINE SwiftInt getIndex() const; }; -struct OptionalBridgedInstruction { - OptionalSwiftObject obj; - - OptionalBridgedInstruction() : obj(nullptr) {} - - OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} +struct BridgedSubstitutionMap { + uint64_t storage[1]; - swift::SILInstruction * _Nullable getInst() const { - if (!obj) - return nullptr; - return llvm::cast(static_cast(obj)->castToInstruction()); +#ifdef USED_IN_CPP_SOURCE + BridgedSubstitutionMap(swift::SubstitutionMap map) { + *reinterpret_cast(&storage) = map; } + swift::SubstitutionMap get() const { + return *reinterpret_cast(&storage); + } +#endif + + BRIDGED_INLINE BridgedSubstitutionMap(); + BRIDGED_INLINE bool isEmpty() const; }; struct BridgedTypeArray { - llvm::ArrayRef typeArray; + BridgedArrayRef typeArray; - SWIFT_IMPORT_UNSAFE - static BridgedTypeArray fromReplacementTypes(swift::SubstitutionMap substMap) { - return {substMap.getReplacementTypes()}; - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE + static BridgedTypeArray fromReplacementTypes(BridgedSubstitutionMap substMap); - SwiftInt getCount() const { return SwiftInt(typeArray.size()); } + SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } - SWIFT_IMPORT_UNSAFE - swift::SILType getAt(SwiftInt index) const { - auto ty = typeArray[index]->getCanonicalType(); - if (ty->isLegalSILType()) - return swift::SILType::getPrimitiveObjectType(ty); - return swift::SILType(); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE + BridgedType getAt(SwiftInt index) const; }; struct BridgedSILTypeArray { - llvm::ArrayRef typeArray; + BridgedArrayRef typeArray; - SwiftInt getCount() const { return SwiftInt(typeArray.size()); } + SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } - SWIFT_IMPORT_UNSAFE - swift::SILType getAt(SwiftInt index) const { return typeArray[index]; } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE + BridgedType getAt(SwiftInt index) const; }; -struct BridgedInstruction { - SwiftObject obj; - - BridgedInstruction(SwiftObject obj) : obj(obj) {} - - template I *_Nonnull getAs() const { - return llvm::cast(static_cast(obj)->castToInstruction()); - } - - swift::SILInstruction * _Nonnull getInst() const { return getAs(); } - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - OptionalBridgedInstruction getNext() const { - auto iter = std::next(getInst()->getIterator()); - if (iter == getInst()->getParent()->end()) - return {nullptr}; - return {iter->asSILNode()}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedInstruction getPrevious() const { - auto iter = std::next(getInst()->getReverseIterator()); - if (iter == getInst()->getParent()->rend()) - return {nullptr}; - return {iter->asSILNode()}; - } - - SWIFT_IMPORT_UNSAFE - inline BridgedBasicBlock getParent() const; +struct BridgedLocation { + uint64_t storage[3]; - SWIFT_IMPORT_UNSAFE - inline BridgedInstruction getLastInstOfParent() const; - - bool isDeleted() const { - return getInst()->isDeleted(); - } - - SWIFT_IMPORT_UNSAFE - BridgedOperandArray getOperands() const { - auto operands = getInst()->getAllOperands(); - return {{operands.data()}, (SwiftInt)operands.size()}; - } - - SWIFT_IMPORT_UNSAFE - BridgedOperandArray getTypeDependentOperands() const { - auto typeOperands = getInst()->getTypeDependentOperands(); - return {{typeOperands.data()}, (SwiftInt)typeOperands.size()}; +#ifdef USED_IN_CPP_SOURCE + BridgedLocation(const swift::SILDebugLocation &loc) { + *reinterpret_cast(&storage) = loc; } - - void setOperand(SwiftInt index, BridgedValue value) const { - getInst()->setOperand((unsigned)index, value.getSILValue()); + const swift::SILDebugLocation &getLoc() const { + return *reinterpret_cast(&storage); } +#endif - SWIFT_IMPORT_UNSAFE - swift::SILDebugLocation getLocation() const { - return getInst()->getDebugLocation(); - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getAutogeneratedLocation() const; + BRIDGED_INLINE bool hasValidLineNumber() const; + BRIDGED_INLINE bool isAutoGenerated() const; + BRIDGED_INLINE bool isEqualTo(BridgedLocation rhs) const; + BRIDGED_INLINE bool hasSameSourceLocation(BridgedLocation rhs) const; + static BRIDGED_INLINE BridgedLocation getArtificialUnreachableLocation(); +}; - swift::MemoryBehavior getMemBehavior() const { - return getInst()->getMemoryBehavior(); - } +struct BridgedGenericSpecializationInformation { + const swift::GenericSpecializationInformation * _Nullable data = nullptr; +}; - bool mayRelease() const { - return getInst()->mayRelease(); - } +struct BridgedInstruction { + SwiftObject obj; - bool mayHaveSideEffects() const { - return getInst()->mayHaveSideEffects(); +#ifdef USED_IN_CPP_SOURCE + template I *_Nonnull getAs() const { + return llvm::cast(static_cast(obj)->castToInstruction()); } - - bool maySuspend() const { - return getInst()->maySuspend(); + swift::SILInstruction * _Nonnull get() const { + return getAs(); } +#endif + BridgedInstruction(SwiftObject obj) : obj(obj) {} + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getNext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getPrevious() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getLastInstOfParent() const; + BRIDGED_INLINE bool isDeleted() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getOperands() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getTypeDependentOperands() const; + BRIDGED_INLINE void setOperand(SwiftInt index, BridgedValue value) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; + BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior() const; + BRIDGED_INLINE bool mayRelease() const; + BRIDGED_INLINE bool mayHaveSideEffects() const; + BRIDGED_INLINE bool maySuspend() const; bool mayAccessPointer() const; bool mayLoadWeakOrUnowned() const; bool maySynchronizeNotConsideringSideEffects() const; @@ -588,570 +481,257 @@ struct BridgedInstruction { // Generalized instruction subclasses // =========================================================================// - SwiftInt MultipleValueInstruction_getNumResults() const { - return getAs()->getNumResults(); - } - - SWIFT_IMPORT_UNSAFE - BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const { - return {getAs()->getResult(index)}; - } - - SWIFT_IMPORT_UNSAFE - inline BridgedSuccessorArray TermInst_getSuccessors() const; + BRIDGED_INLINE SwiftInt MultipleValueInstruction_getNumResults() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessorArray TermInst_getSuccessors() const; // =========================================================================// // Instruction protocols // =========================================================================// - OptionalBridgedOperand ForwardingInst_singleForwardedOperand() const { - return {swift::ForwardingOperation(getInst()).getSingleForwardingOperand()}; - } - - BridgedOperandArray ForwardingInst_forwardedOperands() const { - auto operands = - swift::ForwardingOperation(getInst()).getForwardedOperands(); - return {{operands.data()}, (SwiftInt)operands.size()}; - } - - BridgedValue::Ownership ForwardingInst_forwardingOwnership() const { - auto *forwardingInst = swift::ForwardingInstruction::get(getInst()); - return - BridgedValue::castOwnership(forwardingInst->getForwardingOwnershipKind()); - } - - bool ForwardingInst_preservesOwnership() const { - return swift::ForwardingInstruction::get(getInst())->preservesOwnership(); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand ForwardingInst_singleForwardedOperand() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray ForwardingInst_forwardedOperands() const; + BRIDGED_INLINE BridgedValue::Ownership ForwardingInst_forwardingOwnership() const; + BRIDGED_INLINE bool ForwardingInst_preservesOwnership() const; // =========================================================================// // Specific instruction subclasses // =========================================================================// - SWIFT_IMPORT_UNSAFE - llvm::StringRef CondFailInst_getMessage() const { - return getAs()->getMessage(); - } - - SwiftInt LoadInst_getLoadOwnership() const { - return (SwiftInt)getAs()->getOwnershipQualifier(); - } - - swift::BuiltinValueKind BuiltinInst_getID() const { - return getAs()->getBuiltinInfo().ID; - } + enum class BuiltinValueKind { + None = 0, +#define BUILTIN(Id, Name, Attrs) Id, +#include "swift/AST/Builtins.def" + }; enum class IntrinsicID { memcpy, memmove, unknown }; - IntrinsicID BuiltinInst_getIntrinsicID() const { - switch (getAs()->getIntrinsicInfo().ID) { - case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; - case llvm::Intrinsic::memmove: return IntrinsicID::memmove; - default: return IntrinsicID::unknown; - } - } + struct OptionalInt { + SwiftInt value; + bool hasValue; + }; - SWIFT_IMPORT_UNSAFE - swift::SubstitutionMap BuiltinInst_getSubstitutionMap() const { - return getAs()->getSubstitutions(); - } + enum class AccessKind { + Init, + Read, + Modify, + Deinit + }; - bool PointerToAddressInst_isStrict() const { - return getAs()->isStrict(); - } + struct KeyPathFunctionResults { + enum { maxFunctions = 5 }; + BridgedFunction functions[maxFunctions]; + SwiftInt numFunctions; + }; - bool AddressToPointerInst_needsStackProtection() const { - return getAs()->needsStackProtection(); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef CondFailInst_getMessage() const; + BRIDGED_INLINE SwiftInt LoadInst_getLoadOwnership() const ; + BRIDGED_INLINE BuiltinValueKind BuiltinInst_getID() const; + BRIDGED_INLINE IntrinsicID BuiltinInst_getIntrinsicID() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap BuiltinInst_getSubstitutionMap() const; + BRIDGED_INLINE bool PointerToAddressInst_isStrict() const; + BRIDGED_INLINE bool AddressToPointerInst_needsStackProtection() const; + BRIDGED_INLINE bool IndexAddrInst_needsStackProtection() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar GlobalAccessInst_getGlobal() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar AllocGlobalInst_getGlobal() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction FunctionRefBaseInst_getReferencedFunction() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalInt IntegerLiteralInst_getValue() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef StringLiteralInst_getValue() const; + BRIDGED_INLINE int StringLiteralInst_getEncoding() const; + BRIDGED_INLINE SwiftInt TupleExtractInst_fieldIndex() const; + BRIDGED_INLINE SwiftInt TupleElementAddrInst_fieldIndex() const; + BRIDGED_INLINE SwiftInt StructExtractInst_fieldIndex() const; + BRIDGED_INLINE OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const; + BRIDGED_INLINE SwiftInt StructElementAddrInst_fieldIndex() const; + BRIDGED_INLINE SwiftInt ProjectBoxInst_fieldIndex() const; + BRIDGED_INLINE bool EndCOWMutationInst_doKeepUnique() const; + BRIDGED_INLINE SwiftInt EnumInst_caseIndex() const; + BRIDGED_INLINE SwiftInt UncheckedEnumDataInst_caseIndex() const; + BRIDGED_INLINE SwiftInt InitEnumDataAddrInst_caseIndex() const; + BRIDGED_INLINE SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const; + BRIDGED_INLINE SwiftInt InjectEnumAddrInst_caseIndex() const; + BRIDGED_INLINE SwiftInt RefElementAddrInst_fieldIndex() const; + BRIDGED_INLINE bool RefElementAddrInst_fieldIsLet() const; + BRIDGED_INLINE bool RefElementAddrInst_isImmutable() const; + BRIDGED_INLINE void RefElementAddrInst_setImmutable(bool isImmutable) const; + BRIDGED_INLINE SwiftInt PartialApplyInst_numArguments() const; + BRIDGED_INLINE SwiftInt ApplyInst_numArguments() const; + BRIDGED_INLINE bool ApplyInst_getNonThrowing() const; + BRIDGED_INLINE bool ApplyInst_getNonAsync() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSpecializationInformation ApplyInst_getSpecializationInfo() const; + BRIDGED_INLINE SwiftInt ObjectInst_getNumBaseElements() const; + BRIDGED_INLINE SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const; + BRIDGED_INLINE bool PartialApplyInst_isOnStack() const; + BRIDGED_INLINE bool AllocStackInst_hasDynamicLifetime() const; + BRIDGED_INLINE bool AllocRefInstBase_isObjc() const; + BRIDGED_INLINE bool AllocRefInstBase_canAllocOnStack() const; + BRIDGED_INLINE SwiftInt AllocRefInstBase_getNumTailTypes() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const; + BRIDGED_INLINE bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const; + BRIDGED_INLINE SwiftInt BeginApplyInst_numArguments() const; + BRIDGED_INLINE SwiftInt TryApplyInst_numArguments() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock BranchInst_getTargetBlock() const; + BRIDGED_INLINE SwiftInt SwitchEnumInst_getNumCases() const; + BRIDGED_INLINE SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const; + BRIDGED_INLINE SwiftInt StoreInst_getStoreOwnership() const; + BRIDGED_INLINE SwiftInt AssignInst_getAssignOwnership() const; + BRIDGED_INLINE AccessKind BeginAccessInst_getAccessKind() const; + BRIDGED_INLINE bool BeginAccessInst_isStatic() const; + BRIDGED_INLINE bool CopyAddrInst_isTakeOfSrc() const; + BRIDGED_INLINE bool CopyAddrInst_isInitializationOfDest() const; + BRIDGED_INLINE SwiftInt MarkUninitializedInst_getKind() const; + BRIDGED_INLINE void RefCountingInst_setIsAtomic(bool isAtomic) const; + BRIDGED_INLINE bool RefCountingInst_getIsAtomic() const; + BRIDGED_INLINE SwiftInt CondBranchInst_getNumTrueArgs() const; + BRIDGED_INLINE void AllocRefInstBase_setIsStackAllocatable() const; + BRIDGED_INLINE bool AllocRefInst_isBare() const; + BRIDGED_INLINE void AllocRefInst_setIsBare() const; + BRIDGED_INLINE void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; + BRIDGED_INLINE SwiftInt KeyPathInst_getNumComponents() const; + BRIDGED_INLINE void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const; + BRIDGED_INLINE bool GlobalValueInst_isBare() const; + BRIDGED_INLINE void GlobalValueInst_setIsBare() const; + BRIDGED_INLINE void LoadInst_setOwnership(SwiftInt ownership) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap ApplySite_getSubstitutionMap() const; + BRIDGED_INLINE BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const; + BRIDGED_INLINE SwiftInt ApplySite_getNumArguments() const; + BRIDGED_INLINE SwiftInt FullApplySite_numIndirectResultArguments() const; +}; - bool IndexAddrInst_needsStackProtection() const { - return getAs()->needsStackProtection(); - } +struct OptionalBridgedInstruction { + OptionalSwiftObject obj; - SWIFT_IMPORT_UNSAFE - BridgedGlobalVar GlobalAccessInst_getGlobal() const { - return {getAs()->getReferencedGlobal()}; +#ifdef USED_IN_CPP_SOURCE + swift::SILInstruction * _Nullable get() const { + if (!obj) + return nullptr; + return llvm::cast(static_cast(obj)->castToInstruction()); } +#endif - SWIFT_IMPORT_UNSAFE - BridgedGlobalVar AllocGlobalInst_getGlobal() const { - return {getAs()->getReferencedGlobal()}; - } + OptionalBridgedInstruction() : obj(nullptr) {} + OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} +}; - SWIFT_IMPORT_UNSAFE - BridgedFunction FunctionRefBaseInst_getReferencedFunction() const { - return {getAs()->getInitiallyReferencedFunction()}; - } +struct BridgedArgument { + SwiftObject obj; - SWIFT_IMPORT_UNSAFE - llvm::APInt IntegerLiteralInst_getValue() const { - return getAs()->getValue(); - } + BRIDGED_INLINE swift::SILArgument * _Nonnull getArgument() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; + BRIDGED_INLINE BridgedArgumentConvention getConvention() const; + BRIDGED_INLINE bool isSelf() const; +}; - SWIFT_IMPORT_UNSAFE - llvm::APFloat FloatLiteralInst_getValue() const { - return getAs()->getValue(); - } +struct OptionalBridgedArgument { + OptionalSwiftObject obj; +}; - SWIFT_IMPORT_UNSAFE - llvm::StringRef StringLiteralInst_getValue() const { - return getAs()->getValue(); - } +struct OptionalBridgedBasicBlock { + OptionalSwiftObject obj; - int StringLiteralInst_getEncoding() const { - return (int)getAs()->getEncoding(); +#ifdef USED_IN_CPP_SOURCE + swift::SILBasicBlock * _Nullable get() const { + return obj ? static_cast(obj) : nullptr; } +#endif +}; - SwiftInt TupleExtractInst_fieldIndex() const { - return getAs()->getFieldIndex(); - } +struct BridgedBasicBlock { + SwiftObject obj; - SwiftInt TupleElementAddrInst_fieldIndex() const { - return getAs()->getFieldIndex(); + BridgedBasicBlock(SwiftObject obj) : obj(obj) { } - SwiftInt StructExtractInst_fieldIndex() const { - return getAs()->getFieldIndex(); +#ifdef USED_IN_CPP_SOURCE + BridgedBasicBlock(swift::SILBasicBlock * _Nonnull block) : obj(block) { } - - OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const { - return {getAs()->getUniqueNonTrivialFieldValue()}; + swift::SILBasicBlock * _Nonnull get() const { + return static_cast(obj); } +#endif - SwiftInt StructElementAddrInst_fieldIndex() const { - return getAs()->getFieldIndex(); - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getNext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getPrevious() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstInst() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getLastInst() const; + BRIDGED_INLINE SwiftInt getNumArguments() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument getArgument(SwiftInt index) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const; + BRIDGED_INLINE void eraseArgument(SwiftInt index) const; + BRIDGED_INLINE void moveAllInstructionsToBegin(BridgedBasicBlock dest) const; + BRIDGED_INLINE void moveAllInstructionsToEnd(BridgedBasicBlock dest) const; + BRIDGED_INLINE void moveArgumentsTo(BridgedBasicBlock dest) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getFirstPred() const; +}; - SwiftInt ProjectBoxInst_fieldIndex() const { - return getAs()->getFieldIndex(); - } +struct BridgedSuccessor { + const swift::SILSuccessor * _Nonnull succ; - bool EndCOWMutationInst_doKeepUnique() const { - return getAs()->doKeepUnique(); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getNext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getTargetBlock() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getContainingInst() const; +}; - SwiftInt EnumInst_caseIndex() const { - return getAs()->getCaseIndex(); - } +struct OptionalBridgedSuccessor { + const swift::SILSuccessor * _Nullable succ; - SwiftInt UncheckedEnumDataInst_caseIndex() const { - return getAs()->getCaseIndex(); - } + // Assumes that `succ` is not null. + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessor advancedBy(SwiftInt index) const; +}; - SwiftInt InitEnumDataAddrInst_caseIndex() const { - return getAs()->getCaseIndex(); - } +struct BridgedSuccessorArray { + OptionalBridgedSuccessor base; + SwiftInt count; +}; - SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const { - return getAs()->getCaseIndex(); - } +struct BridgedVTableEntry { + const swift::SILVTableEntry * _Nonnull entry; - SwiftInt InjectEnumAddrInst_caseIndex() const { - return getAs()->getCaseIndex(); - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getImplementation() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntry advanceBy(SwiftInt index) const; +}; - SwiftInt RefElementAddrInst_fieldIndex() const { - return getAs()->getFieldIndex(); - } +struct BridgedVTableEntryArray { + BridgedVTableEntry base; + SwiftInt count; +}; - bool RefElementAddrInst_fieldIsLet() const { - return getAs()->getField()->isLet(); - } +struct BridgedVTable { + const swift::SILVTable * _Nonnull vTable; - bool RefElementAddrInst_isImmutable() const { - return getAs()->isImmutable(); - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntryArray getEntries() const; +}; - void RefElementAddrInst_setImmutable(bool isImmutable) const { - getAs()->setImmutable(isImmutable); - } +struct BridgedWitnessTableEntry { + const void * _Nonnull entry; - SwiftInt PartialApplyInst_numArguments() const { - return getAs()->getNumArguments(); - } + enum class Kind { + Invalid, + Method, + AssociatedType, + AssociatedTypeProtocol, + BaseProtocol + }; - SwiftInt ApplyInst_numArguments() const { - return getAs()->getNumArguments(); +#ifdef USED_IN_CPP_SOURCE + const swift::SILWitnessTable::Entry * _Nonnull getEntry() const { + return (const swift::SILWitnessTable::Entry * _Nonnull)entry; } +#endif - bool ApplyInst_getNonThrowing() const { - return getAs()->isNonThrowing(); - } - - bool ApplyInst_getNonAsync() const { - return getAs()->isNonAsync(); - } - - const swift::GenericSpecializationInformation * _Nullable - - SWIFT_IMPORT_UNSAFE - ApplyInst_getSpecializationInfo() const { - return getAs()->getSpecializationInfo(); - } - - SwiftInt ObjectInst_getNumBaseElements() const { - return getAs()->getNumBaseElements(); - } - - SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { - return swift::ApplySite(getInst()).getCalleeArgIndexOfFirstAppliedArg(); - } - - bool PartialApplyInst_isOnStack() const { - return getAs()->isOnStack(); - } - - bool AllocStackInst_hasDynamicLifetime() const { - return getAs()->hasDynamicLifetime(); - } - - bool AllocRefInstBase_isObjc() const { - return getAs()->isObjC(); - } - - bool AllocRefInstBase_canAllocOnStack() const { - return getAs()->canAllocOnStack(); - } - - SwiftInt AllocRefInstBase_getNumTailTypes() const { - return getAs()->getNumTailTypes(); - } - - SWIFT_IMPORT_UNSAFE - BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const { - return {getAs()->getTailAllocatedTypes()}; - } - - bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { - return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); - } - - SwiftInt BeginApplyInst_numArguments() const { - return getAs()->getNumArguments(); - } - - SwiftInt TryApplyInst_numArguments() const { - return getAs()->getNumArguments(); - } - - SWIFT_IMPORT_UNSAFE - inline BridgedBasicBlock BranchInst_getTargetBlock() const; - - SwiftInt SwitchEnumInst_getNumCases() const { - return getAs()->getNumCases(); - } - - SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const { - auto *seInst = getAs(); - return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); - } - - SwiftInt StoreInst_getStoreOwnership() const { - return (SwiftInt)getAs()->getOwnershipQualifier(); - } - - SwiftInt AssignInst_getAssignOwnership() const { - return (SwiftInt)getAs()->getOwnershipQualifier(); - } - - swift::SILAccessKind BeginAccessInst_getAccessKind() const { - return getAs()->getAccessKind(); - } - - bool BeginAccessInst_isStatic() const { - return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; - } - - bool CopyAddrInst_isTakeOfSrc() const { - return getAs()->isTakeOfSrc(); - } - - bool CopyAddrInst_isInitializationOfDest() const { - return getAs()->isInitializationOfDest(); - } - - SwiftInt MarkUninitializedInst_getKind() const { - return (SwiftInt)getAs()->getMarkUninitializedKind(); - } - - void RefCountingInst_setIsAtomic(bool isAtomic) const { - getAs()->setAtomicity( - isAtomic ? swift::RefCountingInst::Atomicity::Atomic - : swift::RefCountingInst::Atomicity::NonAtomic); - } - - bool RefCountingInst_getIsAtomic() const { - return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; - } - - SwiftInt CondBranchInst_getNumTrueArgs() const { - return getAs()->getNumTrueArgs(); - } - - void AllocRefInstBase_setIsStackAllocatable() const { - getAs()->setStackAllocatable(); - } - - bool AllocRefInst_isBare() const { - return getAs()->isBare(); - } - - void AllocRefInst_setIsBare() const { - getAs()->setBare(true); - } - - inline void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; - - SwiftInt KeyPathInst_getNumComponents() const { - if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { - return (SwiftInt)pattern->getComponents().size(); - } - return 0; - } - - struct KeyPathFunctionResults { - enum { maxFunctions = 5 }; - BridgedFunction functions[maxFunctions]; - SwiftInt numFunctions; - }; - - void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const { - swift::KeyPathPattern *pattern = getAs()->getPattern(); - const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; - results->numFunctions = 0; - - comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { - assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); - results->functions[results->numFunctions++] = {func}; - }, [](swift::SILDeclRef) {}); - } - - bool GlobalValueInst_isBare() const { - return getAs()->isBare(); - } - - void GlobalValueInst_setIsBare() const { - getAs()->setBare(true); - } - - void LoadInst_setOwnership(SwiftInt ownership) const { - getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); - } - - SWIFT_IMPORT_UNSAFE - inline BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; - - SWIFT_IMPORT_UNSAFE - inline BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; - - SWIFT_IMPORT_UNSAFE - swift::SubstitutionMap ApplySite_getSubstitutionMap() const { - auto as = swift::ApplySite(getInst()); - return as.getSubstitutionMap(); - } - - BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { - auto as = swift::ApplySite(getInst()); - auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); - return castToArgumentConvention(conv.Value); - } - - SwiftInt ApplySite_getNumArguments() const { - return swift::ApplySite(getInst()).getNumArguments(); - } - - SwiftInt FullApplySite_numIndirectResultArguments() const { - auto fas = swift::FullApplySite(getInst()); - return fas.getNumIndirectSILResults(); - } -}; - -struct BridgedArgument { - SwiftObject obj; - - swift::SILArgument * _Nonnull getArgument() const { - return static_cast(obj); - } - - SWIFT_IMPORT_UNSAFE - inline BridgedBasicBlock getParent() const; - - BridgedArgumentConvention getConvention() const { - auto *fArg = llvm::cast(getArgument()); - return castToArgumentConvention(fArg->getArgumentConvention()); - } - - bool isSelf() const { - auto *fArg = llvm::cast(getArgument()); - return fArg->isSelf(); - } -}; - -struct OptionalBridgedArgument { - OptionalSwiftObject obj; -}; - -struct OptionalBridgedBasicBlock { - OptionalSwiftObject obj; - - swift::SILBasicBlock * _Nullable getBlock() const { - return obj ? static_cast(obj) : nullptr; - } -}; - -struct BridgedBasicBlock { - SwiftObject obj; - - BridgedBasicBlock(SwiftObject obj) : obj(obj) {} - - swift::SILBasicBlock * _Nonnull getBlock() const { - return static_cast(obj); - } - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - OptionalBridgedBasicBlock getNext() const { - auto iter = std::next(getBlock()->getIterator()); - if (iter == getBlock()->getParent()->end()) - return {nullptr}; - return {&*iter}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedBasicBlock getPrevious() const { - auto iter = std::next(getBlock()->getReverseIterator()); - if (iter == getBlock()->getParent()->rend()) - return {nullptr}; - return {&*iter}; - } - - SWIFT_IMPORT_UNSAFE - BridgedFunction getFunction() const { - return {getBlock()->getParent()}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedInstruction getFirstInst() const { - if (getBlock()->empty()) - return {nullptr}; - return {getBlock()->front().asSILNode()}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedInstruction getLastInst() const { - if (getBlock()->empty()) - return {nullptr}; - return {getBlock()->back().asSILNode()}; - } - - SwiftInt getNumArguments() const { - return getBlock()->getNumArguments(); - } - - SWIFT_IMPORT_UNSAFE - BridgedArgument getArgument(SwiftInt index) const { - return {getBlock()->getArgument(index)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedArgument addBlockArgument(swift::SILType type, BridgedValue::Ownership ownership) const { - return {getBlock()->createPhiArgument(type, castToOwnership(ownership))}; - } - - void eraseArgument(SwiftInt index) const { - getBlock()->eraseArgument(index); - } - - void moveAllInstructionsToBegin(BridgedBasicBlock dest) const { - dest.getBlock()->spliceAtBegin(getBlock()); - } - - void moveAllInstructionsToEnd(BridgedBasicBlock dest) const { - dest.getBlock()->spliceAtEnd(getBlock()); - } - - void moveArgumentsTo(BridgedBasicBlock dest) const { - dest.getBlock()->moveArgumentList(getBlock()); - } - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedSuccessor getFirstPred() const; -}; - -struct BridgedSuccessor { - const swift::SILSuccessor * _Nonnull succ; - - SWIFT_IMPORT_UNSAFE - inline OptionalBridgedSuccessor getNext() const; - - SWIFT_IMPORT_UNSAFE - BridgedBasicBlock getTargetBlock() const { - return {succ->getBB()}; - } - - SWIFT_IMPORT_UNSAFE - inline BridgedInstruction getContainingInst() const; -}; - -struct OptionalBridgedSuccessor { - const swift::SILSuccessor * _Nullable succ; - - // Assumes that `succ` is not null. - SWIFT_IMPORT_UNSAFE - BridgedSuccessor advancedBy(SwiftInt index) const { return {succ + index}; } -}; - -struct BridgedSuccessorArray { - OptionalBridgedSuccessor base; - SwiftInt count; -}; - -struct BridgedVTableEntry { - const swift::SILVTableEntry * _Nonnull entry; - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - BridgedFunction getImplementation() const { - return {entry->getImplementation()}; - } -}; - -struct BridgedVTableEntryArray { - BridgedVTableEntry base; - SwiftInt count; -}; - -struct BridgedVTable { - const swift::SILVTable * _Nonnull vTable; - - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - BridgedVTableEntryArray getEntries() const { - auto entries = vTable->getEntries(); - return {{entries.data()}, (SwiftInt)entries.size()}; - } -}; - -struct BridgedWitnessTableEntry { - const swift::SILWitnessTable::Entry * _Nonnull entry; - - SWIFT_IMPORT_UNSAFE - std::string getDebugDescription() const; - - swift::SILWitnessTable::WitnessKind getKind() const { - return entry->getKind(); - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedFunction getMethodFunction() const { - return {entry->getMethodWitness().Witness}; - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + BRIDGED_INLINE Kind getKind() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getMethodFunction() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntry advanceBy(SwiftInt index) const; }; struct BridgedWitnessTableEntryArray { @@ -1162,13 +742,8 @@ struct BridgedWitnessTableEntryArray { struct BridgedWitnessTable { const swift::SILWitnessTable * _Nonnull table; - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - BridgedWitnessTableEntryArray getEntries() const { - auto entries = table->getEntries(); - return {{entries.data()}, (SwiftInt)entries.size()}; - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; }; struct OptionalBridgedWitnessTable { @@ -1178,13 +753,8 @@ struct OptionalBridgedWitnessTable { struct BridgedDefaultWitnessTable { const swift::SILDefaultWitnessTable * _Nonnull table; - std::string getDebugDescription() const; - - SWIFT_IMPORT_UNSAFE - BridgedWitnessTableEntryArray getEntries() const { - auto entries = table->getEntries(); - return {{entries.data()}, (SwiftInt)entries.size()}; - } + SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; }; struct OptionalBridgedDefaultWitnessTable { @@ -1198,306 +768,79 @@ struct BridgedBuilder{ } insertAt; SwiftObject insertionObj; - swift::SILDebugLocation loc; - - swift::SILBuilder builder() const { - switch (insertAt) { - case InsertAt::beforeInst: - return swift::SILBuilder(BridgedInstruction(insertionObj).getInst(), loc.getScope()); - case InsertAt::endOfBlock: - return swift::SILBuilder(BridgedBasicBlock(insertionObj).getBlock(), loc.getScope()); - case InsertAt::intoGlobal: - return swift::SILBuilder(BridgedGlobalVar(insertionObj).getGlobal()); - } - } - - swift::SILLocation regularLoc() const { return swift::RegularLocation(loc.getLocation()); } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createBuiltinBinaryFunction(llvm::StringRef name, - swift::SILType operandType, swift::SILType resultType, - BridgedValueArray arguments) const { - llvm::SmallVector argValues; - return {builder().createBuiltinBinaryFunction(regularLoc(), - name, operandType, resultType, - arguments.getValues(argValues))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createCondFail(BridgedValue condition, llvm::StringRef message) const { - return {builder().createCondFail(regularLoc(), condition.getSILValue(), message)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createIntegerLiteral(swift::SILType type, SwiftInt value) const { - return {builder().createIntegerLiteral(regularLoc(), type, value)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createAllocStack(swift::SILType type, - bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { - return {builder().createAllocStack(regularLoc(), type, llvm::None, hasDynamicLifetime, isLexical, wasMoved)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDeallocStack(BridgedValue operand) const { - return {builder().createDeallocStack(regularLoc(), operand.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDeallocStackRef(BridgedValue operand) const { - return {builder().createDeallocStackRef(regularLoc(), operand.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUncheckedRefCast(BridgedValue op, swift::SILType type) const { - return {builder().createUncheckedRefCast(regularLoc(), op.getSILValue(), type)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUpcast(BridgedValue op, swift::SILType type) const { - return {builder().createUpcast(regularLoc(), op.getSILValue(), type)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const { - return {builder().createLoad(regularLoc(), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createBeginDeallocRef(BridgedValue reference, BridgedValue allocation) const { - return {builder().createBeginDeallocRef(regularLoc(), reference.getSILValue(), allocation.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createEndInitLetRef(BridgedValue op) const { - return {builder().createEndInitLetRef(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStrongRetain(BridgedValue op) const { - auto b = builder(); - return {b.createStrongRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStrongRelease(BridgedValue op) const { - auto b = builder(); - return {b.createStrongRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUnownedRetain(BridgedValue op) const { - auto b = builder(); - return {b.createUnownedRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUnownedRelease(BridgedValue op) const { - auto b = builder(); - return {b.createUnownedRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createFunctionRef(BridgedFunction function) const { - return {builder().createFunctionRef(regularLoc(), function.getFunction())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createCopyValue(BridgedValue op) const { - return {builder().createCopyValue(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createBeginBorrow(BridgedValue op) const { - return {builder().createBeginBorrow(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createEndBorrow(BridgedValue op) const { - return {builder().createEndBorrow(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, - bool takeSource, bool initializeDest) const { - return {builder().createCopyAddr(regularLoc(), - from.getSILValue(), to.getSILValue(), - swift::IsTake_t(takeSource), - swift::IsInitialization_t(initializeDest))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDestroyValue(BridgedValue op) const { - return {builder().createDestroyValue(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDestroyAddr(BridgedValue op) const { - return {builder().createDestroyAddr(regularLoc(), op.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDebugStep() const { - return {builder().createDebugStep(regularLoc())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createApply(BridgedValue function, swift::SubstitutionMap subMap, - BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, - const swift::GenericSpecializationInformation * _Nullable specInfo) const { - llvm::SmallVector argValues; - swift::ApplyOptions applyOpts; - if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } - if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } - - return {builder().createApply(regularLoc(), - function.getSILValue(), subMap, - arguments.getValues(argValues), - applyOpts, specInfo)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, - const void * _Nullable enumCases, SwiftInt numEnumCases) const { - using BridgedCase = const std::pair; - llvm::ArrayRef cases(static_cast(enumCases), - (unsigned)numEnumCases); - llvm::SmallDenseMap mappedElements; - swift::SILValue en = enumVal.getSILValue(); - swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); - for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { - mappedElements[elemWithIndex.index()] = elemWithIndex.value(); - } - llvm::SmallVector, 16> convertedCases; - for (auto c : cases) { - assert(mappedElements.count(c.first) && "wrong enum element index"); - convertedCases.push_back({mappedElements[c.first], c.second.getBlock()}); - } - return {builder().createSwitchEnum(regularLoc(), - enumVal.getSILValue(), - defaultBlock.getBlock(), convertedCases)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, - swift::SILType resultType) const { - swift::SILValue en = enumVal.getSILValue(); - return {builder().createUncheckedEnumData(regularLoc(), enumVal.getSILValue(), - en->getType().getEnumElement(caseIdx), resultType)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, - swift::SILType resultType) const { - swift::EnumElementDecl *caseDecl = resultType.getEnumElement(caseIdx); - swift::SILValue pl = payload.getSILValue(); - return {builder().createEnum(regularLoc(), pl, caseDecl, resultType)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { - llvm::SmallVector argValues; - return {builder().createBranch(regularLoc(), destBlock.getBlock(), arguments.getValues(argValues))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createUnreachable() const { - return {builder().createUnreachable(regularLoc())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createObject(swift::SILType type, BridgedValueArray arguments, SwiftInt numBaseElements) const { - llvm::SmallVector argValues; - return {builder().createObject(swift::ArtificialUnreachableLocation(), - type, arguments.getValues(argValues), numBaseElements)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const { - return {builder().createGlobalAddr(regularLoc(), global.getGlobal())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createGlobalValue(BridgedGlobalVar global, bool isBare) const { - return {builder().createGlobalValue(regularLoc(), global.getGlobal(), isBare)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStruct(swift::SILType type, BridgedValueArray elements) const { - llvm::SmallVector elementValues; - return {builder().createStruct(regularLoc(), type, elements.getValues(elementValues))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { - swift::SILValue v = str.getSILValue(); - return {builder().createStructExtract(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { - swift::SILValue v = addr.getSILValue(); - return {builder().createStructElementAddr(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDestructureStruct(BridgedValue str) const { - return {builder().createDestructureStruct(regularLoc(), str.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createTuple(swift::SILType type, BridgedValueArray elements) const { - llvm::SmallVector elementValues; - return {builder().createTuple(regularLoc(), type, elements.getValues(elementValues))}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { - swift::SILValue v = str.getSILValue(); - return {builder().createTupleExtract(regularLoc(), v, elementIndex)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { - swift::SILValue v = addr.getSILValue(); - return {builder().createTupleElementAddr(regularLoc(), v, elementIndex)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createDestructureTuple(BridgedValue str) const { - return {builder().createDestructureTuple(regularLoc(), str.getSILValue())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createStore(BridgedValue src, BridgedValue dst, - SwiftInt ownership) const { - return {builder().createStore(regularLoc(), src.getSILValue(), dst.getSILValue(), - (swift::StoreOwnershipQualifier)ownership)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createInitExistentialRef(BridgedValue instance, - swift::SILType type, - BridgedInstruction useConformancesOf) const { - auto *src = useConformancesOf.getAs(); - return {builder().createInitExistentialRef(regularLoc(), type, - src->getFormalConcreteType(), - instance.getSILValue(), - src->getConformances())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createMetatype(swift::SILType type, swift::MetatypeRepresentation representation) const { - swift::MetatypeType *mt = swift::MetatypeType::get(type.getASTType(), representation); - swift::SILType t = swift::SILType::getPrimitiveObjectType(swift::CanType(mt)); - return {builder().createMetatype(regularLoc(), t)}; - } - - SWIFT_IMPORT_UNSAFE - BridgedInstruction createEndCOWMutation(BridgedValue instance, bool keepUnique) const { - return {builder().createEndCOWMutation(regularLoc(), instance.getSILValue(), keepUnique)}; - } + BridgedLocation loc; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBuiltinBinaryFunction(BridgedStringRef name, + BridgedType operandType, BridgedType resultType, + BridgedValueArray arguments) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCondFail(BridgedValue condition, + BridgedStringRef message) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createIntegerLiteral(BridgedType type, SwiftInt value) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createAllocStack(BridgedType type, + bool hasDynamicLifetime, bool isLexical, bool wasMoved) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStack(BridgedValue operand) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStackRef(BridgedValue operand) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedRefCast(BridgedValue op, + BridgedType type) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUpcast(BridgedValue op, BridgedType type) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginDeallocRef(BridgedValue reference, + BridgedValue allocation) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndInitLetRef(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRetain(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRelease(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRetain(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRelease(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createFunctionRef(BridgedFunction function) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyValue(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginBorrow(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndBorrow(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, + bool takeSource, bool initializeDest) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyValue(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyAddr(BridgedValue op) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDebugStep() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createApply(BridgedValue function, + BridgedSubstitutionMap subMap, + BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, + BridgedGenericSpecializationInformation specInfo) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, + OptionalBridgedBasicBlock defaultBlock, + const void * _Nullable enumCases, SwiftInt numEnumCases) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, + SwiftInt caseIdx, BridgedType resultType) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, + BridgedType resultType) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBranch(BridgedBasicBlock destBlock, + BridgedValueArray arguments) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnreachable() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createObject(BridgedType type, BridgedValueArray arguments, + SwiftInt numBaseElements) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalValue(BridgedGlobalVar global, + bool isBare) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStruct(BridgedType type, + BridgedValueArray elements) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructExtract(BridgedValue str, + SwiftInt fieldIndex) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructElementAddr(BridgedValue addr, + SwiftInt fieldIndex) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureStruct(BridgedValue str) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTuple(BridgedType type, + BridgedValueArray elements) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleExtract(BridgedValue str, + SwiftInt elementIndex) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleElementAddr(BridgedValue addr, + SwiftInt elementIndex) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureTuple(BridgedValue str) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStore(BridgedValue src, BridgedValue dst, + SwiftInt ownership) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createInitExistentialRef(BridgedValue instance, + BridgedType type, + BridgedInstruction useConformancesOf) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createMetatype(BridgedType type, + BridgedType::MetatypeRepresentation representation) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndCOWMutation(BridgedValue instance, + bool keepUnique) const; }; // AST bridging @@ -1505,22 +848,11 @@ struct BridgedBuilder{ struct BridgedNominalTypeDecl { swift::NominalTypeDecl * _Nonnull decl; - SWIFT_IMPORT_UNSAFE - llvm::StringRef getName() const { - return decl->getName().str(); - } - + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; bool isStructWithUnreferenceableStorage() const; - - bool isGlobalActor() const { return decl->isGlobalActor(); } + BRIDGED_INLINE bool isGlobalActor() const; }; -// Passmanager and Context - -namespace swift { - class SwiftPassInvocation; -} - struct BridgedChangeNotificationHandler { swift::SwiftPassInvocation * _Nonnull invocation; @@ -1534,89 +866,6 @@ struct BridgedChangeNotificationHandler { void notifyChanges(Kind changeKind) const; }; -//===----------------------------------------------------------------------===// -// Inline functions -//===----------------------------------------------------------------------===// - -OptionalBridgedOperand BridgedOperand::getNextUse() const { - return {op->getNextUse()}; -} - -BridgedInstruction BridgedOperand::getUser() const { - return {op->getUser()->asSILNode()}; -} - -OptionalBridgedOperand BridgedValue::getFirstUse() const { - return {*getSILValue()->use_begin()}; -} - -OptionalBridgedSuccessor BridgedSuccessor::getNext() const { - return {succ->getNext()}; -} - -BridgedInstruction BridgedSuccessor::getContainingInst() const { - return {succ->getContainingInst()}; -} - -OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { - return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; -} - -OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { - return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; -} - -OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { - if (getGlobal()->begin() == getGlobal()->end()) { - return {nullptr}; - } - swift::SILInstruction *firstInst = &*getGlobal()->begin(); - return {firstInst->asSILNode()}; -} - -BridgedInstruction BridgedMultiValueResult::getParent() const { - return {getMVResult()->getParent()}; -} - -BridgedBasicBlock BridgedInstruction::getParent() const { - assert(!getInst()->isStaticInitializerInst() && - "cannot get the parent of a static initializer instruction"); - return {getInst()->getParent()}; -} - -inline BridgedInstruction BridgedInstruction::getLastInstOfParent() const { - return {getInst()->getParent()->back().asSILNode()}; -} - -BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { - auto successors = getAs()->getSuccessors(); - return {{successors.data()}, (SwiftInt)successors.size()}; -} - -BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { - return {getAs()->getDestBB()}; -} - -void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { - getAs()->replaceBranchTarget(from.getBlock(), to.getBlock()); -} - -BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { - return {getAs()->getSuccessBB()}; -} - -inline BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { - return {getAs()->getFailureBB()}; -} - -OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { - return {getBlock()->pred_begin().getSuccessorRef()}; -} - -BridgedBasicBlock BridgedArgument::getParent() const { - return {getArgument()->getParent()}; -} - namespace swift::test { struct Arguments; class FunctionTest; @@ -1630,31 +879,15 @@ struct BridgedTestArguments { swift::test::Arguments *_Nonnull arguments; bool hasUntaken() const; - - SWIFT_IMPORT_UNSAFE - llvm::StringRef takeString() const; - + SWIFT_IMPORT_UNSAFE BridgedStringRef takeString() const; bool takeBool() const; - SwiftInt takeInt() const; - - SWIFT_IMPORT_UNSAFE - BridgedOperand takeOperand() const; - - SWIFT_IMPORT_UNSAFE - BridgedValue takeValue() const; - - SWIFT_IMPORT_UNSAFE - BridgedInstruction takeInstruction() const; - - SWIFT_IMPORT_UNSAFE - BridgedArgument takeArgument() const; - - SWIFT_IMPORT_UNSAFE - BridgedBasicBlock takeBlock() const; - - SWIFT_IMPORT_UNSAFE - BridgedFunction takeFunction() const; + SWIFT_IMPORT_UNSAFE BridgedOperand takeOperand() const; + SWIFT_IMPORT_UNSAFE BridgedValue takeValue() const; + SWIFT_IMPORT_UNSAFE BridgedInstruction takeInstruction() const; + SWIFT_IMPORT_UNSAFE BridgedArgument takeArgument() const; + SWIFT_IMPORT_UNSAFE BridgedBasicBlock takeBlock() const; + SWIFT_IMPORT_UNSAFE BridgedFunction takeFunction() const; }; struct BridgedSwiftPassInvocation { @@ -1667,9 +900,16 @@ using SwiftNativeFunctionTestThunk = void registerFunctionTestThunk(SwiftNativeFunctionTestThunk); -void registerFunctionTest(llvm::StringRef, +void registerFunctionTest(BridgedStringRef, void *_Nonnull nativeSwiftInvocation); +void writeCharToStderr(int c); + SWIFT_END_NULLABILITY_ANNOTATIONS +#ifndef PURE_BRIDGING_MODE +// In _not_ PURE_BRIDGING_MODE, briding functions are inlined and therefore inluded in the header file. +#include "SILBridgingImpl.h" +#endif + #endif diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h new file mode 100644 index 0000000000000..19e72e1cfd72f --- /dev/null +++ b/include/swift/SIL/SILBridgingImpl.h @@ -0,0 +1,1402 @@ +//===--- SILBridgingImpl.h ------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file contains the implementation of bridging functions, which are either +// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or +// in the header file. +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_SIL_SILBRIDGING_IMPL_H +#define SWIFT_SIL_SILBRIDGING_IMPL_H + +#include "swift/AST/Builtins.h" +#include "swift/AST/Decl.h" +#include "swift/AST/SubstitutionMap.h" +#include "swift/Basic/BasicBridging.h" +#include "swift/Basic/Nullability.h" +#include "swift/SIL/ApplySite.h" +#include "swift/SIL/InstWrappers.h" +#include "swift/SIL/SILBuilder.h" +#include "swift/SIL/SILDefaultWitnessTable.h" +#include "swift/SIL/SILFunctionConventions.h" +#include "swift/SIL/SILInstruction.h" +#include "swift/SIL/SILLocation.h" +#include "swift/SIL/SILModule.h" +#include "swift/SIL/SILVTable.h" +#include "swift/SIL/SILWitnessTable.h" +#include +#include +#include + +SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + +//===----------------------------------------------------------------------===// +// BridgedType +//===----------------------------------------------------------------------===// + +BridgedOwnedString BridgedType::getDebugDescription() const { + return BridgedOwnedString(get().getDebugDescription()); +} + +bool BridgedType::isNull() const { + return get().isNull(); +} + +bool BridgedType::isAddress() const { + return get().isAddress(); +} + +BridgedType BridgedType::getAddressType() const { + return get().getAddressType(); +} + +BridgedType BridgedType::getObjectType() const { + return get().getObjectType(); +} + +bool BridgedType::isTrivial(BridgedFunction f) const { + return get().isTrivial(f.getFunction()); +} + +bool BridgedType::isNonTrivialOrContainsRawPointer(BridgedFunction f) const { + return get().isNonTrivialOrContainsRawPointer(f.getFunction()); +} + +bool BridgedType::isValueTypeWithDeinit() const { + return get().isValueTypeWithDeinit(); +} + +bool BridgedType::isLoadable(BridgedFunction f) const { + return get().isLoadable(f.getFunction()); +} + +bool BridgedType::isReferenceCounted(BridgedFunction f) const { + return get().isReferenceCounted(f.getFunction()); +} + +bool BridgedType::isUnownedStorageType() const { + return get().isUnownedStorageType(); +} + +bool BridgedType::hasArchetype() const { + return get().hasArchetype(); +} + +bool BridgedType::isNominalOrBoundGenericNominal() const { + return get().getNominalOrBoundGenericNominal() != nullptr; +} + +BridgedNominalTypeDecl BridgedType::getNominalOrBoundGenericNominal() const { + return {get().getNominalOrBoundGenericNominal()}; +} + +bool BridgedType::isClassOrBoundGenericClass() const { + return get().getClassOrBoundGenericClass() != 0; +} + +bool BridgedType::isStructOrBoundGenericStruct() const { + return get().getStructOrBoundGenericStruct() != nullptr; +} + +bool BridgedType::isTuple() const { + return get().isTuple(); +} + +bool BridgedType::isEnumOrBoundGenericEnum() const { + return get().getEnumOrBoundGenericEnum() != nullptr; +} + +bool BridgedType::isFunction() const { + return get().isFunction(); +} + +bool BridgedType::isMetatype() const { + return get().isMetatype(); +} + +bool BridgedType::isNoEscapeFunction() const { + return get().isNoEscapeFunction(); +} + +bool BridgedType::isAsyncFunction() const { + return get().isAsyncFunction(); +} + +BridgedType::TraitResult BridgedType::canBeClass() const { + return (TraitResult)get().canBeClass(); +} + +bool BridgedType::isMoveOnly() const { + return get().isMoveOnly(); +} + +bool BridgedType::isOrContainsObjectiveCClass() const { + return get().isOrContainsObjectiveCClass(); +} + +bool BridgedType::isBuiltinInteger() const { + return get().isBuiltinInteger(); +} + +bool BridgedType::isBuiltinFloat() const { + return get().isBuiltinFloat(); +} + +bool BridgedType::isBuiltinVector() const { + return get().isBuiltinVector(); +} + +BridgedType BridgedType::getBuiltinVectorElementType() const { + return get().getBuiltinVectorElementType(); +} + +bool BridgedType::isBuiltinFixedWidthInteger(SwiftInt width) const { + return get().isBuiltinFixedWidthInteger((unsigned)width); +} + +bool BridgedType::isExactSuperclassOf(BridgedType t) const { + return get().isExactSuperclassOf(t.get()); +} + +BridgedType BridgedType::getInstanceTypeOfMetatype(BridgedFunction f) const { + return get().getInstanceTypeOfMetatype(f.getFunction()); +} + +BridgedType::MetatypeRepresentation BridgedType::getRepresentationOfMetatype(BridgedFunction f) const { + return BridgedType::MetatypeRepresentation(get().getRepresentationOfMetatype(f.getFunction())); +} + +bool BridgedType::isCalleeConsumedFunction() const { + return get().isCalleeConsumedFunction(); +} + +bool BridgedType::isMarkedAsImmortal() const { + return get().isMarkedAsImmortal(); +} + +SwiftInt BridgedType::getCaseIdxOfEnumType(BridgedStringRef name) const { + return get().getCaseIdxOfEnumType(name.get()); +} + +SwiftInt BridgedType::getNumNominalFields() const { + return get().getNumNominalFields(); +} + + +BridgedType BridgedType::getFieldType(SwiftInt idx, BridgedFunction f) const { + return get().getFieldType(idx, f.getFunction()); +} + +SwiftInt BridgedType::getFieldIdxOfNominalType(BridgedStringRef name) const { + return get().getFieldIdxOfNominalType(name.get()); +} + +BridgedStringRef BridgedType::getFieldName(SwiftInt idx) const { + return get().getFieldName(idx); +} + +SwiftInt BridgedType::getNumTupleElements() const { + return get().getNumTupleElements(); +} + +BridgedType BridgedType::getTupleElementType(SwiftInt idx) const { + return get().getTupleElementType(idx); +} + +//===----------------------------------------------------------------------===// +// BridgedValue +//===----------------------------------------------------------------------===// + +inline BridgedValue::Ownership castOwnership(swift::OwnershipKind ownership) { + switch (ownership) { + case swift::OwnershipKind::Any: + llvm_unreachable("Invalid ownership for value"); + case swift::OwnershipKind::Unowned: return BridgedValue::Ownership::Unowned; + case swift::OwnershipKind::Owned: return BridgedValue::Ownership::Owned; + case swift::OwnershipKind::Guaranteed: return BridgedValue::Ownership::Guaranteed; + case swift::OwnershipKind::None: return BridgedValue::Ownership::None; + } +} + +swift::ValueBase * _Nonnull BridgedValue::getSILValue() const { + return static_cast(obj); +} + +swift::ValueBase * _Nullable OptionalBridgedValue::getSILValue() const { + if (obj) + return static_cast(obj); + return nullptr; +} + +OptionalBridgedOperand BridgedValue::getFirstUse() const { + return {*getSILValue()->use_begin()}; +} + +BridgedType BridgedValue::getType() const { + return getSILValue()->getType(); +} + +BridgedValue::Ownership BridgedValue::getOwnership() const { + return castOwnership(getSILValue()->getOwnershipKind()); +} + +//===----------------------------------------------------------------------===// +// BridgedOperand +//===----------------------------------------------------------------------===// + +bool BridgedOperand::isTypeDependent() const { return op->isTypeDependent(); } + +bool BridgedOperand::isLifetimeEnding() const { return op->isLifetimeEnding(); } + +OptionalBridgedOperand BridgedOperand::getNextUse() const { + return {op->getNextUse()}; +} + +BridgedValue BridgedOperand::getValue() const { return {op->get()}; } + +BridgedInstruction BridgedOperand::getUser() const { + return {op->getUser()->asSILNode()}; +} + +BridgedOperand::OperandOwnership BridgedOperand::getOperandOwnership() const { + switch (op->getOperandOwnership()) { + case swift::OperandOwnership::NonUse: + return OperandOwnership::NonUse; + case swift::OperandOwnership::TrivialUse: + return OperandOwnership::TrivialUse; + case swift::OperandOwnership::InstantaneousUse: + return OperandOwnership::InstantaneousUse; + case swift::OperandOwnership::UnownedInstantaneousUse: + return OperandOwnership::UnownedInstantaneousUse; + case swift::OperandOwnership::ForwardingUnowned: + return OperandOwnership::ForwardingUnowned; + case swift::OperandOwnership::PointerEscape: + return OperandOwnership::PointerEscape; + case swift::OperandOwnership::BitwiseEscape: + return OperandOwnership::BitwiseEscape; + case swift::OperandOwnership::Borrow: + return OperandOwnership::Borrow; + case swift::OperandOwnership::DestroyingConsume: + return OperandOwnership::DestroyingConsume; + case swift::OperandOwnership::ForwardingConsume: + return OperandOwnership::ForwardingConsume; + case swift::OperandOwnership::InteriorPointer: + return OperandOwnership::InteriorPointer; + case swift::OperandOwnership::GuaranteedForwarding: + return OperandOwnership::GuaranteedForwarding; + case swift::OperandOwnership::EndBorrow: + return OperandOwnership::EndBorrow; + case swift::OperandOwnership::Reborrow: + return OperandOwnership::Reborrow; + } +} + +BridgedOperand OptionalBridgedOperand::advancedBy(SwiftInt index) const { return {op + index}; } + +// Assumes that `op` is not null. +SwiftInt OptionalBridgedOperand::distanceTo(BridgedOperand element) const { return element.op - op; } + +//===----------------------------------------------------------------------===// +// BridgedArgument +//===----------------------------------------------------------------------===// + +inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { + return static_cast(convention.Value); +} + +swift::SILArgument * _Nonnull BridgedArgument::getArgument() const { + return static_cast(obj); +} + +BridgedBasicBlock BridgedArgument::getParent() const { + return {getArgument()->getParent()}; +} + +BridgedArgumentConvention BridgedArgument::getConvention() const { + auto *fArg = llvm::cast(getArgument()); + return castToArgumentConvention(fArg->getArgumentConvention()); +} + +bool BridgedArgument::isSelf() const { + auto *fArg = llvm::cast(getArgument()); + return fArg->isSelf(); +} + +//===----------------------------------------------------------------------===// +// BridgedSubstitutionMap +//===----------------------------------------------------------------------===// + +BridgedSubstitutionMap::BridgedSubstitutionMap() : BridgedSubstitutionMap(swift::SubstitutionMap()) { +} + +bool BridgedSubstitutionMap::isEmpty() const { + return get().empty(); +} + +//===----------------------------------------------------------------------===// +// BridgedLocation +//===----------------------------------------------------------------------===// + +BridgedLocation BridgedLocation::getAutogeneratedLocation() const { + return getLoc().getAutogeneratedLocation(); +} +bool BridgedLocation::hasValidLineNumber() const { + return getLoc().hasValidLineNumber(); +} +bool BridgedLocation::isAutoGenerated() const { + return getLoc().isAutoGenerated(); +} +bool BridgedLocation::isEqualTo(BridgedLocation rhs) const { + return getLoc().isEqualTo(rhs.getLoc()); +} +bool BridgedLocation::hasSameSourceLocation(BridgedLocation rhs) const { + return getLoc().hasSameSourceLocation(rhs.getLoc()); +} +BridgedLocation BridgedLocation::getArtificialUnreachableLocation() { + return swift::SILDebugLocation::getArtificialUnreachableLocation(); +} + +//===----------------------------------------------------------------------===// +// BridgedFunction +//===----------------------------------------------------------------------===// + +swift::SILFunction * _Nonnull BridgedFunction::getFunction() const { + return static_cast(obj); +} + +BridgedStringRef BridgedFunction::getName() const { + return getFunction()->getName(); +} + +bool BridgedFunction::hasOwnership() const { return getFunction()->hasOwnership(); } + +OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { + return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; +} + +OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { + return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; +} + +SwiftInt BridgedFunction::getNumIndirectFormalResults() const { + return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); +} + +SwiftInt BridgedFunction::getNumParameters() const { + return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); +} + +SwiftInt BridgedFunction::getSelfArgumentIndex() const { + swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); + swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); + if (!fTy->hasSelfParam()) + return -1; + return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; +} + +SwiftInt BridgedFunction::getNumSILArguments() const { + return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); +} + +BridgedType BridgedFunction::getSILArgumentType(SwiftInt idx) const { + swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); + return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); +} + +BridgedArgumentConvention BridgedFunction::getSILArgumentConvention(SwiftInt idx) const { + swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); + return castToArgumentConvention(conv.getSILArgumentConvention(idx)); +} + +BridgedType BridgedFunction::getSILResultType() const { + swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); + return conv.getSILResultType(getFunction()->getTypeExpansionContext()); +} + +bool BridgedFunction::isSwift51RuntimeAvailable() const { + if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) + return false; + + swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); + return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); +} + +bool BridgedFunction::isPossiblyUsedExternally() const { + return getFunction()->isPossiblyUsedExternally(); +} + +bool BridgedFunction::isAvailableExternally() const { + return getFunction()->isAvailableExternally(); +} + +bool BridgedFunction::isTransparent() const { + return getFunction()->isTransparent() == swift::IsTransparent; +} + +bool BridgedFunction::isAsync() const { + return getFunction()->isAsync(); +} + +bool BridgedFunction::isGlobalInitFunction() const { + return getFunction()->isGlobalInit(); +} + +bool BridgedFunction::isGlobalInitOnceFunction() const { + return getFunction()->isGlobalInitOnceFunction(); +} + +bool BridgedFunction::isDestructor() const { + if (auto *declCtxt = getFunction()->getDeclContext()) { + return llvm::isa(declCtxt); + } + return false; +} + +bool BridgedFunction::isGenericFunction() const { + return !getFunction()->getGenericSignature().isNull(); +} + +bool BridgedFunction::hasSemanticsAttr(BridgedStringRef attrName) const { + return getFunction()->hasSemanticsAttr(attrName.get()); +} + +BridgedFunction::EffectsKind BridgedFunction::getEffectAttribute() const { + return (EffectsKind)getFunction()->getEffectsKind(); +} + +BridgedFunction::PerformanceConstraints BridgedFunction::getPerformanceConstraints() const { + return (PerformanceConstraints)getFunction()->getPerfConstraints(); +} + +BridgedFunction::InlineStrategy BridgedFunction::getInlineStrategy() const { + return (InlineStrategy)getFunction()->getInlineStrategy(); +} + +bool BridgedFunction::isSerialized() const { + return getFunction()->isSerialized(); +} + +bool BridgedFunction::hasValidLinkageForFragileRef() const { + return getFunction()->hasValidLinkageForFragileRef(); +} + +bool BridgedFunction::needsStackProtection() const { + return getFunction()->needsStackProtection(); +} + +void BridgedFunction::setNeedStackProtection(bool needSP) const { + getFunction()->setNeedStackProtection(needSP); +} + + +//===----------------------------------------------------------------------===// +// BridgedGlobalVar +//===----------------------------------------------------------------------===// + +swift::SILGlobalVariable * _Nonnull BridgedGlobalVar::getGlobal() const { + return static_cast(obj); +} + +BridgedStringRef BridgedGlobalVar::getName() const { + return getGlobal()->getName(); +} + +bool BridgedGlobalVar::isLet() const { return getGlobal()->isLet(); } + +void BridgedGlobalVar::setLet(bool value) const { getGlobal()->setLet(value); } + +bool BridgedGlobalVar::isPossiblyUsedExternally() const { + return getGlobal()->isPossiblyUsedExternally(); +} + +bool BridgedGlobalVar::isAvailableExternally() const { + return swift::isAvailableExternally(getGlobal()->getLinkage()); +} + +OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { + if (getGlobal()->begin() == getGlobal()->end()) { + return {nullptr}; + } + swift::SILInstruction *firstInst = &*getGlobal()->begin(); + return {firstInst->asSILNode()}; +} + +//===----------------------------------------------------------------------===// +// BridgedMultiValueResult +//===----------------------------------------------------------------------===// + +BridgedInstruction BridgedMultiValueResult::getParent() const { + return {get()->getParent()}; +} + +SwiftInt BridgedMultiValueResult::getIndex() const { + return (SwiftInt)get()->getIndex(); +} + +//===----------------------------------------------------------------------===// +// BridgedTypeArray +//===----------------------------------------------------------------------===// + +BridgedTypeArray BridgedTypeArray::fromReplacementTypes(BridgedSubstitutionMap substMap) { + swift::ArrayRef replTypes = substMap.get().getReplacementTypes(); + return {replTypes.data(), replTypes.size()}; +} + +BridgedType BridgedTypeArray::getAt(SwiftInt index) const { + assert((size_t)index < typeArray.numElements); + swift::Type origTy = ((const swift::Type *)typeArray.data)[index]; + auto ty = origTy->getCanonicalType(); + if (ty->isLegalSILType()) + return swift::SILType::getPrimitiveObjectType(ty); + return swift::SILType(); +} + +//===----------------------------------------------------------------------===// +// BridgedTypeArray +//===----------------------------------------------------------------------===// + +BridgedType BridgedSILTypeArray::getAt(SwiftInt index) const { + assert((size_t)index < typeArray.numElements); + return ((const swift::SILType *)typeArray.data)[index]; +} + +//===----------------------------------------------------------------------===// +// BridgedInstruction +//===----------------------------------------------------------------------===// + +OptionalBridgedInstruction BridgedInstruction::getNext() const { + auto iter = std::next(get()->getIterator()); + if (iter == get()->getParent()->end()) + return {nullptr}; + return {iter->asSILNode()}; +} + +OptionalBridgedInstruction BridgedInstruction::getPrevious() const { + auto iter = std::next(get()->getReverseIterator()); + if (iter == get()->getParent()->rend()) + return {nullptr}; + return {iter->asSILNode()}; +} + +BridgedBasicBlock BridgedInstruction::getParent() const { + assert(!get()->isStaticInitializerInst() && + "cannot get the parent of a static initializer instruction"); + return {get()->getParent()}; +} + +BridgedInstruction BridgedInstruction::getLastInstOfParent() const { + return {get()->getParent()->back().asSILNode()}; +} + +bool BridgedInstruction::isDeleted() const { + return get()->isDeleted(); +} + +BridgedOperandArray BridgedInstruction::getOperands() const { + auto operands = get()->getAllOperands(); + return {{operands.data()}, (SwiftInt)operands.size()}; +} + +BridgedOperandArray BridgedInstruction::getTypeDependentOperands() const { + auto typeOperands = get()->getTypeDependentOperands(); + return {{typeOperands.data()}, (SwiftInt)typeOperands.size()}; +} + +void BridgedInstruction::setOperand(SwiftInt index, BridgedValue value) const { + get()->setOperand((unsigned)index, value.getSILValue()); +} + +BridgedLocation BridgedInstruction::getLocation() const { + return get()->getDebugLocation(); +} + +BridgedMemoryBehavior BridgedInstruction::getMemBehavior() const { + return (BridgedMemoryBehavior)get()->getMemoryBehavior(); +} + +bool BridgedInstruction::mayRelease() const { + return get()->mayRelease(); +} + +bool BridgedInstruction::mayHaveSideEffects() const { + return get()->mayHaveSideEffects(); +} + +bool BridgedInstruction::maySuspend() const { + return get()->maySuspend(); +} + +SwiftInt BridgedInstruction::MultipleValueInstruction_getNumResults() const { + return getAs()->getNumResults(); +} + +BridgedMultiValueResult BridgedInstruction::MultipleValueInstruction_getResult(SwiftInt index) const { + return {getAs()->getResult(index)}; +} + +BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { + auto successors = getAs()->getSuccessors(); + return {{successors.data()}, (SwiftInt)successors.size()}; +} + +OptionalBridgedOperand BridgedInstruction::ForwardingInst_singleForwardedOperand() const { + return {swift::ForwardingOperation(get()).getSingleForwardingOperand()}; +} + +BridgedOperandArray BridgedInstruction::ForwardingInst_forwardedOperands() const { + auto operands = + swift::ForwardingOperation(get()).getForwardedOperands(); + return {{operands.data()}, (SwiftInt)operands.size()}; +} + +BridgedValue::Ownership BridgedInstruction::ForwardingInst_forwardingOwnership() const { + auto *forwardingInst = swift::ForwardingInstruction::get(get()); + return castOwnership(forwardingInst->getForwardingOwnershipKind()); +} + +bool BridgedInstruction::ForwardingInst_preservesOwnership() const { + return swift::ForwardingInstruction::get(get())->preservesOwnership(); +} + +BridgedStringRef BridgedInstruction::CondFailInst_getMessage() const { + return getAs()->getMessage(); +} + +SwiftInt BridgedInstruction::LoadInst_getLoadOwnership() const { + return (SwiftInt)getAs()->getOwnershipQualifier(); +} + +BridgedInstruction::BuiltinValueKind BridgedInstruction::BuiltinInst_getID() const { + return (BuiltinValueKind)getAs()->getBuiltinInfo().ID; +} + +BridgedInstruction::IntrinsicID BridgedInstruction::BuiltinInst_getIntrinsicID() const { + switch (getAs()->getIntrinsicInfo().ID) { + case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; + case llvm::Intrinsic::memmove: return IntrinsicID::memmove; + default: return IntrinsicID::unknown; + } +} + +BridgedSubstitutionMap BridgedInstruction::BuiltinInst_getSubstitutionMap() const { + return getAs()->getSubstitutions(); +} + +bool BridgedInstruction::PointerToAddressInst_isStrict() const { + return getAs()->isStrict(); +} + +bool BridgedInstruction::AddressToPointerInst_needsStackProtection() const { + return getAs()->needsStackProtection(); +} + +bool BridgedInstruction::IndexAddrInst_needsStackProtection() const { + return getAs()->needsStackProtection(); +} + +BridgedGlobalVar BridgedInstruction::GlobalAccessInst_getGlobal() const { + return {getAs()->getReferencedGlobal()}; +} + +BridgedGlobalVar BridgedInstruction::AllocGlobalInst_getGlobal() const { + return {getAs()->getReferencedGlobal()}; +} + +BridgedFunction BridgedInstruction::FunctionRefBaseInst_getReferencedFunction() const { + return {getAs()->getInitiallyReferencedFunction()}; +} + +BridgedInstruction::OptionalInt BridgedInstruction::IntegerLiteralInst_getValue() const { + llvm::APInt result = getAs()->getValue(); + if (result.getSignificantBits() <= std::min(std::numeric_limits::digits, 64)) { + return {(SwiftInt)result.getSExtValue(), true}; + } + return {0, false}; +} + +BridgedStringRef BridgedInstruction::StringLiteralInst_getValue() const { + return getAs()->getValue(); +} + +int BridgedInstruction::StringLiteralInst_getEncoding() const { + return (int)getAs()->getEncoding(); +} + +SwiftInt BridgedInstruction::TupleExtractInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +SwiftInt BridgedInstruction::TupleElementAddrInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +SwiftInt BridgedInstruction::StructExtractInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +OptionalBridgedValue BridgedInstruction::StructInst_getUniqueNonTrivialFieldValue() const { + return {getAs()->getUniqueNonTrivialFieldValue()}; +} + +SwiftInt BridgedInstruction::StructElementAddrInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +SwiftInt BridgedInstruction::ProjectBoxInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +bool BridgedInstruction::EndCOWMutationInst_doKeepUnique() const { + return getAs()->doKeepUnique(); +} + +SwiftInt BridgedInstruction::EnumInst_caseIndex() const { + return getAs()->getCaseIndex(); +} + +SwiftInt BridgedInstruction::UncheckedEnumDataInst_caseIndex() const { + return getAs()->getCaseIndex(); +} + +SwiftInt BridgedInstruction::InitEnumDataAddrInst_caseIndex() const { + return getAs()->getCaseIndex(); +} + +SwiftInt BridgedInstruction::UncheckedTakeEnumDataAddrInst_caseIndex() const { + return getAs()->getCaseIndex(); +} + +SwiftInt BridgedInstruction::InjectEnumAddrInst_caseIndex() const { + return getAs()->getCaseIndex(); +} + +SwiftInt BridgedInstruction::RefElementAddrInst_fieldIndex() const { + return getAs()->getFieldIndex(); +} + +bool BridgedInstruction::RefElementAddrInst_fieldIsLet() const { + return getAs()->getField()->isLet(); +} + +bool BridgedInstruction::RefElementAddrInst_isImmutable() const { + return getAs()->isImmutable(); +} + +void BridgedInstruction::RefElementAddrInst_setImmutable(bool isImmutable) const { + getAs()->setImmutable(isImmutable); +} + +SwiftInt BridgedInstruction::PartialApplyInst_numArguments() const { + return getAs()->getNumArguments(); +} + +SwiftInt BridgedInstruction::ApplyInst_numArguments() const { + return getAs()->getNumArguments(); +} + +bool BridgedInstruction::ApplyInst_getNonThrowing() const { + return getAs()->isNonThrowing(); +} + +bool BridgedInstruction::ApplyInst_getNonAsync() const { + return getAs()->isNonAsync(); +} + +BridgedGenericSpecializationInformation BridgedInstruction::ApplyInst_getSpecializationInfo() const { + return {getAs()->getSpecializationInfo()}; +} + +SwiftInt BridgedInstruction::ObjectInst_getNumBaseElements() const { + return getAs()->getNumBaseElements(); +} + +SwiftInt BridgedInstruction::PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { + return swift::ApplySite(get()).getCalleeArgIndexOfFirstAppliedArg(); +} + +bool BridgedInstruction::PartialApplyInst_isOnStack() const { + return getAs()->isOnStack(); +} + +bool BridgedInstruction::AllocStackInst_hasDynamicLifetime() const { + return getAs()->hasDynamicLifetime(); +} + +bool BridgedInstruction::AllocRefInstBase_isObjc() const { + return getAs()->isObjC(); +} + +bool BridgedInstruction::AllocRefInstBase_canAllocOnStack() const { + return getAs()->canAllocOnStack(); +} + +SwiftInt BridgedInstruction::AllocRefInstBase_getNumTailTypes() const { + return getAs()->getNumTailTypes(); +} + +BridgedSILTypeArray BridgedInstruction::AllocRefInstBase_getTailAllocatedTypes() const { + llvm::ArrayRef types = getAs()->getTailAllocatedTypes(); + return {types.data(), types.size()}; +} + +bool BridgedInstruction::AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { + return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); +} + +SwiftInt BridgedInstruction::BeginApplyInst_numArguments() const { + return getAs()->getNumArguments(); +} + +SwiftInt BridgedInstruction::TryApplyInst_numArguments() const { + return getAs()->getNumArguments(); +} + +BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { + return {getAs()->getDestBB()}; +} + +SwiftInt BridgedInstruction::SwitchEnumInst_getNumCases() const { + return getAs()->getNumCases(); +} + +SwiftInt BridgedInstruction::SwitchEnumInst_getCaseIndex(SwiftInt idx) const { + auto *seInst = getAs(); + return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); +} + +SwiftInt BridgedInstruction::StoreInst_getStoreOwnership() const { + return (SwiftInt)getAs()->getOwnershipQualifier(); +} + +SwiftInt BridgedInstruction::AssignInst_getAssignOwnership() const { + return (SwiftInt)getAs()->getOwnershipQualifier(); +} + +BridgedInstruction::AccessKind BridgedInstruction::BeginAccessInst_getAccessKind() const { + return (AccessKind)getAs()->getAccessKind(); +} + +bool BridgedInstruction::BeginAccessInst_isStatic() const { + return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; +} + +bool BridgedInstruction::CopyAddrInst_isTakeOfSrc() const { + return getAs()->isTakeOfSrc(); +} + +bool BridgedInstruction::CopyAddrInst_isInitializationOfDest() const { + return getAs()->isInitializationOfDest(); +} + +SwiftInt BridgedInstruction::MarkUninitializedInst_getKind() const { + return (SwiftInt)getAs()->getMarkUninitializedKind(); +} + +void BridgedInstruction::RefCountingInst_setIsAtomic(bool isAtomic) const { + getAs()->setAtomicity( + isAtomic ? swift::RefCountingInst::Atomicity::Atomic + : swift::RefCountingInst::Atomicity::NonAtomic); +} + +bool BridgedInstruction::RefCountingInst_getIsAtomic() const { + return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; +} + +SwiftInt BridgedInstruction::CondBranchInst_getNumTrueArgs() const { + return getAs()->getNumTrueArgs(); +} + +void BridgedInstruction::AllocRefInstBase_setIsStackAllocatable() const { + getAs()->setStackAllocatable(); +} + +bool BridgedInstruction::AllocRefInst_isBare() const { + return getAs()->isBare(); +} + +void BridgedInstruction::AllocRefInst_setIsBare() const { + getAs()->setBare(true); +} + +void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { + getAs()->replaceBranchTarget(from.get(), to.get()); +} + +SwiftInt BridgedInstruction::KeyPathInst_getNumComponents() const { + if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { + return (SwiftInt)pattern->getComponents().size(); + } + return 0; +} + +void BridgedInstruction::KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, + KeyPathFunctionResults * _Nonnull results) const { + swift::KeyPathPattern *pattern = getAs()->getPattern(); + const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; + results->numFunctions = 0; + + comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { + assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); + results->functions[results->numFunctions++] = {func}; + }, [](swift::SILDeclRef) {}); +} + +bool BridgedInstruction::GlobalValueInst_isBare() const { + return getAs()->isBare(); +} + +void BridgedInstruction::GlobalValueInst_setIsBare() const { + getAs()->setBare(true); +} + +void BridgedInstruction::LoadInst_setOwnership(SwiftInt ownership) const { + getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); +} + +BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { + return {getAs()->getSuccessBB()}; +} + +BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { + return {getAs()->getFailureBB()}; +} + +BridgedSubstitutionMap BridgedInstruction::ApplySite_getSubstitutionMap() const { + auto as = swift::ApplySite(get()); + return as.getSubstitutionMap(); +} + +BridgedArgumentConvention BridgedInstruction::ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { + auto as = swift::ApplySite(get()); + auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); + return castToArgumentConvention(conv.Value); +} + +SwiftInt BridgedInstruction::ApplySite_getNumArguments() const { + return swift::ApplySite(get()).getNumArguments(); +} + +SwiftInt BridgedInstruction::FullApplySite_numIndirectResultArguments() const { + auto fas = swift::FullApplySite(get()); + return fas.getNumIndirectSILResults(); +} + +//===----------------------------------------------------------------------===// +// BridgedBasicBlock +//===----------------------------------------------------------------------===// + +OptionalBridgedBasicBlock BridgedBasicBlock::getNext() const { + auto iter = std::next(get()->getIterator()); + if (iter == get()->getParent()->end()) + return {nullptr}; + return {&*iter}; +} + +OptionalBridgedBasicBlock BridgedBasicBlock::getPrevious() const { + auto iter = std::next(get()->getReverseIterator()); + if (iter == get()->getParent()->rend()) + return {nullptr}; + return {&*iter}; +} + +BridgedFunction BridgedBasicBlock::getFunction() const { + return {get()->getParent()}; +} + +OptionalBridgedInstruction BridgedBasicBlock::getFirstInst() const { + if (get()->empty()) + return {nullptr}; + return {get()->front().asSILNode()}; +} + +OptionalBridgedInstruction BridgedBasicBlock::getLastInst() const { + if (get()->empty()) + return {nullptr}; + return {get()->back().asSILNode()}; +} + +SwiftInt BridgedBasicBlock::getNumArguments() const { + return get()->getNumArguments(); +} + +BridgedArgument BridgedBasicBlock::getArgument(SwiftInt index) const { + return {get()->getArgument(index)}; +} + +BridgedArgument BridgedBasicBlock::addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const { + return {get()->createPhiArgument(type.get(), BridgedValue::castToOwnership(ownership))}; +} + +void BridgedBasicBlock::eraseArgument(SwiftInt index) const { + get()->eraseArgument(index); +} + +void BridgedBasicBlock::moveAllInstructionsToBegin(BridgedBasicBlock dest) const { + dest.get()->spliceAtBegin(get()); +} + +void BridgedBasicBlock::moveAllInstructionsToEnd(BridgedBasicBlock dest) const { + dest.get()->spliceAtEnd(get()); +} + +void BridgedBasicBlock::moveArgumentsTo(BridgedBasicBlock dest) const { + dest.get()->moveArgumentList(get()); +} + +OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { + return {get()->pred_begin().getSuccessorRef()}; +} + +//===----------------------------------------------------------------------===// +// BridgedSuccessor +//===----------------------------------------------------------------------===// + +OptionalBridgedSuccessor BridgedSuccessor::getNext() const { + return {succ->getNext()}; +} + +BridgedBasicBlock BridgedSuccessor::getTargetBlock() const { + return succ->getBB(); +} + +BridgedInstruction BridgedSuccessor::getContainingInst() const { + return {succ->getContainingInst()}; +} + +BridgedSuccessor OptionalBridgedSuccessor::advancedBy(SwiftInt index) const { + return {succ + index}; +} + +//===----------------------------------------------------------------------===// +// BridgedVTable +//===----------------------------------------------------------------------===// + +BridgedFunction BridgedVTableEntry::getImplementation() const { + return {entry->getImplementation()}; +} + +BridgedVTableEntry BridgedVTableEntry::advanceBy(SwiftInt index) const { + return {entry + index}; +} + +BridgedVTableEntryArray BridgedVTable::getEntries() const { + auto entries = vTable->getEntries(); + return {{entries.data()}, (SwiftInt)entries.size()}; +} + +//===----------------------------------------------------------------------===// +// BridgedWitnessTable, BridgedDefaultWitnessTable +//===----------------------------------------------------------------------===// + +BridgedWitnessTableEntry::Kind BridgedWitnessTableEntry::getKind() const { + return (Kind)getEntry()->getKind(); +} + +OptionalBridgedFunction BridgedWitnessTableEntry::getMethodFunction() const { + return {getEntry()->getMethodWitness().Witness}; +} + +BridgedWitnessTableEntry BridgedWitnessTableEntry::advanceBy(SwiftInt index) const { + return {getEntry() + index}; +} + +BridgedWitnessTableEntryArray BridgedWitnessTable::getEntries() const { + auto entries = table->getEntries(); + return {{entries.data()}, (SwiftInt)entries.size()}; +} + +BridgedWitnessTableEntryArray BridgedDefaultWitnessTable::getEntries() const { + auto entries = table->getEntries(); + return {{entries.data()}, (SwiftInt)entries.size()}; +} + +//===----------------------------------------------------------------------===// +// BridgedBuilder +//===----------------------------------------------------------------------===// + +static swift::SILBuilder builder(const BridgedBuilder * _Nonnull b) { + switch (b->insertAt) { + case BridgedBuilder::InsertAt::beforeInst: + return swift::SILBuilder(BridgedInstruction(b->insertionObj).get(), b->loc.getLoc().getScope()); + case BridgedBuilder::InsertAt::endOfBlock: + return swift::SILBuilder(BridgedBasicBlock(b->insertionObj).get(), b->loc.getLoc().getScope()); + case BridgedBuilder::InsertAt::intoGlobal: + return swift::SILBuilder(BridgedGlobalVar(b->insertionObj).getGlobal()); + } +} + +static swift::SILLocation regularLoc(const BridgedBuilder * _Nonnull b) { + return swift::RegularLocation(b->loc.getLoc().getLocation()); +} + +BridgedInstruction BridgedBuilder::createBuiltinBinaryFunction(BridgedStringRef name, + BridgedType operandType, BridgedType resultType, + BridgedValueArray arguments) const { + llvm::SmallVector argValues; + return {builder(this).createBuiltinBinaryFunction(regularLoc(this), + name.get(), + operandType.get(), resultType.get(), + arguments.getValues(argValues))}; +} + +BridgedInstruction BridgedBuilder::createCondFail(BridgedValue condition, BridgedStringRef message) const { + return {builder(this).createCondFail(regularLoc(this), condition.getSILValue(), message.get())}; +} + +BridgedInstruction BridgedBuilder::createIntegerLiteral(BridgedType type, SwiftInt value) const { + return {builder(this).createIntegerLiteral(regularLoc(this), type.get(), value)}; +} + +BridgedInstruction BridgedBuilder::createAllocStack(BridgedType type, + bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { + return {builder(this).createAllocStack(regularLoc(this), type.get(), llvm::None, + hasDynamicLifetime, isLexical, wasMoved)}; +} + +BridgedInstruction BridgedBuilder::createDeallocStack(BridgedValue operand) const { + return {builder(this).createDeallocStack(regularLoc(this), operand.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createDeallocStackRef(BridgedValue operand) const { + return {builder(this).createDeallocStackRef(regularLoc(this), operand.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createUncheckedRefCast(BridgedValue op, BridgedType type) const { + return {builder(this).createUncheckedRefCast(regularLoc(this), op.getSILValue(), type.get())}; +} + +BridgedInstruction BridgedBuilder::createUpcast(BridgedValue op, BridgedType type) const { + return {builder(this).createUpcast(regularLoc(this), op.getSILValue(), type.get())}; +} + +BridgedInstruction BridgedBuilder::createLoad(BridgedValue op, SwiftInt ownership) const { + return {builder(this).createLoad(regularLoc(this), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; +} + +BridgedInstruction BridgedBuilder::createBeginDeallocRef(BridgedValue reference, BridgedValue allocation) const { + return {builder(this).createBeginDeallocRef(regularLoc(this), reference.getSILValue(), allocation.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createEndInitLetRef(BridgedValue op) const { + return {builder(this).createEndInitLetRef(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createStrongRetain(BridgedValue op) const { + auto b = builder(this); + return {b.createStrongRetain(regularLoc(this), op.getSILValue(), b.getDefaultAtomicity())}; +} + +BridgedInstruction BridgedBuilder::createStrongRelease(BridgedValue op) const { + auto b = builder(this); + return {b.createStrongRelease(regularLoc(this), op.getSILValue(), b.getDefaultAtomicity())}; +} + +BridgedInstruction BridgedBuilder::createUnownedRetain(BridgedValue op) const { + auto b = builder(this); + return {b.createUnownedRetain(regularLoc(this), op.getSILValue(), b.getDefaultAtomicity())}; +} + +BridgedInstruction BridgedBuilder::createUnownedRelease(BridgedValue op) const { + auto b = builder(this); + return {b.createUnownedRelease(regularLoc(this), op.getSILValue(), b.getDefaultAtomicity())}; +} + +BridgedInstruction BridgedBuilder::createFunctionRef(BridgedFunction function) const { + return {builder(this).createFunctionRef(regularLoc(this), function.getFunction())}; +} + +BridgedInstruction BridgedBuilder::createCopyValue(BridgedValue op) const { + return {builder(this).createCopyValue(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createBeginBorrow(BridgedValue op) const { + return {builder(this).createBeginBorrow(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createEndBorrow(BridgedValue op) const { + return {builder(this).createEndBorrow(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createCopyAddr(BridgedValue from, BridgedValue to, + bool takeSource, bool initializeDest) const { + return {builder(this).createCopyAddr(regularLoc(this), + from.getSILValue(), to.getSILValue(), + swift::IsTake_t(takeSource), + swift::IsInitialization_t(initializeDest))}; +} + +BridgedInstruction BridgedBuilder::createDestroyValue(BridgedValue op) const { + return {builder(this).createDestroyValue(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createDestroyAddr(BridgedValue op) const { + return {builder(this).createDestroyAddr(regularLoc(this), op.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createDebugStep() const { + return {builder(this).createDebugStep(regularLoc(this))}; +} + +BridgedInstruction BridgedBuilder::createApply(BridgedValue function, BridgedSubstitutionMap subMap, + BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, + BridgedGenericSpecializationInformation specInfo) const { + llvm::SmallVector argValues; + swift::ApplyOptions applyOpts; + if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } + if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } + + return {builder(this).createApply(regularLoc(this), + function.getSILValue(), subMap.get(), + arguments.getValues(argValues), + applyOpts, specInfo.data)}; +} + +BridgedInstruction BridgedBuilder::createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, + const void * _Nullable enumCases, SwiftInt numEnumCases) const { + using BridgedCase = const std::pair; + llvm::ArrayRef cases(static_cast(enumCases), + (unsigned)numEnumCases); + llvm::SmallDenseMap mappedElements; + swift::SILValue en = enumVal.getSILValue(); + swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); + for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { + mappedElements[elemWithIndex.index()] = elemWithIndex.value(); + } + llvm::SmallVector, 16> convertedCases; + for (auto c : cases) { + assert(mappedElements.count(c.first) && "wrong enum element index"); + convertedCases.push_back({mappedElements[c.first], c.second.get()}); + } + return {builder(this).createSwitchEnum(regularLoc(this), + enumVal.getSILValue(), + defaultBlock.get(), convertedCases)}; +} + +BridgedInstruction BridgedBuilder::createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, + BridgedType resultType) const { + swift::SILValue en = enumVal.getSILValue(); + return {builder(this).createUncheckedEnumData(regularLoc(this), enumVal.getSILValue(), + en->getType().getEnumElement(caseIdx), resultType.get())}; +} + +BridgedInstruction BridgedBuilder::createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, + BridgedType resultType) const { + swift::EnumElementDecl *caseDecl = resultType.get().getEnumElement(caseIdx); + swift::SILValue pl = payload.getSILValue(); + return {builder(this).createEnum(regularLoc(this), pl, caseDecl, resultType.get())}; +} + +BridgedInstruction BridgedBuilder::createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { + llvm::SmallVector argValues; + return {builder(this).createBranch(regularLoc(this), destBlock.get(), arguments.getValues(argValues))}; +} + +BridgedInstruction BridgedBuilder::createUnreachable() const { + return {builder(this).createUnreachable(regularLoc(this))}; +} + +BridgedInstruction BridgedBuilder::createObject(BridgedType type, + BridgedValueArray arguments, + SwiftInt numBaseElements) const { + llvm::SmallVector argValues; + return {builder(this).createObject(swift::ArtificialUnreachableLocation(), + type.get(), arguments.getValues(argValues), numBaseElements)}; +} + +BridgedInstruction BridgedBuilder::createGlobalAddr(BridgedGlobalVar global) const { + return {builder(this).createGlobalAddr(regularLoc(this), global.getGlobal())}; +} + +BridgedInstruction BridgedBuilder::createGlobalValue(BridgedGlobalVar global, bool isBare) const { + return {builder(this).createGlobalValue(regularLoc(this), global.getGlobal(), isBare)}; +} + +BridgedInstruction BridgedBuilder::createStruct(BridgedType type, BridgedValueArray elements) const { + llvm::SmallVector elementValues; + return {builder(this).createStruct(regularLoc(this), type.get(), elements.getValues(elementValues))}; +} + +BridgedInstruction BridgedBuilder::createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { + swift::SILValue v = str.getSILValue(); + return {builder(this).createStructExtract(regularLoc(this), v, v->getType().getFieldDecl(fieldIndex))}; +} + +BridgedInstruction BridgedBuilder::createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { + swift::SILValue v = addr.getSILValue(); + return {builder(this).createStructElementAddr(regularLoc(this), v, v->getType().getFieldDecl(fieldIndex))}; +} + +BridgedInstruction BridgedBuilder::createDestructureStruct(BridgedValue str) const { + return {builder(this).createDestructureStruct(regularLoc(this), str.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createTuple(BridgedType type, BridgedValueArray elements) const { + llvm::SmallVector elementValues; + return {builder(this).createTuple(regularLoc(this), type.get(), elements.getValues(elementValues))}; +} + +BridgedInstruction BridgedBuilder::createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { + swift::SILValue v = str.getSILValue(); + return {builder(this).createTupleExtract(regularLoc(this), v, elementIndex)}; +} + +BridgedInstruction BridgedBuilder::createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { + swift::SILValue v = addr.getSILValue(); + return {builder(this).createTupleElementAddr(regularLoc(this), v, elementIndex)}; +} + +BridgedInstruction BridgedBuilder::createDestructureTuple(BridgedValue str) const { + return {builder(this).createDestructureTuple(regularLoc(this), str.getSILValue())}; +} + +BridgedInstruction BridgedBuilder::createStore(BridgedValue src, BridgedValue dst, + SwiftInt ownership) const { + return {builder(this).createStore(regularLoc(this), src.getSILValue(), dst.getSILValue(), + (swift::StoreOwnershipQualifier)ownership)}; +} + +BridgedInstruction BridgedBuilder::createInitExistentialRef(BridgedValue instance, + BridgedType type, + BridgedInstruction useConformancesOf) const { + auto *src = useConformancesOf.getAs(); + return {builder(this).createInitExistentialRef(regularLoc(this), type.get(), + src->getFormalConcreteType(), + instance.getSILValue(), + src->getConformances())}; +} + +BridgedInstruction BridgedBuilder::createMetatype(BridgedType type, + BridgedType::MetatypeRepresentation representation) const { + auto *mt = swift::MetatypeType::get(type.get().getASTType(), (swift::MetatypeRepresentation)representation); + auto t = swift::SILType::getPrimitiveObjectType(swift::CanType(mt)); + return {builder(this).createMetatype(regularLoc(this), t)}; +} + +BridgedInstruction BridgedBuilder::createEndCOWMutation(BridgedValue instance, bool keepUnique) const { + return {builder(this).createEndCOWMutation(regularLoc(this), instance.getSILValue(), keepUnique)}; +} + +//===----------------------------------------------------------------------===// +// BridgedNominalTypeDecl +//===----------------------------------------------------------------------===// + +BridgedStringRef BridgedNominalTypeDecl::getName() const { + return decl->getName().str(); +} + +bool BridgedNominalTypeDecl::isGlobalActor() const { return decl->isGlobalActor(); } + + +SWIFT_END_NULLABILITY_ANNOTATIONS + +#endif diff --git a/include/swift/SIL/SILLocation.h b/include/swift/SIL/SILLocation.h index 671eb25443d58..1e18af386ed05 100644 --- a/include/swift/SIL/SILLocation.h +++ b/include/swift/SIL/SILLocation.h @@ -730,8 +730,6 @@ class SILDebugLocation { bool isAutoGenerated() const { return location.isAutoGenerated(); } operator bool() const { return bool(location) && debugScope; } - std::string getDebugDescription() const; - SWIFT_IMPORT_UNSAFE SILDebugLocation getAutogeneratedLocation() const { SILDebugLocation autoGenLoc(RegularLocation::getAutoGeneratedLocation(), getScope()); diff --git a/include/swift/SILOptimizer/OptimizerBridging.h b/include/swift/SILOptimizer/OptimizerBridging.h index 9159662584c28..49b961af66f55 100644 --- a/include/swift/SILOptimizer/OptimizerBridging.h +++ b/include/swift/SILOptimizer/OptimizerBridging.h @@ -13,27 +13,52 @@ #ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H #define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H -#include "swift/Basic/Nullability.h" +// Do not add other C++/llvm/swift header files here! +// Function implementations should be placed into OptimizerBridgingImpl.h or OptimizerBridging.cpp and +// required header files should be added there. +// #include "swift/SIL/SILBridging.h" -#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" + +#ifdef USED_IN_CPP_SOURCE + #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" -#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" -#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" -#include "swift/SILOptimizer/PassManager/PassManager.h" -#include "swift/SILOptimizer/Utils/InstOptUtils.h" + +#else // USED_IN_CPP_SOURCE + +#ifdef SWIFT_SIL_SILVALUE_H +#error "should not include swift headers into bridging header" +#endif +#ifdef LLVM_SUPPORT_COMPILER_H +#error "should not include llvm headers into bridging header" +#endif + +#endif // USED_IN_CPP_SOURCE SWIFT_BEGIN_NULLABILITY_ANNOTATIONS +namespace swift { +class AliasAnalysis; +class BasicCalleeAnalysis; +class DeadEndBlocks; +class DominanceInfo; +class PostDominanceInfo; +class BasicBlockSet; +class NodeSet; +class ClonerWithFixedLocation; +class SwiftPassInvocation; +class FixedSizeSlabPayload; +class FixedSizeSlab; +class SILVTable; +} + struct BridgedPassContext; struct BridgedAliasAnalysis { swift::AliasAnalysis * _Nonnull aa; - swift::MemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { - return aa->computeMemoryBehavior(inst.getInst(), addr.getSILValue()); - } + BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const; - typedef swift::MemoryBehavior (* _Nonnull GetMemEffectFn)( + typedef BridgedMemoryBehavior (* _Nonnull GetMemEffectFn)( BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); typedef bool (* _Nonnull Escaping2InstFn)( BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); @@ -51,19 +76,28 @@ struct BridgedAliasAnalysis { struct BridgedCalleeAnalysis { swift::BasicCalleeAnalysis * _Nonnull ca; - SWIFT_IMPORT_UNSAFE - swift::CalleeList getCallees(BridgedValue callee) const; + struct CalleeList { + uint64_t storage[3]; - SWIFT_IMPORT_UNSAFE - swift::CalleeList getDestructors(swift::SILType type, bool isExactType) const; +#ifdef USED_IN_CPP_SOURCE + CalleeList(swift::CalleeList list) { + *reinterpret_cast(&storage) = list; + } + swift::CalleeList get() const { + return *reinterpret_cast(&storage); + } +#endif - SWIFT_IMPORT_UNSAFE - static BridgedFunction getCallee(swift::CalleeList cl, SwiftInt index) { - return {cl.get(index)}; - } + BRIDGED_INLINE bool isIncomplete() const; + BRIDGED_INLINE SwiftInt getCount() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getCallee(SwiftInt index) const; + }; + + SWIFT_IMPORT_UNSAFE CalleeList getCallees(BridgedValue callee) const; + SWIFT_IMPORT_UNSAFE CalleeList getDestructors(BridgedType type, bool isExactType) const; typedef bool (* _Nonnull IsDeinitBarrierFn)(BridgedInstruction, BridgedCalleeAnalysis bca); - typedef swift::MemoryBehavior (* _Nonnull GetMemBehvaiorFn)( + typedef BridgedMemoryBehavior (* _Nonnull GetMemBehvaiorFn)( BridgedInstruction apply, bool observeRetains, BridgedCalleeAnalysis bca); static void registerAnalysis(IsDeinitBarrierFn isDeinitBarrierFn, @@ -73,246 +107,120 @@ struct BridgedCalleeAnalysis { struct BridgedDeadEndBlocksAnalysis { swift::DeadEndBlocks * _Nonnull deb; - bool isDeadEnd(BridgedBasicBlock block) const { - return deb->isDeadEnd(block.getBlock()); - } + BRIDGED_INLINE bool isDeadEnd(BridgedBasicBlock block) const; }; struct BridgedDomTree { swift::DominanceInfo * _Nonnull di; - bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { - return di->dominates(dominating.getBlock(), dominated.getBlock()); - } + BRIDGED_INLINE bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; }; -struct BridgedBasicBlockSet { - swift::BasicBlockSet * _Nonnull set; - - bool contains(BridgedBasicBlock block) const { - return set->contains(block.getBlock()); - } +struct BridgedPostDomTree { + swift::PostDominanceInfo * _Nonnull pdi; - bool insert(BridgedBasicBlock block) const { - return set->insert(block.getBlock()); - } + BRIDGED_INLINE bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; +}; - void erase(BridgedBasicBlock block) const { - set->erase(block.getBlock()); - } +struct BridgedBasicBlockSet { + swift::BasicBlockSet * _Nonnull set; - SWIFT_IMPORT_UNSAFE - BridgedFunction getFunction() const { - return {set->getFunction()}; - } + BRIDGED_INLINE bool contains(BridgedBasicBlock block) const; + BRIDGED_INLINE bool insert(BridgedBasicBlock block) const; + BRIDGED_INLINE void erase(BridgedBasicBlock block) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; }; struct BridgedNodeSet { swift::NodeSet * _Nonnull set; - bool containsValue(BridgedValue value) const { - return set->contains(value.getSILValue()); - } - - bool insertValue(BridgedValue value) const { - return set->insert(value.getSILValue()); - } - - void eraseValue(BridgedValue value) const { - set->erase(value.getSILValue()); - } - - bool containsInstruction(BridgedInstruction inst) const { - return set->contains(inst.getInst()->asSILNode()); - } - - bool insertInstruction(BridgedInstruction inst) const { - return set->insert(inst.getInst()->asSILNode()); - } - - void eraseInstruction(BridgedInstruction inst) const { - set->erase(inst.getInst()->asSILNode()); - } - - SWIFT_IMPORT_UNSAFE - BridgedFunction getFunction() const { - return {set->getFunction()}; - } + BRIDGED_INLINE bool containsValue(BridgedValue value) const; + BRIDGED_INLINE bool insertValue(BridgedValue value) const; + BRIDGED_INLINE void eraseValue(BridgedValue value) const; + BRIDGED_INLINE bool containsInstruction(BridgedInstruction inst) const; + BRIDGED_INLINE bool insertInstruction(BridgedInstruction inst) const; + BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; }; -namespace swift { -class ClonerWithFixedLocation; -} - struct BridgedCloner { swift::ClonerWithFixedLocation * _Nonnull cloner; BridgedCloner(BridgedGlobalVar var, BridgedPassContext context); - BridgedCloner(BridgedInstruction inst, BridgedPassContext context); - void destroy(BridgedPassContext context); - - SWIFT_IMPORT_UNSAFE - BridgedValue getClonedValue(BridgedValue v); - + SWIFT_IMPORT_UNSAFE BridgedValue getClonedValue(BridgedValue v); bool isValueCloned(BridgedValue v) const; - void clone(BridgedInstruction inst); }; -struct BridgedPostDomTree { - swift::PostDominanceInfo * _Nonnull pdi; - - bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { - return pdi->dominates(dominating.getBlock(), dominated.getBlock()); - } -}; - struct BridgedPassContext { swift::SwiftPassInvocation * _Nonnull invocation; - std::string getModuleDescription() const; + enum class SILStage { + Raw, + Canonical, + Lowered + }; + + SWIFT_IMPORT_UNSAFE BridgedOwnedString getModuleDescription() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedChangeNotificationHandler asNotificationHandler() const; + BRIDGED_INLINE SILStage getSILStage() const; + BRIDGED_INLINE bool hadError() const; - SWIFT_IMPORT_UNSAFE - BridgedChangeNotificationHandler asNotificationHandler() const { - return {invocation}; - } // Analysis - SWIFT_IMPORT_UNSAFE - BridgedAliasAnalysis getAliasAnalysis() const { - return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedCalleeAnalysis getCalleeAnalysis() const { - return {invocation->getPassManager()->getAnalysis()}; - } - - bool hadError() const { - return invocation->getPassManager()->getModule()->getASTContext().hadError(); - } - - swift::SILStage getSILStage() const { - return invocation->getPassManager()->getModule()->getStage(); - } - - SWIFT_IMPORT_UNSAFE - BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const { - auto *dba = invocation->getPassManager()->getAnalysis(); - return {dba->get(invocation->getFunction())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedDomTree getDomTree() const { - auto *da = invocation->getPassManager()->getAnalysis(); - return {da->get(invocation->getFunction())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedPostDomTree getPostDomTree() const { - auto *pda = invocation->getPassManager()->getAnalysis(); - return {pda->get(invocation->getFunction())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedNominalTypeDecl getSwiftArrayDecl() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return {mod->getASTContext().getArrayDecl()}; - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedAliasAnalysis getAliasAnalysis() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCalleeAnalysis getCalleeAnalysis() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDomTree getDomTree() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedPostDomTree getPostDomTree() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getSwiftArrayDecl() const; // SIL modifications - SWIFT_IMPORT_UNSAFE - BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const { - auto *inst = bridgedInst.getInst(); - auto *block = inst->getParent(); - return {block->split(inst->getIterator())}; - } - - void eraseInstruction(BridgedInstruction inst) const { - invocation->eraseInstruction(inst.getInst()); - } - - void eraseBlock(BridgedBasicBlock block) const { - block.getBlock()->eraseFromParent(); - } - - bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; - - bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; - struct DevirtResult { OptionalBridgedInstruction newApply; bool cfgChanged; }; - SWIFT_IMPORT_UNSAFE - DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; - - SWIFT_IMPORT_UNSAFE - OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; - - SWIFT_IMPORT_UNSAFE - swift::SILVTable * _Nullable specializeVTableForType(swift::SILType type, BridgedFunction function) const; - + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const; + BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; + BRIDGED_INLINE void eraseBlock(BridgedBasicBlock block) const; + bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; + bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; + SWIFT_IMPORT_UNSAFE DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; + SWIFT_IMPORT_UNSAFE OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; + SWIFT_IMPORT_UNSAFE swift::SILVTable * _Nullable specializeVTableForType(BridgedType type, + BridgedFunction function) const; bool specializeClassMethodInst(BridgedInstruction cm) const; - bool specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const; - - std::string mangleOutlinedVariable(BridgedFunction function) const; - - std::string mangleAsyncRemoved(BridgedFunction function) const; - - SWIFT_IMPORT_UNSAFE - BridgedGlobalVar createGlobalVariable(llvm::StringRef name, swift::SILType type, bool isPrivate) const; - + SWIFT_IMPORT_UNSAFE BridgedOwnedString mangleOutlinedVariable(BridgedFunction function) const; + SWIFT_IMPORT_UNSAFE BridgedOwnedString mangleAsyncRemoved(BridgedFunction function) const; + SWIFT_IMPORT_UNSAFE BridgedGlobalVar createGlobalVariable(BridgedStringRef name, BridgedType type, + bool isPrivate) const; void inlineFunction(BridgedInstruction apply, bool mandatoryInline) const; - - SWIFT_IMPORT_UNSAFE - BridgedValue getSILUndef(swift::SILType type) const { - return {swift::SILUndef::get(type, *invocation->getFunction())}; - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getSILUndef(BridgedType type) const; + BRIDGED_INLINE static bool optimizeMemoryAccesses(BridgedFunction f); + BRIDGED_INLINE static bool eliminateDeadAllocations(BridgedFunction f); // IRGen - SwiftInt getStaticSize(swift::SILType type) const; - - SwiftInt getStaticAlignment(swift::SILType type) const; - - SwiftInt getStaticStride(swift::SILType type) const; + SwiftInt getStaticSize(BridgedType type) const; + SwiftInt getStaticAlignment(BridgedType type) const; + SwiftInt getStaticStride(BridgedType type) const; // Sets - SWIFT_IMPORT_UNSAFE - BridgedBasicBlockSet allocBasicBlockSet() const { - return {invocation->allocBlockSet()}; - } - - void freeBasicBlockSet(BridgedBasicBlockSet set) const { - invocation->freeBlockSet(set.set); - } - - SWIFT_IMPORT_UNSAFE - BridgedNodeSet allocNodeSet() const { - return {invocation->allocNodeSet()}; - } - - void freeNodeSet(BridgedNodeSet set) const { - invocation->freeNodeSet(set.set); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlockSet allocBasicBlockSet() const; + BRIDGED_INLINE void freeBasicBlockSet(BridgedBasicBlockSet set) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNodeSet allocNodeSet() const; + BRIDGED_INLINE void freeNodeSet(BridgedNodeSet set) const; // Stack nesting - void notifyInvalidatedStackNesting() const { - invocation->setNeedFixStackNesting(true); - } - - bool getNeedFixStackNesting() const { - return invocation->getNeedFixStackNesting(); - } - + BRIDGED_INLINE void notifyInvalidatedStackNesting() const; + BRIDGED_INLINE bool getNeedFixStackNesting() const; void fixStackNesting(BridgedFunction function) const; // Slabs @@ -320,216 +228,65 @@ struct BridgedPassContext { struct Slab { swift::FixedSizeSlabPayload * _Nullable data = nullptr; - static SwiftInt getCapacity() { - return (SwiftInt)swift::FixedSizeSlabPayload::capacity; - } - - Slab(swift::FixedSizeSlab * _Nullable slab) { - if (slab) { - data = slab; - assert((void *)data == slab->dataFor()); - } - } - - swift::FixedSizeSlab * _Nullable getSlab() const { - if (data) - return static_cast(data); - return nullptr; - } - - SWIFT_IMPORT_UNSAFE - Slab getNext() const { - return &*std::next(getSlab()->getIterator()); - } - - SWIFT_IMPORT_UNSAFE - Slab getPrevious() const { - return &*std::prev(getSlab()->getIterator()); - } + BRIDGED_INLINE static SwiftInt getCapacity(); + BRIDGED_INLINE Slab(swift::FixedSizeSlab * _Nullable slab); + BRIDGED_INLINE swift::FixedSizeSlab * _Nullable getSlab() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getNext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getPrevious() const; }; - SWIFT_IMPORT_UNSAFE - Slab allocSlab(Slab afterSlab) const { - return invocation->allocSlab(afterSlab.getSlab()); - } - - SWIFT_IMPORT_UNSAFE - Slab freeSlab(Slab slab) const { - return invocation->freeSlab(slab.getSlab()); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab allocSlab(Slab afterSlab) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab freeSlab(Slab slab) const; // Access SIL module data structures - SWIFT_IMPORT_UNSAFE - OptionalBridgedFunction getFirstFunctionInModule() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - if (mod->getFunctions().empty()) - return {nullptr}; - return {&*mod->getFunctions().begin()}; - } - - SWIFT_IMPORT_UNSAFE - static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function) { - auto *f = function.getFunction(); - auto nextIter = std::next(f->getIterator()); - if (nextIter == f->getModule().getFunctions().end()) - return {nullptr}; - return {&*nextIter}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedGlobalVar getFirstGlobalInModule() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - if (mod->getSILGlobals().empty()) - return {nullptr}; - return {&*mod->getSILGlobals().begin()}; - } - - SWIFT_IMPORT_UNSAFE - static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global) { - auto *g = global.getGlobal(); - auto nextIter = std::next(g->getIterator()); - if (nextIter == g->getModule().getSILGlobals().end()) - return {nullptr}; - return {&*nextIter}; - } - struct VTableArray { swift::SILVTable * const _Nonnull * _Nullable base; SwiftInt count; }; - SWIFT_IMPORT_UNSAFE - VTableArray getVTables() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - auto vTables = mod->getVTables(); - return {vTables.data(), (SwiftInt)vTables.size()}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedWitnessTable getFirstWitnessTableInModule() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - if (mod->getWitnessTables().empty()) - return {nullptr}; - return {&*mod->getWitnessTables().begin()}; - } - - SWIFT_IMPORT_UNSAFE - static OptionalBridgedWitnessTable getNextWitnessTableInModule(BridgedWitnessTable table) { - auto *t = table.table; - auto nextIter = std::next(t->getIterator()); - if (nextIter == t->getModule().getWitnessTables().end()) - return {nullptr}; - return {&*nextIter}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - if (mod->getDefaultWitnessTables().empty()) - return {nullptr}; - return {&*mod->getDefaultWitnessTables().begin()}; - } - - SWIFT_IMPORT_UNSAFE - static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { - auto *t = table.table; - auto nextIter = std::next(t->getIterator()); - if (nextIter == t->getModule().getDefaultWitnessTables().end()) - return {nullptr}; - return {&*nextIter}; - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedFunction loadFunction(llvm::StringRef name, bool loadCalleesRecursively) const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return {mod->loadFunction(name, loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll - : swift::SILModule::LinkingMode::LinkNormal)}; - } - - SWIFT_IMPORT_UNSAFE - void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - mod->loadFunction(function.getFunction(), - loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll - : swift::SILModule::LinkingMode::LinkNormal); - } - - SWIFT_IMPORT_UNSAFE - OptionalBridgedFunction lookupStdlibFunction(llvm::StringRef name) const; - - SWIFT_IMPORT_UNSAFE - swift::SubstitutionMap getContextSubstitutionMap(swift::SILType type) const { - auto *ntd = type.getASTType()->getAnyNominal(); - auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); - return type.getASTType()->getContextSubstitutionMap(mod, ntd); - } + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getFirstFunctionInModule() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function); + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedGlobalVar getFirstGlobalInModule() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global); + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE VTableArray getVTables() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedWitnessTable getFirstWitnessTableInModule() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedWitnessTable getNextWitnessTableInModule( + BridgedWitnessTable table); + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule( + BridgedDefaultWitnessTable table); + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction loadFunction(BridgedStringRef name, + bool loadCalleesRecursively) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const; + SWIFT_IMPORT_UNSAFE OptionalBridgedFunction lookupStdlibFunction(BridgedStringRef name) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap(BridgedType type) const; // Passmanager housekeeping - void beginTransformFunction(BridgedFunction function) const { - invocation->beginTransformFunction(function.getFunction()); - } - - void endTransformFunction() const { - invocation->endTransformFunction(); - } - - bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { - swift::SILPassManager *pm = invocation->getPassManager(); - return pm->continueWithNextSubpassRun(inst.getInst(), - invocation->getFunction(), - invocation->getTransform()); - } + BRIDGED_INLINE void beginTransformFunction(BridgedFunction function) const; + BRIDGED_INLINE void endTransformFunction() const; + BRIDGED_INLINE bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const; // SSAUpdater - void SSAUpdater_initialize(swift::SILType type, BridgedValue::Ownership ownership) const { - invocation->initializeSSAUpdater(type, castToOwnership(ownership)); - } - - void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { - invocation->getSSAUpdater()->addAvailableValue(block.getBlock(), value.getSILValue()); - } - - SWIFT_IMPORT_UNSAFE - BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { - return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.getBlock())}; - } - - SWIFT_IMPORT_UNSAFE - BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { - return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.getBlock())}; - } + BRIDGED_INLINE void SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const; + BRIDGED_INLINE void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const; // Options - bool enableStackProtection() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return mod->getOptions().EnableStackProtection; - } - - bool enableEmbeddedSwift() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); - } - - bool enableMoveInoutStackProtection() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return mod->getOptions().EnableMoveInoutStackProtection; - } - enum class AssertConfiguration { - Debug = swift::SILOptions::Debug, - Release = swift::SILOptions::Release, - Unchecked = swift::SILOptions::Unchecked + Debug = 0, + Release = 1, + Unchecked = 2 }; - AssertConfiguration getAssertConfiguration() const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - return (AssertConfiguration)mod->getOptions().AssertConfig; - } - + BRIDGED_INLINE bool enableStackProtection() const; + BRIDGED_INLINE bool enableEmbeddedSwift() const; + BRIDGED_INLINE bool enableMoveInoutStackProtection() const; + BRIDGED_INLINE AssertConfiguration getAssertConfiguration() const; bool enableSimplificationFor(BridgedInstruction inst) const; }; @@ -553,13 +310,18 @@ typedef void (* _Nonnull BridgedModulePassRunFn)(BridgedPassContext); typedef void (* _Nonnull BridgedFunctionPassRunFn)(BridgedFunctionPassCtxt); typedef void (* _Nonnull BridgedInstructionPassRunFn)(BridgedInstructionPassCtxt); -void SILPassManager_registerModulePass(llvm::StringRef name, +void SILPassManager_registerModulePass(BridgedStringRef name, BridgedModulePassRunFn runFn); -void SILPassManager_registerFunctionPass(llvm::StringRef name, +void SILPassManager_registerFunctionPass(BridgedStringRef name, BridgedFunctionPassRunFn runFn); -void SILCombine_registerInstructionPass(llvm::StringRef instClassName, +void SILCombine_registerInstructionPass(BridgedStringRef instClassName, BridgedInstructionPassRunFn runFn); +#ifndef PURE_BRIDGING_MODE +// In _not_ PURE_BRIDGING_MODE, briding functions are inlined and therefore inluded in the header file. +#include "OptimizerBridgingImpl.h" +#endif + SWIFT_END_NULLABILITY_ANNOTATIONS #endif diff --git a/include/swift/SILOptimizer/OptimizerBridgingImpl.h b/include/swift/SILOptimizer/OptimizerBridgingImpl.h new file mode 100644 index 0000000000000..798efc6ec576c --- /dev/null +++ b/include/swift/SILOptimizer/OptimizerBridgingImpl.h @@ -0,0 +1,405 @@ +//===--- OptimizerBridgingImpl.h ------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file contains the implementation of bridging functions, which are either +// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or +// in the header file. +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H +#define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H + +#include "swift/SILOptimizer/OptimizerBridging.h" +#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" +#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" +#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" +#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" +#include "swift/SILOptimizer/PassManager/PassManager.h" +#include "swift/SILOptimizer/Utils/InstOptUtils.h" + +SWIFT_BEGIN_NULLABILITY_ANNOTATIONS + +//===----------------------------------------------------------------------===// +// BridgedAliasAnalysis +//===----------------------------------------------------------------------===// + +BridgedMemoryBehavior BridgedAliasAnalysis::getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { + return (BridgedMemoryBehavior)aa->computeMemoryBehavior(inst.get(), addr.getSILValue()); +} + +//===----------------------------------------------------------------------===// +// BridgedCalleeAnalysis +//===----------------------------------------------------------------------===// + +static_assert(sizeof(BridgedCalleeAnalysis::CalleeList) >= sizeof(swift::CalleeList), + "BridgedCalleeAnalysis::CalleeList has wrong size"); + +bool BridgedCalleeAnalysis::CalleeList::isIncomplete() const { + return get().isIncomplete(); +} + +SwiftInt BridgedCalleeAnalysis::CalleeList::getCount() const { + return get().getCount(); +} + +BridgedFunction BridgedCalleeAnalysis::CalleeList::getCallee(SwiftInt index) const { + return {get().get((unsigned)index)}; +} + +//===----------------------------------------------------------------------===// +// BridgedDeadEndBlocksAnalysis +//===----------------------------------------------------------------------===// + +bool BridgedDeadEndBlocksAnalysis::isDeadEnd(BridgedBasicBlock block) const { + return deb->isDeadEnd(block.get()); +} + +//===----------------------------------------------------------------------===// +// BridgedDomTree, BridgedPostDomTree +//===----------------------------------------------------------------------===// + +bool BridgedDomTree::dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { + return di->dominates(dominating.get(), dominated.get()); +} + +bool BridgedPostDomTree::postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { + return pdi->dominates(dominating.get(), dominated.get()); +} + +//===----------------------------------------------------------------------===// +// BridgedBasicBlockSet +//===----------------------------------------------------------------------===// + +bool BridgedBasicBlockSet::contains(BridgedBasicBlock block) const { + return set->contains(block.get()); +} + +bool BridgedBasicBlockSet::insert(BridgedBasicBlock block) const { + return set->insert(block.get()); +} + +void BridgedBasicBlockSet::erase(BridgedBasicBlock block) const { + set->erase(block.get()); +} + +BridgedFunction BridgedBasicBlockSet::getFunction() const { + return {set->getFunction()}; +} + +//===----------------------------------------------------------------------===// +// BridgedNodeSet +//===----------------------------------------------------------------------===// + +bool BridgedNodeSet::containsValue(BridgedValue value) const { + return set->contains(value.getSILValue()); +} + +bool BridgedNodeSet::insertValue(BridgedValue value) const { + return set->insert(value.getSILValue()); +} + +void BridgedNodeSet::eraseValue(BridgedValue value) const { + set->erase(value.getSILValue()); +} + +bool BridgedNodeSet::containsInstruction(BridgedInstruction inst) const { + return set->contains(inst.get()->asSILNode()); +} + +bool BridgedNodeSet::insertInstruction(BridgedInstruction inst) const { + return set->insert(inst.get()->asSILNode()); +} + +void BridgedNodeSet::eraseInstruction(BridgedInstruction inst) const { + set->erase(inst.get()->asSILNode()); +} + +BridgedFunction BridgedNodeSet::getFunction() const { + return {set->getFunction()}; +} + +//===----------------------------------------------------------------------===// +// BridgedPassContext +//===----------------------------------------------------------------------===// + +BridgedChangeNotificationHandler BridgedPassContext::asNotificationHandler() const { + return {invocation}; +} + +BridgedPassContext::SILStage BridgedPassContext::getSILStage() const { + return (SILStage)invocation->getPassManager()->getModule()->getStage(); +} + +bool BridgedPassContext::hadError() const { + return invocation->getPassManager()->getModule()->getASTContext().hadError(); +} + +BridgedAliasAnalysis BridgedPassContext::getAliasAnalysis() const { + return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; +} + +BridgedCalleeAnalysis BridgedPassContext::getCalleeAnalysis() const { + return {invocation->getPassManager()->getAnalysis()}; +} + +BridgedDeadEndBlocksAnalysis BridgedPassContext::getDeadEndBlocksAnalysis() const { + auto *dba = invocation->getPassManager()->getAnalysis(); + return {dba->get(invocation->getFunction())}; +} + +BridgedDomTree BridgedPassContext::getDomTree() const { + auto *da = invocation->getPassManager()->getAnalysis(); + return {da->get(invocation->getFunction())}; +} + +BridgedPostDomTree BridgedPassContext::getPostDomTree() const { + auto *pda = invocation->getPassManager()->getAnalysis(); + return {pda->get(invocation->getFunction())}; +} + +BridgedNominalTypeDecl BridgedPassContext::getSwiftArrayDecl() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return {mod->getASTContext().getArrayDecl()}; +} + +// SIL modifications + +BridgedBasicBlock BridgedPassContext::splitBlock(BridgedInstruction bridgedInst) const { + auto *block = bridgedInst.get()->getParent(); + return {block->split(bridgedInst.get()->getIterator())}; +} + +void BridgedPassContext::eraseInstruction(BridgedInstruction inst) const { + invocation->eraseInstruction(inst.get()); +} + +void BridgedPassContext::eraseBlock(BridgedBasicBlock block) const { + block.get()->eraseFromParent(); +} + +BridgedValue BridgedPassContext::getSILUndef(BridgedType type) const { + return {swift::SILUndef::get(type.get(), *invocation->getFunction())}; +} + +bool BridgedPassContext::optimizeMemoryAccesses(BridgedFunction f) { + return swift::optimizeMemoryAccesses(f.getFunction()); +} +bool BridgedPassContext::eliminateDeadAllocations(BridgedFunction f) { + return swift::eliminateDeadAllocations(f.getFunction()); +} + +BridgedBasicBlockSet BridgedPassContext::allocBasicBlockSet() const { + return {invocation->allocBlockSet()}; +} + +void BridgedPassContext::freeBasicBlockSet(BridgedBasicBlockSet set) const { + invocation->freeBlockSet(set.set); +} + +BridgedNodeSet BridgedPassContext::allocNodeSet() const { + return {invocation->allocNodeSet()}; +} + +void BridgedPassContext::freeNodeSet(BridgedNodeSet set) const { + invocation->freeNodeSet(set.set); +} + +void BridgedPassContext::notifyInvalidatedStackNesting() const { + invocation->setNeedFixStackNesting(true); +} + +bool BridgedPassContext::getNeedFixStackNesting() const { + return invocation->getNeedFixStackNesting(); +} + +SwiftInt BridgedPassContext::Slab::getCapacity() { + return (SwiftInt)swift::FixedSizeSlabPayload::capacity; +} + +BridgedPassContext::Slab::Slab(swift::FixedSizeSlab * _Nullable slab) { + if (slab) { + data = slab; + assert((void *)data == slab->dataFor()); + } +} + +swift::FixedSizeSlab * _Nullable BridgedPassContext::Slab::getSlab() const { + if (data) + return static_cast(data); + return nullptr; +} + +BridgedPassContext::Slab BridgedPassContext::Slab::getNext() const { + return &*std::next(getSlab()->getIterator()); +} + +BridgedPassContext::Slab BridgedPassContext::Slab::getPrevious() const { + return &*std::prev(getSlab()->getIterator()); +} + +BridgedPassContext::Slab BridgedPassContext::allocSlab(Slab afterSlab) const { + return invocation->allocSlab(afterSlab.getSlab()); +} + +BridgedPassContext::Slab BridgedPassContext::freeSlab(Slab slab) const { + return invocation->freeSlab(slab.getSlab()); +} + +OptionalBridgedFunction BridgedPassContext::getFirstFunctionInModule() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + if (mod->getFunctions().empty()) + return {nullptr}; + return {&*mod->getFunctions().begin()}; +} + +OptionalBridgedFunction BridgedPassContext::getNextFunctionInModule(BridgedFunction function) { + auto *f = function.getFunction(); + auto nextIter = std::next(f->getIterator()); + if (nextIter == f->getModule().getFunctions().end()) + return {nullptr}; + return {&*nextIter}; +} + +OptionalBridgedGlobalVar BridgedPassContext::getFirstGlobalInModule() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + if (mod->getSILGlobals().empty()) + return {nullptr}; + return {&*mod->getSILGlobals().begin()}; +} + +OptionalBridgedGlobalVar BridgedPassContext::getNextGlobalInModule(BridgedGlobalVar global) { + auto *g = global.getGlobal(); + auto nextIter = std::next(g->getIterator()); + if (nextIter == g->getModule().getSILGlobals().end()) + return {nullptr}; + return {&*nextIter}; +} + +BridgedPassContext::VTableArray BridgedPassContext::getVTables() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + auto vTables = mod->getVTables(); + return {vTables.data(), (SwiftInt)vTables.size()}; +} + +OptionalBridgedWitnessTable BridgedPassContext::getFirstWitnessTableInModule() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + if (mod->getWitnessTables().empty()) + return {nullptr}; + return {&*mod->getWitnessTables().begin()}; +} + +OptionalBridgedWitnessTable BridgedPassContext::getNextWitnessTableInModule(BridgedWitnessTable table) { + auto *t = table.table; + auto nextIter = std::next(t->getIterator()); + if (nextIter == t->getModule().getWitnessTables().end()) + return {nullptr}; + return {&*nextIter}; +} + +OptionalBridgedDefaultWitnessTable BridgedPassContext::getFirstDefaultWitnessTableInModule() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + if (mod->getDefaultWitnessTables().empty()) + return {nullptr}; + return {&*mod->getDefaultWitnessTables().begin()}; +} + +OptionalBridgedDefaultWitnessTable BridgedPassContext:: +getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { + auto *t = table.table; + auto nextIter = std::next(t->getIterator()); + if (nextIter == t->getModule().getDefaultWitnessTables().end()) + return {nullptr}; + return {&*nextIter}; +} + +OptionalBridgedFunction BridgedPassContext::loadFunction(BridgedStringRef name, bool loadCalleesRecursively) const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return {mod->loadFunction(name.get(), + loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll + : swift::SILModule::LinkingMode::LinkNormal)}; +} + +void BridgedPassContext::loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + mod->loadFunction(function.getFunction(), + loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll + : swift::SILModule::LinkingMode::LinkNormal); +} + +BridgedSubstitutionMap BridgedPassContext::getContextSubstitutionMap(BridgedType type) const { + swift::SILType ty = type.get(); + auto *ntd = ty.getASTType()->getAnyNominal(); + auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); + return ty.getASTType()->getContextSubstitutionMap(mod, ntd); +} + +void BridgedPassContext::beginTransformFunction(BridgedFunction function) const { + invocation->beginTransformFunction(function.getFunction()); +} + +void BridgedPassContext::endTransformFunction() const { + invocation->endTransformFunction(); +} + +bool BridgedPassContext::continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { + swift::SILPassManager *pm = invocation->getPassManager(); + return pm->continueWithNextSubpassRun(inst.get(), invocation->getFunction(), invocation->getTransform()); +} + +void BridgedPassContext::SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const { + invocation->initializeSSAUpdater(type.get(), BridgedValue::castToOwnership(ownership)); +} + +void BridgedPassContext::SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { + invocation->getSSAUpdater()->addAvailableValue(block.get(), value.getSILValue()); +} + +BridgedValue BridgedPassContext::SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { + return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.get())}; +} + +BridgedValue BridgedPassContext::SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { + return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.get())}; +} + +bool BridgedPassContext::enableStackProtection() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return mod->getOptions().EnableStackProtection; +} + +bool BridgedPassContext::enableEmbeddedSwift() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); +} + +bool BridgedPassContext::enableMoveInoutStackProtection() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return mod->getOptions().EnableMoveInoutStackProtection; +} + +BridgedPassContext::AssertConfiguration BridgedPassContext::getAssertConfiguration() const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + return (AssertConfiguration)mod->getOptions().AssertConfig; +} + +static_assert((int)BridgedPassContext::SILStage::Raw == (int)swift::SILStage::Raw); +static_assert((int)BridgedPassContext::SILStage::Canonical == (int)swift::SILStage::Canonical); +static_assert((int)BridgedPassContext::SILStage::Lowered == (int)swift::SILStage::Lowered); + +static_assert((int)BridgedPassContext::AssertConfiguration::Debug == (int)swift::SILOptions::Debug); +static_assert((int)BridgedPassContext::AssertConfiguration::Release == (int)swift::SILOptions::Release); +static_assert((int)BridgedPassContext::AssertConfiguration::Unchecked == (int)swift::SILOptions::Unchecked); + +SWIFT_END_NULLABILITY_ANNOTATIONS + +#endif diff --git a/lib/AST/ASTBridging.cpp b/lib/AST/ASTBridging.cpp index 4b924f801637a..946cd335d2b6d 100644 --- a/lib/AST/ASTBridging.cpp +++ b/lib/AST/ASTBridging.cpp @@ -25,30 +25,53 @@ DiagnosticEngine *getDiagnosticEngine(const BridgedDiagnosticEngine &bridged) { } // namespace +static_assert(sizeof(BridgedDiagnosticArgument) >= sizeof(DiagnosticArgument), + "BridgedDiagnosticArgument has wrong size"); + +BridgedDiagnosticArgument::BridgedDiagnosticArgument(SwiftInt i) + : BridgedDiagnosticArgument(DiagnosticArgument((int)i)) {} + +BridgedDiagnosticArgument::BridgedDiagnosticArgument(BridgedStringRef s) + : BridgedDiagnosticArgument(DiagnosticArgument(s.get())) {} + +static_assert(sizeof(BridgedDiagnosticFixIt) >= sizeof(DiagnosticInfo::FixIt), + "BridgedDiagnosticArgument has wrong size"); + +static SourceLoc getSourceLoc(BridgedSourceLoc bridgedLoc) { + return SourceLoc(llvm::SMLoc::getFromPointer((const char *)bridgedLoc.opaquePointer)); +} + +BridgedDiagnosticFixIt::BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text) + : BridgedDiagnosticFixIt(DiagnosticInfo::FixIt( + CharSourceRange(getSourceLoc(start), length), + text.get(), + llvm::ArrayRef())) {} + void DiagnosticEngine_diagnose( - BridgedDiagnosticEngine bridgedEngine, SourceLoc loc, + BridgedDiagnosticEngine bridgedEngine, BridgedSourceLoc loc, BridgedDiagID bridgedDiagID, - BridgedArrayRef /*DiagnosticArgument*/ bridgedArguments, - CharSourceRange highlight, - BridgedArrayRef /*DiagnosticInfo::FixIt*/ bridgedFixIts) { + BridgedArrayRef /*BridgedDiagnosticArgument*/ bridgedArguments, + BridgedSourceLoc highlightStart, uint32_t hightlightLength, + BridgedArrayRef /*BridgedDiagnosticFixIt*/ bridgedFixIts) { auto *D = getDiagnosticEngine(bridgedEngine); auto diagID = static_cast(bridgedDiagID); SmallVector arguments; - for (auto arg : getArrayRef(bridgedArguments)) { - arguments.push_back(arg); + for (auto arg : getArrayRef(bridgedArguments)) { + arguments.push_back(arg.get()); } - auto inflight = D->diagnose(loc, diagID, arguments); + auto inflight = D->diagnose(SourceLoc(llvm::SMLoc::getFromPointer((const char *)loc.opaquePointer)), diagID, arguments); // Add highlight. - if (highlight.isValid()) { + if (highlightStart.isValid()) { + CharSourceRange highlight(getSourceLoc(highlightStart), (unsigned)hightlightLength); inflight.highlightChars(highlight.getStart(), highlight.getEnd()); } // Add fix-its. - for (auto fixIt : getArrayRef(bridgedFixIts)) { - auto range = fixIt.getRange(); - auto text = fixIt.getText(); + for (const BridgedDiagnosticFixIt &fixIt : getArrayRef(bridgedFixIts)) { + auto range = fixIt.get().getRange(); + auto text = fixIt.get().getText(); inflight.fixItReplaceChars(range.getStart(), range.getEnd(), text); } } diff --git a/lib/Basic/BasicBridging.cpp b/lib/Basic/BasicBridging.cpp index 9f9e9e03e1371..b9b9fe76717ca 100644 --- a/lib/Basic/BasicBridging.cpp +++ b/lib/Basic/BasicBridging.cpp @@ -16,10 +16,27 @@ using namespace swift; //===----------------------------------------------------------------------===// -// Bridging C functions +// BridgedStringRef //===----------------------------------------------------------------------===// -void OStream_write(BridgedOStream os, StringRef str) { - static_cast(os.streamAddr) - ->write(str.data(), str.size()); +void BridgedStringRef::write(BridgedOStream os) const { + static_cast(os.streamAddr)->write(data, length); } + +//===----------------------------------------------------------------------===// +// BridgedOwnedString +//===----------------------------------------------------------------------===// + +BridgedOwnedString::BridgedOwnedString(const std::string &stringToCopy) + : data(nullptr), length(stringToCopy.size()) { + if (length != 0) { + data = new char[length]; + std::memcpy(data, stringToCopy.data(), length); + } +} + +void BridgedOwnedString::destroy() const { + if (data) + delete [] data; +} + diff --git a/lib/Parse/ParseRegex.cpp b/lib/Parse/ParseRegex.cpp index 5ed804653d3e0..2b680142487ca 100644 --- a/lib/Parse/ParseRegex.cpp +++ b/lib/Parse/ParseRegex.cpp @@ -44,7 +44,7 @@ ParserResult Parser::parseExprRegexLiteral() { regexLiteralParsingFn(regexText.str().c_str(), &version, /*captureStructureOut*/ capturesBuf.data(), /*captureStructureSize*/ capturesBuf.size(), - /*diagBaseLoc*/ Tok.getLoc(), + /*diagBaseLoc*/ {(const uint8_t *)(Tok.getLoc().getOpaquePointerValue())}, getBridgedDiagnosticEngine(&Diags)); auto loc = consumeToken(); SourceMgr.recordRegexLiteralStartLoc(loc); diff --git a/lib/SIL/IR/SILBasicBlock.cpp b/lib/SIL/IR/SILBasicBlock.cpp index b94fcc7f376f9..2810e8331b442 100644 --- a/lib/SIL/IR/SILBasicBlock.cpp +++ b/lib/SIL/IR/SILBasicBlock.cpp @@ -19,7 +19,6 @@ #include "swift/SIL/DebugUtils.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SIL/SILBuilder.h" -#include "swift/SIL/SILBridging.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILDebugScope.h" #include "swift/SIL/SILFunction.h" diff --git a/lib/SIL/IR/SILFunction.cpp b/lib/SIL/IR/SILFunction.cpp index 5c97ac25581f9..201b27edf7fff 100644 --- a/lib/SIL/IR/SILFunction.cpp +++ b/lib/SIL/IR/SILFunction.cpp @@ -985,9 +985,14 @@ void BridgedFunction::registerBridging(SwiftMetatype metatype, std::pair SILFunction:: parseArgumentEffectsFromSource(StringRef effectStr, ArrayRef paramNames) { if (parseFunction) { + llvm::SmallVector bridgedParamNames; + for (StringRef paramName : paramNames) { + bridgedParamNames.push_back(paramName); + } + ArrayRef bridgedParamNameArray = bridgedParamNames; auto error = parseFunction( {this}, effectStr, BridgedFunction::ParseEffectsMode::argumentEffectsFromSource, -1, - {(const unsigned char *)paramNames.data(), paramNames.size()}); + {(const unsigned char *)bridgedParamNameArray.data(), bridgedParamNameArray.size()}); return {(const char *)error.message, (int)error.position}; } return {nullptr, 0}; diff --git a/lib/SIL/IR/SILLocation.cpp b/lib/SIL/IR/SILLocation.cpp index ad6feba56f5ff..cfaa988038277 100644 --- a/lib/SIL/IR/SILLocation.cpp +++ b/lib/SIL/IR/SILLocation.cpp @@ -337,21 +337,3 @@ ImplicitReturnLocation::ImplicitReturnLocation(SILLocation L) L.isASTNode() || L.isNull()); } - -std::string SILDebugLocation::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - SILLocation loc = getLocation(); - loc.print(os); -#ifndef NDEBUG - if (const SILDebugScope *scope = getScope()) { - if (DeclContext *dc = loc.getAsDeclContext()) { - os << ", scope="; - scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); - } else { - os << ", scope=?"; - } - } -#endif - return str; -} diff --git a/lib/SIL/Utils/SILBridging.cpp b/lib/SIL/Utils/SILBridging.cpp index 53a64dc58cf7f..09df933170136 100644 --- a/lib/SIL/Utils/SILBridging.cpp +++ b/lib/SIL/Utils/SILBridging.cpp @@ -1,8 +1,8 @@ -//===--- SILBridgingUtils.cpp - Utilities for swift bridging --------------===// +//===--- SILBridging.cpp --------------------------------------------------===// // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -11,10 +11,15 @@ //===----------------------------------------------------------------------===// #include "swift/SIL/SILBridging.h" + +#ifdef PURE_BRIDGING_MODE +// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. +#include "swift/SIL/SILBridgingImpl.h" +#endif + #include "swift/AST/Attr.h" #include "swift/AST/SemanticAttrs.h" #include "swift/Basic/BridgingUtils.h" -#include "swift/SIL/ApplySite.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/ParseTestSpecification.h" #include "swift/SIL/SILBuilder.h" @@ -22,6 +27,8 @@ #include "swift/SIL/SILNode.h" #include "swift/SIL/Test.h" #include +#include +#include using namespace swift; @@ -63,7 +70,8 @@ static void setUnimplementedRange(SwiftMetatype metatype, /// Registers the metatype of a swift SIL class. /// Called by initializeSwiftModules(). -void registerBridgedClass(StringRef className, SwiftMetatype metatype) { +void registerBridgedClass(BridgedStringRef bridgedClassName, SwiftMetatype metatype) { + StringRef className = bridgedClassName.get(); nodeMetatypesInitialized = true; // Handle the important non Node classes. @@ -133,15 +141,15 @@ void registerBridgedClass(StringRef className, SwiftMetatype metatype) { // Test //===----------------------------------------------------------------------===// -void registerFunctionTest(llvm::StringRef name, void *nativeSwiftInvocation) { - new swift::test::FunctionTest(name, nativeSwiftInvocation); +void registerFunctionTest(BridgedStringRef name, void *nativeSwiftInvocation) { + new swift::test::FunctionTest(name.get(), nativeSwiftInvocation); } bool BridgedTestArguments::hasUntaken() const { return arguments->hasUntaken(); } -llvm::StringRef BridgedTestArguments::takeString() const { +BridgedStringRef BridgedTestArguments::takeString() const { return arguments->takeString(); } @@ -173,11 +181,39 @@ BridgedFunction BridgedTestArguments::takeFunction() const { return {arguments->takeFunction()}; } +//===----------------------------------------------------------------------===// +// SILType +//===----------------------------------------------------------------------===// + +static_assert((int)BridgedType::MetatypeRepresentation::Thin == (int)swift::MetatypeRepresentation::Thin); +static_assert((int)BridgedType::MetatypeRepresentation::Thick == (int)swift::MetatypeRepresentation::Thick); +static_assert((int)BridgedType::MetatypeRepresentation::ObjC == (int)swift::MetatypeRepresentation::ObjC); + +static_assert((int)BridgedType::TraitResult::IsNot == (int)swift::TypeTraitResult::IsNot); +static_assert((int)BridgedType::TraitResult::CanBe == (int)swift::TypeTraitResult::CanBe); +static_assert((int)BridgedType::TraitResult::Is == (int)swift::TypeTraitResult::Is); + + //===----------------------------------------------------------------------===// // SILFunction //===----------------------------------------------------------------------===// -std::string BridgedFunction::getDebugDescription() const { +static_assert((int)BridgedFunction::EffectsKind::ReadNone == (int)swift::EffectsKind::ReadNone); +static_assert((int)BridgedFunction::EffectsKind::ReadOnly == (int)swift::EffectsKind::ReadOnly); +static_assert((int)BridgedFunction::EffectsKind::ReleaseNone == (int)swift::EffectsKind::ReleaseNone); +static_assert((int)BridgedFunction::EffectsKind::ReadWrite == (int)swift::EffectsKind::ReadWrite); +static_assert((int)BridgedFunction::EffectsKind::Unspecified == (int)swift::EffectsKind::Unspecified); +static_assert((int)BridgedFunction::EffectsKind::Custom == (int)swift::EffectsKind::Custom); + +static_assert((int)BridgedFunction::PerformanceConstraints::None == (int)swift::PerformanceConstraints::None); +static_assert((int)BridgedFunction::PerformanceConstraints::NoAllocation == (int)swift::PerformanceConstraints::NoAllocation); +static_assert((int)BridgedFunction::PerformanceConstraints::NoLocks == (int)swift::PerformanceConstraints::NoLocks); + +static_assert((int)BridgedFunction::InlineStrategy::InlineDefault == (int)swift::InlineDefault); +static_assert((int)BridgedFunction::InlineStrategy::NoInline == (int)swift::NoInline); +static_assert((int)BridgedFunction::InlineStrategy::AlwaysInline == (int)swift::AlwaysInline); + +BridgedOwnedString BridgedFunction::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); getFunction()->print(os); @@ -189,10 +225,10 @@ std::string BridgedFunction::getDebugDescription() const { // SILBasicBlock //===----------------------------------------------------------------------===// -std::string BridgedBasicBlock::getDebugDescription() const { +BridgedOwnedString BridgedBasicBlock::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); - getBlock()->print(os); + get()->print(os); str.pop_back(); // Remove trailing newline. return str; } @@ -201,7 +237,7 @@ std::string BridgedBasicBlock::getDebugDescription() const { // SILValue //===----------------------------------------------------------------------===// -std::string BridgedValue::getDebugDescription() const { +BridgedOwnedString BridgedValue::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); getSILValue()->print(os); @@ -230,11 +266,30 @@ ArrayRef BridgedValueArray::getValues(SmallVectorImpl &stora return storage; } + +//===----------------------------------------------------------------------===// +// SILArgument +//===----------------------------------------------------------------------===// + +static_assert((int)BridgedArgumentConvention::Indirect_In == (int)swift::SILArgumentConvention::Indirect_In); +static_assert((int)BridgedArgumentConvention::Indirect_In_Guaranteed == (int)swift::SILArgumentConvention::Indirect_In_Guaranteed); +static_assert((int)BridgedArgumentConvention::Indirect_Inout == (int)swift::SILArgumentConvention::Indirect_Inout); +static_assert((int)BridgedArgumentConvention::Indirect_InoutAliasable == (int)swift::SILArgumentConvention::Indirect_InoutAliasable); +static_assert((int)BridgedArgumentConvention::Indirect_Out == (int)swift::SILArgumentConvention::Indirect_Out); +static_assert((int)BridgedArgumentConvention::Direct_Owned == (int)swift::SILArgumentConvention::Direct_Owned); +static_assert((int)BridgedArgumentConvention::Direct_Unowned == (int)swift::SILArgumentConvention::Direct_Unowned); +static_assert((int)BridgedArgumentConvention::Direct_Guaranteed == (int)swift::SILArgumentConvention::Direct_Guaranteed); +static_assert((int)BridgedArgumentConvention::Pack_Owned == (int)swift::SILArgumentConvention::Pack_Owned); +static_assert((int)BridgedArgumentConvention::Pack_Inout == (int)swift::SILArgumentConvention::Pack_Inout); +static_assert((int)BridgedArgumentConvention::Pack_Guaranteed == (int)swift::SILArgumentConvention::Pack_Guaranteed); +static_assert((int)BridgedArgumentConvention::Pack_Out == (int)swift::SILArgumentConvention::Pack_Out); + + //===----------------------------------------------------------------------===// // SILGlobalVariable //===----------------------------------------------------------------------===// -std::string BridgedGlobalVar::getDebugDescription() const { +BridgedOwnedString BridgedGlobalVar::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); getGlobal()->print(os); @@ -263,7 +318,7 @@ bool BridgedGlobalVar::mustBeInitializedStatically() const { // SILVTable //===----------------------------------------------------------------------===// -std::string BridgedVTable::getDebugDescription() const { +BridgedOwnedString BridgedVTable::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); vTable->print(os); @@ -271,7 +326,7 @@ std::string BridgedVTable::getDebugDescription() const { return str; } -std::string BridgedVTableEntry::getDebugDescription() const { +BridgedOwnedString BridgedVTableEntry::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); entry->print(os); @@ -283,15 +338,21 @@ std::string BridgedVTableEntry::getDebugDescription() const { // SILVWitnessTable, SILDefaultWitnessTable //===----------------------------------------------------------------------===// -std::string BridgedWitnessTableEntry::getDebugDescription() const { +static_assert((int)BridgedWitnessTableEntry::Kind::Invalid == (int)swift::SILWitnessTable::WitnessKind::Invalid); +static_assert((int)BridgedWitnessTableEntry::Kind::Method == (int)swift::SILWitnessTable::WitnessKind::Method); +static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedType == (int)swift::SILWitnessTable::WitnessKind::AssociatedType); +static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedTypeProtocol == (int)swift::SILWitnessTable::WitnessKind::AssociatedTypeProtocol); +static_assert((int)BridgedWitnessTableEntry::Kind::BaseProtocol == (int)swift::SILWitnessTable::WitnessKind::BaseProtocol); + +BridgedOwnedString BridgedWitnessTableEntry::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); - entry->print(os, /*verbose=*/ false, PrintOptions::printSIL()); + getEntry()->print(os, /*verbose=*/ false, PrintOptions::printSIL()); str.pop_back(); // Remove trailing newline. return str; } -std::string BridgedWitnessTable::getDebugDescription() const { +BridgedOwnedString BridgedWitnessTable::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); table->print(os); @@ -299,7 +360,7 @@ std::string BridgedWitnessTable::getDebugDescription() const { return str; } -std::string BridgedDefaultWitnessTable::getDebugDescription() const { +BridgedOwnedString BridgedDefaultWitnessTable::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); table->print(os); @@ -307,32 +368,76 @@ std::string BridgedDefaultWitnessTable::getDebugDescription() const { return str; } +//===----------------------------------------------------------------------===// +// SubstitutionMap +//===----------------------------------------------------------------------===// + +static_assert(sizeof(BridgedSubstitutionMap) >= sizeof(swift::SubstitutionMap), + "BridgedSubstitutionMap has wrong size"); + + +//===----------------------------------------------------------------------===// +// SILDebugLocation +//===----------------------------------------------------------------------===// + +static_assert(sizeof(BridgedLocation) >= sizeof(swift::SILDebugLocation), + "BridgedLocation has wrong size"); + +BridgedOwnedString BridgedLocation::getDebugDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + SILLocation loc = getLoc().getLocation(); + loc.print(os); +#ifndef NDEBUG + if (const SILDebugScope *scope = getLoc().getScope()) { + if (DeclContext *dc = loc.getAsDeclContext()) { + os << ", scope="; + scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); + } else { + os << ", scope=?"; + } + } +#endif + return str; +} + //===----------------------------------------------------------------------===// // SILInstruction //===----------------------------------------------------------------------===// -std::string BridgedInstruction::getDebugDescription() const { +static_assert((int)BridgedMemoryBehavior::None == (int)swift::MemoryBehavior::None); +static_assert((int)BridgedMemoryBehavior::MayRead == (int)swift::MemoryBehavior::MayRead); +static_assert((int)BridgedMemoryBehavior::MayWrite == (int)swift::MemoryBehavior::MayWrite); +static_assert((int)BridgedMemoryBehavior::MayReadWrite == (int)swift::MemoryBehavior::MayReadWrite); +static_assert((int)BridgedMemoryBehavior::MayHaveSideEffects == (int)swift::MemoryBehavior::MayHaveSideEffects); + +static_assert((int)BridgedInstruction::AccessKind::Init == (int)swift::SILAccessKind::Init); +static_assert((int)BridgedInstruction::AccessKind::Read == (int)swift::SILAccessKind::Read); +static_assert((int)BridgedInstruction::AccessKind::Modify == (int)swift::SILAccessKind::Modify); +static_assert((int)BridgedInstruction::AccessKind::Deinit == (int)swift::SILAccessKind::Deinit); + +BridgedOwnedString BridgedInstruction::getDebugDescription() const { std::string str; llvm::raw_string_ostream os(str); - getInst()->print(os); + get()->print(os); str.pop_back(); // Remove trailing newline. return str; } bool BridgedInstruction::mayAccessPointer() const { - return ::mayAccessPointer(getInst()); + return ::mayAccessPointer(get()); } bool BridgedInstruction::mayLoadWeakOrUnowned() const { - return ::mayLoadWeakOrUnowned(getInst()); + return ::mayLoadWeakOrUnowned(get()); } bool BridgedInstruction::maySynchronizeNotConsideringSideEffects() const { - return ::maySynchronizeNotConsideringSideEffects(getInst()); + return ::maySynchronizeNotConsideringSideEffects(get()); } bool BridgedInstruction::mayBeDeinitBarrierNotConsideringSideEffects() const { - return ::mayBeDeinitBarrierNotConsideringSideEffects(getInst()); + return ::mayBeDeinitBarrierNotConsideringSideEffects(get()); } //===----------------------------------------------------------------------===// @@ -345,3 +450,7 @@ bool BridgedNominalTypeDecl::isStructWithUnreferenceableStorage() const { } return false; } + +void writeCharToStderr(int c) { + putc(c, stderr); +} diff --git a/lib/SILOptimizer/PassManager/PassManager.cpp b/lib/SILOptimizer/PassManager/PassManager.cpp index 36338c5f4d5dc..e5b117533e6ad 100644 --- a/lib/SILOptimizer/PassManager/PassManager.cpp +++ b/lib/SILOptimizer/PassManager/PassManager.cpp @@ -19,27 +19,15 @@ #include "swift/Demangling/Demangle.h" #include "../../IRGen/IRGenModule.h" #include "swift/SIL/ApplySite.h" -#include "swift/SIL/SILCloner.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILModule.h" -#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" -#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" #include "swift/SILOptimizer/Analysis/FunctionOrder.h" -#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" -#include "swift/SILOptimizer/OptimizerBridging.h" #include "swift/SILOptimizer/PassManager/PrettyStackTrace.h" #include "swift/SILOptimizer/PassManager/Transforms.h" -#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h" -#include "swift/SILOptimizer/Utils/ConstantFolding.h" -#include "swift/SILOptimizer/Utils/CFGOptUtils.h" -#include "swift/SILOptimizer/Utils/Devirtualize.h" #include "swift/SILOptimizer/Utils/OptimizerStatsUtils.h" #include "swift/SILOptimizer/Utils/SILInliner.h" #include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" -#include "swift/SILOptimizer/Utils/StackNesting.h" -#include "swift/SILOptimizer/Utils/SpecializationMangler.h" -#include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringSwitch.h" @@ -152,10 +140,6 @@ llvm::cl::opt SILForceVerifyAll( llvm::cl::desc("For all passes, precompute analyses before the pass and " "verify analyses after the pass")); -llvm::cl::list - SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, - llvm::cl::desc("Simplify instruction of specified kind(s)")); - static llvm::ManagedStatic> DebugPassNumbers; namespace { @@ -1439,304 +1423,3 @@ SwiftPassInvocation::~SwiftPassInvocation() { irgen = nullptr; } } - -//===----------------------------------------------------------------------===// -// Swift Bridging -//===----------------------------------------------------------------------===// - -void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { - switch (changeKind) { - case Kind::instructionsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); - break; - case Kind::callsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::CallsAndInstructions); - break; - case Kind::branchesChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); - break; - case Kind::effectsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Effects); - break; - } -} - -std::string BridgedPassContext::getModuleDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - invocation->getPassManager()->getModule()->print(os); - str.pop_back(); // Remove trailing newline. - return str; -} - -bool BridgedPassContext::tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const { - auto *pa = closure.getAs(); - SILBuilder builder(pa); - return ::tryOptimizeApplyOfPartialApply(pa, builder.getBuilderContext(), InstModCallbacks()); -} - -bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const { - return ::tryDeleteDeadClosure(closure.getAs(), InstModCallbacks(), needKeepArgsAlive); -} - -BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, - bool isMandatory) const { - auto cha = invocation->getPassManager()->getAnalysis(); - auto result = ::tryDevirtualizeApply(ApplySite(apply.getInst()), cha, nullptr, isMandatory); - if (result.first) { - OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); - return {newApply, result.second}; - } - return {{nullptr}, false}; -} - -OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction builtin) const { - auto bi = builtin.getAs(); - llvm::Optional resultsInError; - return {::constantFoldBuiltin(bi, resultsInError)}; -} - -void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { - SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); - InstructionDeleter deleter; - SILInliner::inlineFullApply(FullApplySite(apply.getInst()), - mandatoryInline ? SILInliner::InlineKind::MandatoryInline - : SILInliner::InlineKind::PerformanceInline, - funcBuilder, - deleter); -} - -static const irgen::TypeInfo &getTypeInfoOfBuiltin(swift::SILType type, irgen::IRGenModule &IGM) { - SILType lowered = IGM.getLoweredType(swift::Lowering::AbstractionPattern::getOpaque(), type.getASTType()); - return IGM.getTypeInfo(lowered); -} - -static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { - auto *intConst = dyn_cast_or_null(c); - if (!intConst) - return -1; - APInt value = intConst->getValue(); - return value.getLimitedValue() + add; -} - -SwiftInt BridgedPassContext::getStaticSize(swift::SILType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type, *IGM); - llvm::Constant *c = ti.getStaticSize(*IGM); - return integerValueFromConstant(c); -} - -SwiftInt BridgedPassContext::getStaticAlignment(swift::SILType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type, *IGM); - llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); - return integerValueFromConstant(c, 1); -} - -SwiftInt BridgedPassContext::getStaticStride(swift::SILType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type, *IGM); - llvm::Constant *c = ti.getStaticStride(*IGM); - return integerValueFromConstant(c); -} - -swift::SILVTable * BridgedPassContext::specializeVTableForType(swift::SILType type, BridgedFunction function) const { - return ::specializeVTableForType(type, function.getFunction()->getModule(), invocation->getTransform()); -} - -bool BridgedPassContext::specializeClassMethodInst(BridgedInstruction cm) const { - return ::specializeClassMethodInst(cm.getAs()); -} - -bool BridgedPassContext::specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const { - return ::specializeAppliesInFunction(*function.getFunction(), invocation->getTransform(), isMandatory); -} - -namespace { -class GlobalVariableMangler : public Mangle::ASTMangler { -public: - std::string mangleOutlinedVariable(SILFunction *F, int &uniqueIdx) { - std::string GlobName; - do { - beginManglingWithoutPrefix(); - appendOperator(F->getName()); - appendOperator("Tv", Index(uniqueIdx++)); - GlobName = finalize(); - } while (F->getModule().lookUpGlobalVariable(GlobName)); - - return GlobName; - } -}; -} // namespace - -std::string BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { - int idx = 0; - SILFunction *f = function.getFunction(); - SILModule &mod = f->getModule(); - while (true) { - GlobalVariableMangler mangler; - std::string name = mangler.mangleOutlinedVariable(f, idx); - if (!mod.lookUpGlobalVariable(name)) - return name; - idx++; - } -} - -std::string BridgedPassContext::mangleAsyncRemoved(BridgedFunction function) const { - SILFunction *F = function.getFunction(); - - // FIXME: hard assumption on what pass is requesting this. - auto P = Demangle::SpecializationPass::AsyncDemotion; - - Mangle::FunctionSignatureSpecializationMangler Mangler(P, F->isSerialized(), - F); - Mangler.setRemovedEffect(EffectKind::Async); - return Mangler.mangle(); -} - -BridgedGlobalVar BridgedPassContext::createGlobalVariable(StringRef name, SILType type, bool isPrivate) const { - return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), - isPrivate ? SILLinkage::Private : SILLinkage::Public, - IsNotSerialized, - name, type)}; -} - -void BridgedPassContext::fixStackNesting(BridgedFunction function) const { - switch (StackNesting::fixNesting(function.getFunction())) { - case StackNesting::Changes::None: - break; - case StackNesting::Changes::Instructions: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); - break; - case StackNesting::Changes::CFG: - invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); - break; - } - invocation->setNeedFixStackNesting(false); -} - -OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(llvm::StringRef name) const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - SmallVector results; - mod->getASTContext().lookupInSwiftModule(name, results); - if (results.size() != 1) - return {nullptr}; - - auto *decl = dyn_cast(results.front()); - if (!decl) - return {nullptr}; - - SILDeclRef declRef(decl, SILDeclRef::Kind::Func); - SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); - return {funcBuilder.getOrCreateFunction(SILLocation(decl), declRef, NotForDefinition)}; -} - -bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const { - // Fast-path check. - if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) - return true; - - StringRef instName = getSILInstructionName(inst.getInst()->getKind()); - - if (SILPassManager::isInstructionPassDisabled(instName)) - return false; - - if (SimplifyInstructionTest.empty()) - return true; - - for (const std::string &testName : SimplifyInstructionTest) { - if (testName == instName) - return true; - } - return false; -} - -bool FullApplySite_canInline(BridgedInstruction apply) { - return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.getInst())); -} - -// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 -CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { - return ca->getCalleeListOfValue(callee.getSILValue()); -} - -// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 -CalleeList BridgedCalleeAnalysis::getDestructors(SILType type, bool isExactType) const { - return ca->getDestructors(type, isExactType); -} - -// Need to put ClonerWithFixedLocation into namespace swift to forward reference -// it in OptimizerBridging.h. -namespace swift { - -class ClonerWithFixedLocation : public SILCloner { - friend class SILInstructionVisitor; - friend class SILCloner; - - SILDebugLocation insertLoc; - -public: - ClonerWithFixedLocation(SILGlobalVariable *gVar) - : SILCloner(gVar), - insertLoc(ArtificialUnreachableLocation(), nullptr) {} - - ClonerWithFixedLocation(SILInstruction *insertionPoint) - : SILCloner(*insertionPoint->getFunction()), - insertLoc(insertionPoint->getDebugLocation()) { - Builder.setInsertionPoint(insertionPoint); - } - - SILValue getClonedValue(SILValue v) { - return getMappedValue(v); - } - - void cloneInst(SILInstruction *inst) { - visit(inst); - } - -protected: - - SILLocation remapLocation(SILLocation loc) { - return insertLoc.getLocation(); - } - - const SILDebugScope *remapScope(const SILDebugScope *DS) { - return insertLoc.getScope(); - } -}; - -} // namespace swift - -BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) - : cloner(new ClonerWithFixedLocation(var.getGlobal())) { - context.invocation->notifyNewCloner(); -} - -BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) - : cloner(new ClonerWithFixedLocation(inst.getInst())) { - context.invocation->notifyNewCloner(); -} - -void BridgedCloner::destroy(BridgedPassContext context) { - delete cloner; - cloner = nullptr; - context.invocation->notifyClonerDestroyed(); -} - -BridgedValue BridgedCloner::getClonedValue(BridgedValue v) { - return {cloner->getClonedValue(v.getSILValue())}; -} - -bool BridgedCloner::isValueCloned(BridgedValue v) const { - return cloner->isValueCloned(v.getSILValue()); -} - -void BridgedCloner::clone(BridgedInstruction inst) { - cloner->cloneInst(inst.getInst()); -} diff --git a/lib/SILOptimizer/PassManager/Passes.cpp b/lib/SILOptimizer/PassManager/Passes.cpp index 7f04f625a47bf..e28b6bbb6d8e5 100644 --- a/lib/SILOptimizer/PassManager/Passes.cpp +++ b/lib/SILOptimizer/PassManager/Passes.cpp @@ -274,15 +274,15 @@ static void runBridgedFunctionPass(BridgedFunctionPassRunFn &runFunction, } // Called from initializeSwiftModules(). -void SILPassManager_registerModulePass(llvm::StringRef name, +void SILPassManager_registerModulePass(BridgedStringRef name, BridgedModulePassRunFn runFn) { - bridgedModulePassRunFunctions[name] = runFn; + bridgedModulePassRunFunctions[name.get()] = runFn; passesRegistered = true; } -void SILPassManager_registerFunctionPass(llvm::StringRef name, +void SILPassManager_registerFunctionPass(BridgedStringRef name, BridgedFunctionPassRunFn runFn) { - bridgedFunctionPassRunFunctions[name] = runFn; + bridgedFunctionPassRunFunctions[name.get()] = runFn; passesRegistered = true; } diff --git a/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/lib/SILOptimizer/SILCombiner/SILCombine.cpp index 599855125c9f8..0959b8733a937 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombine.cpp +++ b/lib/SILOptimizer/SILCombiner/SILCombine.cpp @@ -540,9 +540,9 @@ static llvm::StringMap swiftInstPasses; static bool passesRegistered = false; // Called from initializeSwiftModules(). -void SILCombine_registerInstructionPass(llvm::StringRef instClassName, +void SILCombine_registerInstructionPass(BridgedStringRef instClassName, BridgedInstructionPassRunFn runFn) { - swiftInstPasses[instClassName] = runFn; + swiftInstPasses[instClassName.get()] = runFn; passesRegistered = true; } diff --git a/lib/SILOptimizer/Utils/CMakeLists.txt b/lib/SILOptimizer/Utils/CMakeLists.txt index efca12eb257fd..69a89febf591d 100644 --- a/lib/SILOptimizer/Utils/CMakeLists.txt +++ b/lib/SILOptimizer/Utils/CMakeLists.txt @@ -22,6 +22,7 @@ target_sources(swiftSILOptimizer PRIVATE LexicalDestroyHoisting.cpp LoopUtils.cpp OptimizerStatsUtils.cpp + OptimizerBridging.cpp PartialApplyCombiner.cpp PerformanceInlinerUtils.cpp ShrinkBorrowScope.cpp diff --git a/lib/SILOptimizer/Utils/OptimizerBridging.cpp b/lib/SILOptimizer/Utils/OptimizerBridging.cpp new file mode 100644 index 0000000000000..4bba8da29f09b --- /dev/null +++ b/lib/SILOptimizer/Utils/OptimizerBridging.cpp @@ -0,0 +1,332 @@ +//===--- SILBridging.cpp --------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#ifdef PURE_BRIDGING_MODE +// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. +#include "swift/SILOptimizer/OptimizerBridgingImpl.h" +#endif + +#include "swift/SILOptimizer/OptimizerBridging.h" +#include "swift/SIL/SILCloner.h" +#include "swift/SILOptimizer/Utils/Devirtualize.h" +#include "swift/SILOptimizer/Utils/ConstantFolding.h" +#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" +#include "swift/SILOptimizer/Utils/SILInliner.h" +#include "swift/SILOptimizer/Utils/SpecializationMangler.h" +#include "swift/SILOptimizer/Utils/StackNesting.h" +#include "../../IRGen/IRGenModule.h" + +using namespace swift; + +extern llvm::cl::list SILDisablePass; + +llvm::cl::list + SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, + llvm::cl::desc("Simplify instruction of specified kind(s)")); + +void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { + switch (changeKind) { + case Kind::instructionsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); + break; + case Kind::callsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::CallsAndInstructions); + break; + case Kind::branchesChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); + break; + case Kind::effectsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Effects); + break; + } +} + +BridgedOwnedString BridgedPassContext::getModuleDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + invocation->getPassManager()->getModule()->print(os); + str.pop_back(); // Remove trailing newline. + return str; +} + +bool BridgedPassContext::tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const { + auto *pa = closure.getAs(); + SILBuilder builder(pa); + return ::tryOptimizeApplyOfPartialApply(pa, builder.getBuilderContext(), InstModCallbacks()); +} + +bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const { + return ::tryDeleteDeadClosure(closure.getAs(), InstModCallbacks(), needKeepArgsAlive); +} + +BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, + bool isMandatory) const { + auto cha = invocation->getPassManager()->getAnalysis(); + auto result = ::tryDevirtualizeApply(ApplySite(apply.get()), cha, nullptr, isMandatory); + if (result.first) { + OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); + return {newApply, result.second}; + } + return {{nullptr}, false}; +} + +OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction builtin) const { + auto bi = builtin.getAs(); + llvm::Optional resultsInError; + return {::constantFoldBuiltin(bi, resultsInError)}; +} + +void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { + SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); + InstructionDeleter deleter; + SILInliner::inlineFullApply(FullApplySite(apply.get()), + mandatoryInline ? SILInliner::InlineKind::MandatoryInline + : SILInliner::InlineKind::PerformanceInline, + funcBuilder, + deleter); +} + +static const irgen::TypeInfo &getTypeInfoOfBuiltin(swift::SILType type, irgen::IRGenModule &IGM) { + SILType lowered = IGM.getLoweredType(swift::Lowering::AbstractionPattern::getOpaque(), type.getASTType()); + return IGM.getTypeInfo(lowered); +} + +static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { + auto *intConst = dyn_cast_or_null(c); + if (!intConst) + return -1; + APInt value = intConst->getValue(); + return value.getLimitedValue() + add; +} + +SwiftInt BridgedPassContext::getStaticSize(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticSize(*IGM); + return integerValueFromConstant(c); +} + +SwiftInt BridgedPassContext::getStaticAlignment(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); + return integerValueFromConstant(c, 1); +} + +SwiftInt BridgedPassContext::getStaticStride(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticStride(*IGM); + return integerValueFromConstant(c); +} + +swift::SILVTable * BridgedPassContext::specializeVTableForType(BridgedType type, BridgedFunction function) const { + return ::specializeVTableForType(type.get(), function.getFunction()->getModule(), invocation->getTransform()); +} + +bool BridgedPassContext::specializeClassMethodInst(BridgedInstruction cm) const { + return ::specializeClassMethodInst(cm.getAs()); +} + +bool BridgedPassContext::specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const { + return ::specializeAppliesInFunction(*function.getFunction(), invocation->getTransform(), isMandatory); +} + +namespace { +class GlobalVariableMangler : public Mangle::ASTMangler { +public: + std::string mangleOutlinedVariable(SILFunction *F, int &uniqueIdx) { + std::string GlobName; + do { + beginManglingWithoutPrefix(); + appendOperator(F->getName()); + appendOperator("Tv", Index(uniqueIdx++)); + GlobName = finalize(); + } while (F->getModule().lookUpGlobalVariable(GlobName)); + + return GlobName; + } +}; +} // namespace + +BridgedOwnedString BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { + int idx = 0; + SILFunction *f = function.getFunction(); + SILModule &mod = f->getModule(); + while (true) { + GlobalVariableMangler mangler; + std::string name = mangler.mangleOutlinedVariable(f, idx); + if (!mod.lookUpGlobalVariable(name)) + return name; + idx++; + } +} + +BridgedOwnedString BridgedPassContext::mangleAsyncRemoved(BridgedFunction function) const { + SILFunction *F = function.getFunction(); + + // FIXME: hard assumption on what pass is requesting this. + auto P = Demangle::SpecializationPass::AsyncDemotion; + + Mangle::FunctionSignatureSpecializationMangler Mangler(P, F->isSerialized(), + F); + Mangler.setRemovedEffect(EffectKind::Async); + return Mangler.mangle(); +} + +BridgedGlobalVar BridgedPassContext::createGlobalVariable(BridgedStringRef name, BridgedType type, bool isPrivate) const { + return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), + isPrivate ? SILLinkage::Private : SILLinkage::Public, + IsNotSerialized, + name.get(), type.get())}; +} + +void BridgedPassContext::fixStackNesting(BridgedFunction function) const { + switch (StackNesting::fixNesting(function.getFunction())) { + case StackNesting::Changes::None: + break; + case StackNesting::Changes::Instructions: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); + break; + case StackNesting::Changes::CFG: + invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); + break; + } + invocation->setNeedFixStackNesting(false); +} + +OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(BridgedStringRef name) const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + SmallVector results; + mod->getASTContext().lookupInSwiftModule(name.get(), results); + if (results.size() != 1) + return {nullptr}; + + auto *decl = dyn_cast(results.front()); + if (!decl) + return {nullptr}; + + SILDeclRef declRef(decl, SILDeclRef::Kind::Func); + SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); + return {funcBuilder.getOrCreateFunction(SILLocation(decl), declRef, NotForDefinition)}; +} + +bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const { + // Fast-path check. + if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) + return true; + + StringRef instName = getSILInstructionName(inst.get()->getKind()); + + if (SILPassManager::isInstructionPassDisabled(instName)) + return false; + + if (SimplifyInstructionTest.empty()) + return true; + + for (const std::string &testName : SimplifyInstructionTest) { + if (testName == instName) + return true; + } + return false; +} + +bool FullApplySite_canInline(BridgedInstruction apply) { + return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.get())); +} + +// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { + return ca->getCalleeListOfValue(callee.getSILValue()); +} + +// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getDestructors(BridgedType type, bool isExactType) const { + return ca->getDestructors(type.get(), isExactType); +} + +// Need to put ClonerWithFixedLocation into namespace swift to forward reference +// it in OptimizerBridging.h. +namespace swift { + +class ClonerWithFixedLocation : public SILCloner { + friend class SILInstructionVisitor; + friend class SILCloner; + + SILDebugLocation insertLoc; + +public: + ClonerWithFixedLocation(SILGlobalVariable *gVar) + : SILCloner(gVar), + insertLoc(ArtificialUnreachableLocation(), nullptr) {} + + ClonerWithFixedLocation(SILInstruction *insertionPoint) + : SILCloner(*insertionPoint->getFunction()), + insertLoc(insertionPoint->getDebugLocation()) { + Builder.setInsertionPoint(insertionPoint); + } + + SILValue getClonedValue(SILValue v) { + return getMappedValue(v); + } + + void cloneInst(SILInstruction *inst) { + visit(inst); + } + +protected: + + SILLocation remapLocation(SILLocation loc) { + return insertLoc.getLocation(); + } + + const SILDebugScope *remapScope(const SILDebugScope *DS) { + return insertLoc.getScope(); + } +}; + +} // namespace swift + +BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) + : cloner(new ClonerWithFixedLocation(var.getGlobal())) { + context.invocation->notifyNewCloner(); +} + +BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) + : cloner(new ClonerWithFixedLocation(inst.get())) { + context.invocation->notifyNewCloner(); +} + +void BridgedCloner::destroy(BridgedPassContext context) { + delete cloner; + cloner = nullptr; + context.invocation->notifyClonerDestroyed(); +} + +BridgedValue BridgedCloner::getClonedValue(BridgedValue v) { + return {cloner->getClonedValue(v.getSILValue())}; +} + +bool BridgedCloner::isValueCloned(BridgedValue v) const { + return cloner->isValueCloned(v.getSILValue()); +} + +void BridgedCloner::clone(BridgedInstruction inst) { + cloner->cloneInst(inst.get()); +} + From 3a0f63583040a2040d09385e17a2e2a07e956a1e Mon Sep 17 00:00:00 2001 From: Erik Eckstein Date: Mon, 9 Oct 2023 10:10:20 +0200 Subject: [PATCH 3/3] Move the optimizer bridging back to PassManager.cpp Putting it into a separate source file OptimizerBridging.cpp caused linker errors for sourcekitd-test in sourcekit tests on linux. --- .../swift/SILOptimizer/OptimizerBridging.h | 4 +- lib/SILOptimizer/PassManager/PassManager.cpp | 317 +++++++++++++++++ lib/SILOptimizer/Utils/CMakeLists.txt | 1 - lib/SILOptimizer/Utils/OptimizerBridging.cpp | 332 ------------------ 4 files changed, 319 insertions(+), 335 deletions(-) delete mode 100644 lib/SILOptimizer/Utils/OptimizerBridging.cpp diff --git a/include/swift/SILOptimizer/OptimizerBridging.h b/include/swift/SILOptimizer/OptimizerBridging.h index 49b961af66f55..e9474979ea101 100644 --- a/include/swift/SILOptimizer/OptimizerBridging.h +++ b/include/swift/SILOptimizer/OptimizerBridging.h @@ -14,8 +14,8 @@ #define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H // Do not add other C++/llvm/swift header files here! -// Function implementations should be placed into OptimizerBridgingImpl.h or OptimizerBridging.cpp and -// required header files should be added there. +// Function implementations should be placed into OptimizerBridgingImpl.h or PassManager.cpp +// (under OptimizerBridging) andrequired header files should be added there. // #include "swift/SIL/SILBridging.h" diff --git a/lib/SILOptimizer/PassManager/PassManager.cpp b/lib/SILOptimizer/PassManager/PassManager.cpp index e5b117533e6ad..0ab769e100a3a 100644 --- a/lib/SILOptimizer/PassManager/PassManager.cpp +++ b/lib/SILOptimizer/PassManager/PassManager.cpp @@ -19,15 +19,21 @@ #include "swift/Demangling/Demangle.h" #include "../../IRGen/IRGenModule.h" #include "swift/SIL/ApplySite.h" +#include "swift/SIL/SILCloner.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" #include "swift/SILOptimizer/Analysis/FunctionOrder.h" +#include "swift/SILOptimizer/OptimizerBridging.h" #include "swift/SILOptimizer/PassManager/PrettyStackTrace.h" #include "swift/SILOptimizer/PassManager/Transforms.h" +#include "swift/SILOptimizer/Utils/Devirtualize.h" +#include "swift/SILOptimizer/Utils/ConstantFolding.h" #include "swift/SILOptimizer/Utils/OptimizerStatsUtils.h" #include "swift/SILOptimizer/Utils/SILInliner.h" #include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" +#include "swift/SILOptimizer/Utils/SpecializationMangler.h" +#include "swift/SILOptimizer/Utils/StackNesting.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringSwitch.h" @@ -1423,3 +1429,314 @@ SwiftPassInvocation::~SwiftPassInvocation() { irgen = nullptr; } } + +//===----------------------------------------------------------------------===// +// OptimizerBridging +//===----------------------------------------------------------------------===// + +llvm::cl::list + SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, + llvm::cl::desc("Simplify instruction of specified kind(s)")); + +#ifdef PURE_BRIDGING_MODE +// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. +#include "swift/SILOptimizer/OptimizerBridgingImpl.h" +#endif + +void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { + switch (changeKind) { + case Kind::instructionsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); + break; + case Kind::callsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::CallsAndInstructions); + break; + case Kind::branchesChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); + break; + case Kind::effectsChanged: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Effects); + break; + } +} + +BridgedOwnedString BridgedPassContext::getModuleDescription() const { + std::string str; + llvm::raw_string_ostream os(str); + invocation->getPassManager()->getModule()->print(os); + str.pop_back(); // Remove trailing newline. + return str; +} + +bool BridgedPassContext::tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const { + auto *pa = closure.getAs(); + SILBuilder builder(pa); + return ::tryOptimizeApplyOfPartialApply(pa, builder.getBuilderContext(), InstModCallbacks()); +} + +bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const { + return ::tryDeleteDeadClosure(closure.getAs(), InstModCallbacks(), needKeepArgsAlive); +} + +BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, + bool isMandatory) const { + auto cha = invocation->getPassManager()->getAnalysis(); + auto result = ::tryDevirtualizeApply(ApplySite(apply.get()), cha, nullptr, isMandatory); + if (result.first) { + OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); + return {newApply, result.second}; + } + return {{nullptr}, false}; +} + +OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction builtin) const { + auto bi = builtin.getAs(); + llvm::Optional resultsInError; + return {::constantFoldBuiltin(bi, resultsInError)}; +} + +void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { + SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); + InstructionDeleter deleter; + SILInliner::inlineFullApply(FullApplySite(apply.get()), + mandatoryInline ? SILInliner::InlineKind::MandatoryInline + : SILInliner::InlineKind::PerformanceInline, + funcBuilder, + deleter); +} + +static const irgen::TypeInfo &getTypeInfoOfBuiltin(swift::SILType type, irgen::IRGenModule &IGM) { + SILType lowered = IGM.getLoweredType(swift::Lowering::AbstractionPattern::getOpaque(), type.getASTType()); + return IGM.getTypeInfo(lowered); +} + +static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { + auto *intConst = dyn_cast_or_null(c); + if (!intConst) + return -1; + APInt value = intConst->getValue(); + return value.getLimitedValue() + add; +} + +SwiftInt BridgedPassContext::getStaticSize(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticSize(*IGM); + return integerValueFromConstant(c); +} + +SwiftInt BridgedPassContext::getStaticAlignment(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); + return integerValueFromConstant(c, 1); +} + +SwiftInt BridgedPassContext::getStaticStride(BridgedType type) const { + irgen::IRGenModule *IGM = invocation->getIRGenModule(); + if (!IGM) + return -1; + auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); + llvm::Constant *c = ti.getStaticStride(*IGM); + return integerValueFromConstant(c); +} + +swift::SILVTable * BridgedPassContext::specializeVTableForType(BridgedType type, BridgedFunction function) const { + return ::specializeVTableForType(type.get(), function.getFunction()->getModule(), invocation->getTransform()); +} + +bool BridgedPassContext::specializeClassMethodInst(BridgedInstruction cm) const { + return ::specializeClassMethodInst(cm.getAs()); +} + +bool BridgedPassContext::specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const { + return ::specializeAppliesInFunction(*function.getFunction(), invocation->getTransform(), isMandatory); +} + +namespace { +class GlobalVariableMangler : public Mangle::ASTMangler { +public: + std::string mangleOutlinedVariable(SILFunction *F, int &uniqueIdx) { + std::string GlobName; + do { + beginManglingWithoutPrefix(); + appendOperator(F->getName()); + appendOperator("Tv", Index(uniqueIdx++)); + GlobName = finalize(); + } while (F->getModule().lookUpGlobalVariable(GlobName)); + + return GlobName; + } +}; +} // namespace + +BridgedOwnedString BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { + int idx = 0; + SILFunction *f = function.getFunction(); + SILModule &mod = f->getModule(); + while (true) { + GlobalVariableMangler mangler; + std::string name = mangler.mangleOutlinedVariable(f, idx); + if (!mod.lookUpGlobalVariable(name)) + return name; + idx++; + } +} + +BridgedOwnedString BridgedPassContext::mangleAsyncRemoved(BridgedFunction function) const { + SILFunction *F = function.getFunction(); + + // FIXME: hard assumption on what pass is requesting this. + auto P = Demangle::SpecializationPass::AsyncDemotion; + + Mangle::FunctionSignatureSpecializationMangler Mangler(P, F->isSerialized(), + F); + Mangler.setRemovedEffect(EffectKind::Async); + return Mangler.mangle(); +} + +BridgedGlobalVar BridgedPassContext::createGlobalVariable(BridgedStringRef name, BridgedType type, bool isPrivate) const { + return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), + isPrivate ? SILLinkage::Private : SILLinkage::Public, + IsNotSerialized, + name.get(), type.get())}; +} + +void BridgedPassContext::fixStackNesting(BridgedFunction function) const { + switch (StackNesting::fixNesting(function.getFunction())) { + case StackNesting::Changes::None: + break; + case StackNesting::Changes::Instructions: + invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); + break; + case StackNesting::Changes::CFG: + invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); + break; + } + invocation->setNeedFixStackNesting(false); +} + +OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(BridgedStringRef name) const { + swift::SILModule *mod = invocation->getPassManager()->getModule(); + SmallVector results; + mod->getASTContext().lookupInSwiftModule(name.get(), results); + if (results.size() != 1) + return {nullptr}; + + auto *decl = dyn_cast(results.front()); + if (!decl) + return {nullptr}; + + SILDeclRef declRef(decl, SILDeclRef::Kind::Func); + SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); + return {funcBuilder.getOrCreateFunction(SILLocation(decl), declRef, NotForDefinition)}; +} + +bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const { + // Fast-path check. + if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) + return true; + + StringRef instName = getSILInstructionName(inst.get()->getKind()); + + if (SILPassManager::isInstructionPassDisabled(instName)) + return false; + + if (SimplifyInstructionTest.empty()) + return true; + + for (const std::string &testName : SimplifyInstructionTest) { + if (testName == instName) + return true; + } + return false; +} + +bool FullApplySite_canInline(BridgedInstruction apply) { + return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.get())); +} + +// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { + return ca->getCalleeListOfValue(callee.getSILValue()); +} + +// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 +BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getDestructors(BridgedType type, bool isExactType) const { + return ca->getDestructors(type.get(), isExactType); +} + +// Need to put ClonerWithFixedLocation into namespace swift to forward reference +// it in OptimizerBridging.h. +namespace swift { + +class ClonerWithFixedLocation : public SILCloner { + friend class SILInstructionVisitor; + friend class SILCloner; + + SILDebugLocation insertLoc; + +public: + ClonerWithFixedLocation(SILGlobalVariable *gVar) + : SILCloner(gVar), + insertLoc(ArtificialUnreachableLocation(), nullptr) {} + + ClonerWithFixedLocation(SILInstruction *insertionPoint) + : SILCloner(*insertionPoint->getFunction()), + insertLoc(insertionPoint->getDebugLocation()) { + Builder.setInsertionPoint(insertionPoint); + } + + SILValue getClonedValue(SILValue v) { + return getMappedValue(v); + } + + void cloneInst(SILInstruction *inst) { + visit(inst); + } + +protected: + + SILLocation remapLocation(SILLocation loc) { + return insertLoc.getLocation(); + } + + const SILDebugScope *remapScope(const SILDebugScope *DS) { + return insertLoc.getScope(); + } +}; + +} // namespace swift + +BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) + : cloner(new ClonerWithFixedLocation(var.getGlobal())) { + context.invocation->notifyNewCloner(); +} + +BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) + : cloner(new ClonerWithFixedLocation(inst.get())) { + context.invocation->notifyNewCloner(); +} + +void BridgedCloner::destroy(BridgedPassContext context) { + delete cloner; + cloner = nullptr; + context.invocation->notifyClonerDestroyed(); +} + +BridgedValue BridgedCloner::getClonedValue(BridgedValue v) { + return {cloner->getClonedValue(v.getSILValue())}; +} + +bool BridgedCloner::isValueCloned(BridgedValue v) const { + return cloner->isValueCloned(v.getSILValue()); +} + +void BridgedCloner::clone(BridgedInstruction inst) { + cloner->cloneInst(inst.get()); +} + diff --git a/lib/SILOptimizer/Utils/CMakeLists.txt b/lib/SILOptimizer/Utils/CMakeLists.txt index 69a89febf591d..efca12eb257fd 100644 --- a/lib/SILOptimizer/Utils/CMakeLists.txt +++ b/lib/SILOptimizer/Utils/CMakeLists.txt @@ -22,7 +22,6 @@ target_sources(swiftSILOptimizer PRIVATE LexicalDestroyHoisting.cpp LoopUtils.cpp OptimizerStatsUtils.cpp - OptimizerBridging.cpp PartialApplyCombiner.cpp PerformanceInlinerUtils.cpp ShrinkBorrowScope.cpp diff --git a/lib/SILOptimizer/Utils/OptimizerBridging.cpp b/lib/SILOptimizer/Utils/OptimizerBridging.cpp deleted file mode 100644 index 4bba8da29f09b..0000000000000 --- a/lib/SILOptimizer/Utils/OptimizerBridging.cpp +++ /dev/null @@ -1,332 +0,0 @@ -//===--- SILBridging.cpp --------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#ifdef PURE_BRIDGING_MODE -// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. -#include "swift/SILOptimizer/OptimizerBridgingImpl.h" -#endif - -#include "swift/SILOptimizer/OptimizerBridging.h" -#include "swift/SIL/SILCloner.h" -#include "swift/SILOptimizer/Utils/Devirtualize.h" -#include "swift/SILOptimizer/Utils/ConstantFolding.h" -#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" -#include "swift/SILOptimizer/Utils/SILInliner.h" -#include "swift/SILOptimizer/Utils/SpecializationMangler.h" -#include "swift/SILOptimizer/Utils/StackNesting.h" -#include "../../IRGen/IRGenModule.h" - -using namespace swift; - -extern llvm::cl::list SILDisablePass; - -llvm::cl::list - SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, - llvm::cl::desc("Simplify instruction of specified kind(s)")); - -void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { - switch (changeKind) { - case Kind::instructionsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); - break; - case Kind::callsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::CallsAndInstructions); - break; - case Kind::branchesChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); - break; - case Kind::effectsChanged: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Effects); - break; - } -} - -BridgedOwnedString BridgedPassContext::getModuleDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - invocation->getPassManager()->getModule()->print(os); - str.pop_back(); // Remove trailing newline. - return str; -} - -bool BridgedPassContext::tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const { - auto *pa = closure.getAs(); - SILBuilder builder(pa); - return ::tryOptimizeApplyOfPartialApply(pa, builder.getBuilderContext(), InstModCallbacks()); -} - -bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const { - return ::tryDeleteDeadClosure(closure.getAs(), InstModCallbacks(), needKeepArgsAlive); -} - -BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, - bool isMandatory) const { - auto cha = invocation->getPassManager()->getAnalysis(); - auto result = ::tryDevirtualizeApply(ApplySite(apply.get()), cha, nullptr, isMandatory); - if (result.first) { - OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); - return {newApply, result.second}; - } - return {{nullptr}, false}; -} - -OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction builtin) const { - auto bi = builtin.getAs(); - llvm::Optional resultsInError; - return {::constantFoldBuiltin(bi, resultsInError)}; -} - -void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { - SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); - InstructionDeleter deleter; - SILInliner::inlineFullApply(FullApplySite(apply.get()), - mandatoryInline ? SILInliner::InlineKind::MandatoryInline - : SILInliner::InlineKind::PerformanceInline, - funcBuilder, - deleter); -} - -static const irgen::TypeInfo &getTypeInfoOfBuiltin(swift::SILType type, irgen::IRGenModule &IGM) { - SILType lowered = IGM.getLoweredType(swift::Lowering::AbstractionPattern::getOpaque(), type.getASTType()); - return IGM.getTypeInfo(lowered); -} - -static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { - auto *intConst = dyn_cast_or_null(c); - if (!intConst) - return -1; - APInt value = intConst->getValue(); - return value.getLimitedValue() + add; -} - -SwiftInt BridgedPassContext::getStaticSize(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticSize(*IGM); - return integerValueFromConstant(c); -} - -SwiftInt BridgedPassContext::getStaticAlignment(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); - return integerValueFromConstant(c, 1); -} - -SwiftInt BridgedPassContext::getStaticStride(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; - auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticStride(*IGM); - return integerValueFromConstant(c); -} - -swift::SILVTable * BridgedPassContext::specializeVTableForType(BridgedType type, BridgedFunction function) const { - return ::specializeVTableForType(type.get(), function.getFunction()->getModule(), invocation->getTransform()); -} - -bool BridgedPassContext::specializeClassMethodInst(BridgedInstruction cm) const { - return ::specializeClassMethodInst(cm.getAs()); -} - -bool BridgedPassContext::specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const { - return ::specializeAppliesInFunction(*function.getFunction(), invocation->getTransform(), isMandatory); -} - -namespace { -class GlobalVariableMangler : public Mangle::ASTMangler { -public: - std::string mangleOutlinedVariable(SILFunction *F, int &uniqueIdx) { - std::string GlobName; - do { - beginManglingWithoutPrefix(); - appendOperator(F->getName()); - appendOperator("Tv", Index(uniqueIdx++)); - GlobName = finalize(); - } while (F->getModule().lookUpGlobalVariable(GlobName)); - - return GlobName; - } -}; -} // namespace - -BridgedOwnedString BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { - int idx = 0; - SILFunction *f = function.getFunction(); - SILModule &mod = f->getModule(); - while (true) { - GlobalVariableMangler mangler; - std::string name = mangler.mangleOutlinedVariable(f, idx); - if (!mod.lookUpGlobalVariable(name)) - return name; - idx++; - } -} - -BridgedOwnedString BridgedPassContext::mangleAsyncRemoved(BridgedFunction function) const { - SILFunction *F = function.getFunction(); - - // FIXME: hard assumption on what pass is requesting this. - auto P = Demangle::SpecializationPass::AsyncDemotion; - - Mangle::FunctionSignatureSpecializationMangler Mangler(P, F->isSerialized(), - F); - Mangler.setRemovedEffect(EffectKind::Async); - return Mangler.mangle(); -} - -BridgedGlobalVar BridgedPassContext::createGlobalVariable(BridgedStringRef name, BridgedType type, bool isPrivate) const { - return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), - isPrivate ? SILLinkage::Private : SILLinkage::Public, - IsNotSerialized, - name.get(), type.get())}; -} - -void BridgedPassContext::fixStackNesting(BridgedFunction function) const { - switch (StackNesting::fixNesting(function.getFunction())) { - case StackNesting::Changes::None: - break; - case StackNesting::Changes::Instructions: - invocation->notifyChanges(SILAnalysis::InvalidationKind::Instructions); - break; - case StackNesting::Changes::CFG: - invocation->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions); - break; - } - invocation->setNeedFixStackNesting(false); -} - -OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(BridgedStringRef name) const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - SmallVector results; - mod->getASTContext().lookupInSwiftModule(name.get(), results); - if (results.size() != 1) - return {nullptr}; - - auto *decl = dyn_cast(results.front()); - if (!decl) - return {nullptr}; - - SILDeclRef declRef(decl, SILDeclRef::Kind::Func); - SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); - return {funcBuilder.getOrCreateFunction(SILLocation(decl), declRef, NotForDefinition)}; -} - -bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const { - // Fast-path check. - if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) - return true; - - StringRef instName = getSILInstructionName(inst.get()->getKind()); - - if (SILPassManager::isInstructionPassDisabled(instName)) - return false; - - if (SimplifyInstructionTest.empty()) - return true; - - for (const std::string &testName : SimplifyInstructionTest) { - if (testName == instName) - return true; - } - return false; -} - -bool FullApplySite_canInline(BridgedInstruction apply) { - return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.get())); -} - -// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 -BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { - return ca->getCalleeListOfValue(callee.getSILValue()); -} - -// TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 -BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getDestructors(BridgedType type, bool isExactType) const { - return ca->getDestructors(type.get(), isExactType); -} - -// Need to put ClonerWithFixedLocation into namespace swift to forward reference -// it in OptimizerBridging.h. -namespace swift { - -class ClonerWithFixedLocation : public SILCloner { - friend class SILInstructionVisitor; - friend class SILCloner; - - SILDebugLocation insertLoc; - -public: - ClonerWithFixedLocation(SILGlobalVariable *gVar) - : SILCloner(gVar), - insertLoc(ArtificialUnreachableLocation(), nullptr) {} - - ClonerWithFixedLocation(SILInstruction *insertionPoint) - : SILCloner(*insertionPoint->getFunction()), - insertLoc(insertionPoint->getDebugLocation()) { - Builder.setInsertionPoint(insertionPoint); - } - - SILValue getClonedValue(SILValue v) { - return getMappedValue(v); - } - - void cloneInst(SILInstruction *inst) { - visit(inst); - } - -protected: - - SILLocation remapLocation(SILLocation loc) { - return insertLoc.getLocation(); - } - - const SILDebugScope *remapScope(const SILDebugScope *DS) { - return insertLoc.getScope(); - } -}; - -} // namespace swift - -BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) - : cloner(new ClonerWithFixedLocation(var.getGlobal())) { - context.invocation->notifyNewCloner(); -} - -BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) - : cloner(new ClonerWithFixedLocation(inst.get())) { - context.invocation->notifyNewCloner(); -} - -void BridgedCloner::destroy(BridgedPassContext context) { - delete cloner; - cloner = nullptr; - context.invocation->notifyClonerDestroyed(); -} - -BridgedValue BridgedCloner::getClonedValue(BridgedValue v) { - return {cloner->getClonedValue(v.getSILValue())}; -} - -bool BridgedCloner::isValueCloned(BridgedValue v) const { - return cloner->isValueCloned(v.getSILValue()); -} - -void BridgedCloner::clone(BridgedInstruction inst) { - cloner->cloneInst(inst.get()); -} -