From bf82b36e9036dad5981412dcc05fe966a0ddfb28 Mon Sep 17 00:00:00 2001 From: "stack-file[bot]" <147888899+stack-file[bot]@users.noreply.github.com> Date: Sat, 20 Jan 2024 09:58:30 +0100 Subject: [PATCH 01/38] Create tech stack docs (techstack.yml and techstack.md) (#1) * Create techstack.yml * Create techstack.md --------- Co-authored-by: stacksharebot --- techstack.md | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++ techstack.yml | 53 ++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 techstack.md create mode 100644 techstack.yml diff --git a/techstack.md b/techstack.md new file mode 100644 index 0000000..015e4bf --- /dev/null +++ b/techstack.md @@ -0,0 +1,80 @@ + +
+ +# Tech Stack File +![](https://img.stackshare.io/repo.svg "repo") [mrLSD/llvm-codegen](https://github.com/mrLSD/llvm-codegen)![](https://img.stackshare.io/public_badge.svg "public") +

+|4
Tools used|01/20/24
Report generated| +|------|------| +
+ +## Languages (2) + + + + + + +
+ C lang +
+ C lang +
+ +
+ Swift +
+ Swift +
+ +
+ +## DevOps (2) + + + + + + +
+ Git +
+ Git +
+ +
+ GitHub Actions +
+ GitHub Actions +
+ +
+ +
+
+ +Generated via [Stack File](https://github.com/marketplace/stack-file) diff --git a/techstack.yml b/techstack.yml new file mode 100644 index 0000000..5a3f6ae --- /dev/null +++ b/techstack.yml @@ -0,0 +1,53 @@ +repo_name: mrLSD/llvm-codegen +report_id: a41b946dc26669f61269f027fe8e228c +version: 0.1 +repo_type: Public +timestamp: '2024-01-20T08:48:50+00:00' +requested_by: mrLSD +provider: github +branch: master +detected_tools_count: 4 +tools: +- name: C lang + description: One of the most widely used programming languages of all time + website_url: http://en.wikipedia.org/wiki/C_(programming_language) + open_source: true + hosted_saas: false + category: Languages & Frameworks + sub_category: Languages + image_url: https://img.stackshare.io/no-img-open-source.png + detection_source_url: https://github.com/mrLSD/llvm-codegen + detection_source: Repo Metadata +- name: Swift + description: 'An innovative new programming language for Cocoa and Cocoa Touch. ' + website_url: https://developer.apple.com/swift/ + license: Apache-2.0 + open_source: true + hosted_saas: false + category: Languages & Frameworks + sub_category: Languages + image_url: https://img.stackshare.io/service/1009/tuHsaI2U.png + detection_source_url: https://github.com/mrLSD/llvm-codegen + detection_source: Repo Metadata +- name: Git + description: Fast, scalable, distributed revision control system + website_url: http://git-scm.com/ + open_source: true + hosted_saas: false + category: Build, Test, Deploy + sub_category: Version Control System + image_url: https://img.stackshare.io/service/1046/git.png + detection_source_url: https://github.com/mrLSD/llvm-codegen + detection_source: Repo Metadata +- name: GitHub Actions + description: Automate your workflow from idea to production + website_url: https://github.com/features/actions + open_source: false + hosted_saas: true + category: Build, Test, Deploy + sub_category: Continuous Integration + image_url: https://img.stackshare.io/service/11563/actions.png + detection_source_url: https://github.com/mrLSD/llvm-codegen/blob/master/.github/workflows/swift.yaml + detection_source: ".github/workflows/swift.yaml" + last_updated_by: Evgeny Ukhanov + last_updated_on: 2021-07-03 22:01:07.000000000 Z From 47fa270dfe0289a895d267f42434a4b05225688c Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 7 Sep 2021 23:01:12 +0200 Subject: [PATCH 02/38] Extend Context functions --- llvm-codegen/LLVM/Context.swift | 91 +++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/llvm-codegen/LLVM/Context.swift b/llvm-codegen/LLVM/Context.swift index 109a749..3807bed 100644 --- a/llvm-codegen/LLVM/Context.swift +++ b/llvm-codegen/LLVM/Context.swift @@ -21,6 +21,8 @@ public class Context: ContextRef { /// Diagnostic handler type public typealias DiagnosticHandler = @convention(c) (LLVMDiagnosticInfoRef, UnsafeMutableRawPointer?) -> Void + public typealias YieldCallback = @convention(c) (LLVMContextRef?, UnsafeMutableRawPointer?) -> Void + /// Retrieves the global context instance. /// /// The global context is an particularly convenient instance managed by LLVM @@ -86,37 +88,41 @@ public class Context: ContextRef { } } - //=============================== - //############################### - //=============================== - /// Get the diagnostic context of this context. - public func getDiagnosticContext() { - // void *LLVMContextGetDiagnosticContext(LLVMContextRef C); + public func getDiagnosticContext() -> UnsafeMutableRawPointer { + LLVMContextGetDiagnosticContext(llvm) } /// Set the yield callback function for this context. - public func setYieldCallback() { - // void LLVMContextSetYieldCallback(LLVMContextRef C, LLVMYieldCallback Callback, + public func setYieldCallback(callback: YieldCallback?, opaqueHandle: UnsafeMutableRawPointer?) { + LLVMContextSetYieldCallback(llvm, callback, opaqueHandle) } /// Return a string representation of the DiagnosticInfo. Use /// LLVMDisposeMessage to free the string. - public func getDiagInfoDescription() { - // char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI); + public func getDiagInfoDescription(diagnosticInfo: DiagnosticInfoRef) -> String? { + if let cString = LLVMGetDiagInfoDescription(diagnosticInfo.diagnosticInfoRef) { + return String(cString: cString) + } else { + return nil + } } - /// Return an enum LLVMDiagnosticSeverity. - public func getDiagInfoSeverity() { - // LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI); + /// Return an enum LLVMDiagnosticSeverity. + public func getDiagInfoSeverity(diagnosticInfo: DiagnosticInfoRef) -> LLVMDiagnosticSeverity { + LLVMGetDiagInfoSeverity(diagnosticInfo.diagnosticInfoRef) } - public func getMDKindIDInContext() { - // unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char *Name, + public func getMDKindIDInContext(name: String) -> UInt32 { + name.withCString { cString in + LLVMGetMDKindIDInContext(llvm, cString, UInt32(name.utf8.count)) + } } - public func getMDKindID() { - // unsigned LLVMGetMDKindID(const char *Name, unsigned SLen); + public func getMDKindID(name: String) -> UInt32 { + name.withCString { cString in + LLVMGetMDKindIDInContext(llvm, cString, UInt32(name.utf8.count)) + } } /// Return an unique id given the name of a enum attribute, @@ -128,44 +134,63 @@ public class Context: ContextRef { /// /// NB: Attribute names and/or id are subject to change without /// going through the C API deprecation cycle. - public func getEnumAttributeKindForName() { - // unsigned LLVMGetEnumAttributeKindForName(const char *Name, size_t SLen); + public func getEnumAttributeKindForName(name: String) -> UInt32 { + name.withCString { cString in + LLVMGetEnumAttributeKindForName(cString, name.utf8.count) + } + } + + public func getLastEnumAttributeKind() -> UInt32 { + LLVMGetLastEnumAttributeKind() } - public func getLastEnumAttributeKind() { - // unsigned LLVMGetLastEnumAttributeKind(void); + struct Attribute: AttributeRef { + var attributeRef: LLVMAttributeRef } /// Create an enum attribute. - public func attributeRef() { - // LLVMAttributeRef LLVMCreateEnumAttribute(LLVMContextRef C, unsigned KindID, uint64_t Val); + public func createEnumAttribute(kindID: UInt32, value: UInt64) -> AttributeRef? { + guard let attributeRef = LLVMCreateEnumAttribute(llvm, kindID, value) else { return nil } + return Attribute(attributeRef: attributeRef) } /// Get the unique id corresponding to the enum attribute passed as argument. - public func getEnumAttributeKind() { - // unsigned LLVMGetEnumAttributeKind(LLVMAttributeRef A); + public func getEnumAttributeKind(attributeRef: AttributeRef) -> UInt32 { + LLVMGetEnumAttributeKind(attributeRef.attributeRef) } /// Get the enum attribute's value. 0 is returned if none exists. - public func getEnumAttributeValue() { - // uint64_t LLVMGetEnumAttributeValue(LLVMAttributeRef A); + public func getEnumAttributeValue(attributeRef: AttributeRef) -> UInt64 { + LLVMGetEnumAttributeValue(attributeRef.attributeRef) } /// Create a type attribute - public func createTypeAttribute() { - // LLVMAttributeRef LLVMCreateTypeAttribute(LLVMContextRef C, unsigned KindID, LLVMTypeRef type_ref); + public func createTypeAttribute(kindID: UInt32, typeRef: TypeRef) -> AttributeRef? { + guard let attributeRef = LLVMCreateTypeAttribute(llvm, kindID, typeRef.typeRef) else { return nil } + return Attribute(attributeRef: attributeRef) } /// Get the type attribute's value. - public func getTypeAttributeValue() { - // LLVMTypeRef LLVMGetTypeAttributeValue(LLVMAttributeRef A); + public func getTypeAttributeValue(attributeRef: AttributeRef) -> TypeRef? { + guard let typeRef = LLVMGetTypeAttributeValue(attributeRef.attributeRef) else { return nil } + return Types(llvm: typeRef) } /// Create a string attribute. - public func createStringAttribute() { - // TODO: LLVMAttributeRef LLVMCreateStringAttribute(LLVMContextRef C, + public func createStringAttribute(key: String, value: String) -> AttributeRef? { + let attribute = key.withCString { keyCString in + value.withCString { valueCString in + LLVMCreateStringAttribute(llvm, keyCString, UInt32(key.utf8.count), valueCString, UInt32(value.utf8.count)) + } + } + guard let attributeRef = attribute else { return nil } + return Attribute(attributeRef: attributeRef) } + //=============================== + // ############################### + //=============================== + /// Get the string attribute's kind. public func getStringAttributeKind() { // const char *LLVMGetStringAttributeKind(LLVMAttributeRef A, unsigned *Length); From 40c75f7d15d78e28c5cac0bb8f5c5942d80c9e1e Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 8 Sep 2021 01:44:33 +0200 Subject: [PATCH 03/38] Context API completed. Updated readme --- README.md | 61 +++++++++++++++++++++++++++------ llvm-codegen/CLLVM/bridge.h | 2 +- llvm-codegen/LLVM/Context.swift | 46 +++++++++++++++---------- utils/make-pkg-config.swift | 0 4 files changed, 79 insertions(+), 30 deletions(-) mode change 100644 => 100755 utils/make-pkg-config.swift diff --git a/README.md b/README.md index 4c31ba4..86b5a8c 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,58 @@ -# Swift LLVM codegen +# `llvm-api-swift` -`SwiftLLVMCodegen` is a pure Swift interface to the [LLVM API](https://llvm.org/docs/) and its associated libraries. It provides -native, easy-to-use components to create compilers codegen backend. It contains LLVM bindings, -components and toolset for `Codegen` implementation on Swift. +`llvm-api-swift` is a library representing Swift LLVM API, a pure Swift interface to the [LLVM API](https://llvm.org/docs/) and its associated libraries. +It provides native, easy-to-use components to create compilers codegen backend. It contains LLVM bindings, +components and toolset for efficiently use LLVM as compilers backend implementation on Swift. -## Status +### Compatibility with LLVM-C API -In progress... +When creating the library, we were guided by **full compatibility** with [LLVM-C API](https://llvm.org/doxygen/group__LLVMC.html). +For this reason, structurally the library tries to inherit the `LLVM-C API` tree, thereby dividing the library structure into subdirectories. +And filling the components also with the appropriate `LLVM-C API`. +When implementing Swift types, we were guided by the approach of abstracting away from C types, completely transforming them into Swift types. +At the same time adhering to the principles of a safety and reliability implementation - without explicit memory management, means of safe techniques, functions provided by Swift. -### Supported LLVM version -**v17.0** +### Requirements +- Supported OS: MacOS 12.0 or above +- Swift lang: 5.9 or above + +- Install LLVM: +``` +brew install llvm +``` +- Set Environment variables, that provided during `brew` llvm install +- initialize `pkg-config`: +``` +./utils/make-pkg-config.swift +``` -## Inspiration +**NOTE:** Every time, when LLVM is updated or installed new version should be run `pkg-config` step. -Inspired by [SwiftLLVM](https://github.com/llvm-swift/LLVMSwift). +### Supported LLVM version -## LICENS: [MIT](LICENSE) +- [x] v17.0 + + +### Troubleshooting + +If `LLVM-C` head files during compulation doesn't found, make sure that you: +- installed LLVM +``` +llv --version +``` +- Set environment variables for your terminal (for example in `.zshrc`). To get instruction about variables run: +``` +brew info llvm +``` +- run pkg-config utility: +``` +./utils/make-pkg-config.swift +``` +- if utility doesn't have access right to run: +``` +chmod +x ./utils/make-pkg-config.swift +./utils/make-pkg-config.swift +``` + +### LICENS: [MIT](LICENSE) diff --git a/llvm-codegen/CLLVM/bridge.h b/llvm-codegen/CLLVM/bridge.h index 24f6bd7..d540bad 100644 --- a/llvm-codegen/CLLVM/bridge.h +++ b/llvm-codegen/CLLVM/bridge.h @@ -13,7 +13,7 @@ #include #include #include - #include +#include #include #include #include diff --git a/llvm-codegen/LLVM/Context.swift b/llvm-codegen/LLVM/Context.swift index 3807bed..75a8e3b 100644 --- a/llvm-codegen/LLVM/Context.swift +++ b/llvm-codegen/LLVM/Context.swift @@ -101,11 +101,8 @@ public class Context: ContextRef { /// Return a string representation of the DiagnosticInfo. Use /// LLVMDisposeMessage to free the string. public func getDiagInfoDescription(diagnosticInfo: DiagnosticInfoRef) -> String? { - if let cString = LLVMGetDiagInfoDescription(diagnosticInfo.diagnosticInfoRef) { - return String(cString: cString) - } else { - return nil - } + guard let cString = LLVMGetDiagInfoDescription(diagnosticInfo.diagnosticInfoRef) else { return nil } + return String(cString: cString) } /// Return an enum LLVMDiagnosticSeverity. @@ -113,6 +110,8 @@ public class Context: ContextRef { LLVMGetDiagInfoSeverity(diagnosticInfo.diagnosticInfoRef) } + /// Get Metadata KindId by name in current Context. + /// Useful for working with Metadata public func getMDKindIDInContext(name: String) -> UInt32 { name.withCString { cString in LLVMGetMDKindIDInContext(llvm, cString, UInt32(name.utf8.count)) @@ -121,7 +120,7 @@ public class Context: ContextRef { public func getMDKindID(name: String) -> UInt32 { name.withCString { cString in - LLVMGetMDKindIDInContext(llvm, cString, UInt32(name.utf8.count)) + LLVMGetMDKindID(cString, UInt32(name.utf8.count)) } } @@ -192,33 +191,44 @@ public class Context: ContextRef { //=============================== /// Get the string attribute's kind. - public func getStringAttributeKind() { - // const char *LLVMGetStringAttributeKind(LLVMAttributeRef A, unsigned *Length); + public func getStringAttributeKind(attributeRef: AttributeRef, length: UInt32) -> String? { + var mutLength = length + guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in + LLVMGetStringAttributeKind(attributeRef.attributeRef, lengthPtr) + }) else { return nil } + return String(cString: cString) } /// Get the string attribute's value. - public func getStringAttributeValue() { - // const char *LLVMGetStringAttributeValue(LLVMAttributeRef A, unsigned *Length); + public func getStringAttributeValue(attributeRef: AttributeRef, length: UInt32) -> String? { + var mutLength = length + guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in + LLVMGetStringAttributeValue(attributeRef.attributeRef, lengthPtr) + }) else { return nil } + return String(cString: cString) } /// Check for the types of attributes. - public func isEnumAttribute() { - // LLVMBool LLVMIsEnumAttribute(LLVMAttributeRef A); + public func isEnumAttribute(attributeRef: AttributeRef) -> Bool { + return LLVMIsEnumAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. - public func isStringAttribute() { - // LLVMBool LLVMIsStringAttribute(LLVMAttributeRef A); + public func isStringAttribute(attributeRef: AttributeRef) -> Bool { + return LLVMIsStringAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. - public func isTypeAttribute() { - // LLVMBool LLVMIsTypeAttribute(LLVMAttributeRef A); + public func isTypeAttribute(attributeRef: AttributeRef) -> Bool { + return LLVMIsTypeAttribute(attributeRef.attributeRef) != 0 } /// Obtain a Type from a context by its registered name. - public func getTypeByName2() { - // LLVMTypeRef LLVMGetTypeByName2(LLVMContextRef C, const char *Name); + public func getTypeByName2(name: String) -> TypeRef? { + name.withCString { cString in + guard let typeRef = LLVMGetTypeByName2(llvm, cString) else { return nil } + return Types(llvm: typeRef) + } } /// Deinitialize this value and dispose of its resources. diff --git a/utils/make-pkg-config.swift b/utils/make-pkg-config.swift old mode 100644 new mode 100755 From f9b3d2c36db34cbb09999bb399096734c82eeb8b Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 19 Sep 2021 02:02:45 +0200 Subject: [PATCH 04/38] Updated Library properties. Renamed dir structure --- Package.swift | 22 ++++--------------- {llvm-codegen => llvm-api}/CLLVM/bridge.h | 0 .../CLLVM/module.modulemap | 0 .../LLVM/AddressSpace.swift | 0 .../LLVM/BasicBlock.swift | 0 {llvm-codegen => llvm-api}/LLVM/Context.swift | 0 .../LLVM/Functions.swift | 0 .../LLVM/Types/Array.swift | 0 .../LLVM/Types/Float.swift | 0 .../LLVM/Types/Function.swift | 0 .../LLVM/Types/Int.swift | 0 .../LLVM/Types/Other/Label.swift | 0 .../LLVM/Types/Other/Metadata.swift | 0 .../LLVM/Types/Other/TargetExt.swift | 0 .../LLVM/Types/Other/Token.swift | 0 .../LLVM/Types/Other/Void.swift | 0 .../LLVM/Types/Other/X86AMX.swift | 0 .../LLVM/Types/Other/X86MMX.swift | 0 .../LLVM/Types/Pointer.swift | 0 .../LLVM/Types/Struct.swift | 0 .../LLVM/Types/Types.swift | 0 .../LLVM/Types/Vector.swift | 0 .../LLVM/Values/Values.swift | 0 llvm-codegen/cli/main.swift | 4 ---- 24 files changed, 4 insertions(+), 22 deletions(-) rename {llvm-codegen => llvm-api}/CLLVM/bridge.h (100%) rename {llvm-codegen => llvm-api}/CLLVM/module.modulemap (100%) rename {llvm-codegen => llvm-api}/LLVM/AddressSpace.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/BasicBlock.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Context.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Functions.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Array.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Float.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Function.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Int.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/Label.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/Metadata.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/TargetExt.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/Token.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/Void.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/X86AMX.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Other/X86MMX.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Pointer.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Struct.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Types.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Types/Vector.swift (100%) rename {llvm-codegen => llvm-api}/LLVM/Values/Values.swift (100%) delete mode 100644 llvm-codegen/cli/main.swift diff --git a/Package.swift b/Package.swift index 95ffbc0..9c31421 100644 --- a/Package.swift +++ b/Package.swift @@ -4,28 +4,14 @@ import PackageDescription let package = Package( - name: "llvm-codegen", + name: "llvm-api", products: [ - .executable(name: "llvm-codegen", targets: ["llvm-codegen"]), - ], - dependencies: [ - .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.3.0"), + .library(name: "llvm-api", targets: ["LLVM"]), ], targets: [ - .executableTarget( - name: "llvm-codegen", - dependencies: [ - "LLVM", - .product( - name: "ArgumentParser", - package: "swift-argument-parser" - ), - ], - path: "llvm-codegen/cli" - ), .systemLibrary( name: "CLLVM", - path: "llvm-codegen/CLLVM", + path: "llvm-api/CLLVM", pkgConfig: "CLLVM", providers: [ .brew(["llvm"]), @@ -34,7 +20,7 @@ let package = Package( .target( name: "LLVM", dependencies: ["CLLVM"], - path: "llvm-codegen/LLVM" + path: "llvm-api/LLVM" ), ], cxxLanguageStandard: .cxx20 diff --git a/llvm-codegen/CLLVM/bridge.h b/llvm-api/CLLVM/bridge.h similarity index 100% rename from llvm-codegen/CLLVM/bridge.h rename to llvm-api/CLLVM/bridge.h diff --git a/llvm-codegen/CLLVM/module.modulemap b/llvm-api/CLLVM/module.modulemap similarity index 100% rename from llvm-codegen/CLLVM/module.modulemap rename to llvm-api/CLLVM/module.modulemap diff --git a/llvm-codegen/LLVM/AddressSpace.swift b/llvm-api/LLVM/AddressSpace.swift similarity index 100% rename from llvm-codegen/LLVM/AddressSpace.swift rename to llvm-api/LLVM/AddressSpace.swift diff --git a/llvm-codegen/LLVM/BasicBlock.swift b/llvm-api/LLVM/BasicBlock.swift similarity index 100% rename from llvm-codegen/LLVM/BasicBlock.swift rename to llvm-api/LLVM/BasicBlock.swift diff --git a/llvm-codegen/LLVM/Context.swift b/llvm-api/LLVM/Context.swift similarity index 100% rename from llvm-codegen/LLVM/Context.swift rename to llvm-api/LLVM/Context.swift diff --git a/llvm-codegen/LLVM/Functions.swift b/llvm-api/LLVM/Functions.swift similarity index 100% rename from llvm-codegen/LLVM/Functions.swift rename to llvm-api/LLVM/Functions.swift diff --git a/llvm-codegen/LLVM/Types/Array.swift b/llvm-api/LLVM/Types/Array.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Array.swift rename to llvm-api/LLVM/Types/Array.swift diff --git a/llvm-codegen/LLVM/Types/Float.swift b/llvm-api/LLVM/Types/Float.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Float.swift rename to llvm-api/LLVM/Types/Float.swift diff --git a/llvm-codegen/LLVM/Types/Function.swift b/llvm-api/LLVM/Types/Function.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Function.swift rename to llvm-api/LLVM/Types/Function.swift diff --git a/llvm-codegen/LLVM/Types/Int.swift b/llvm-api/LLVM/Types/Int.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Int.swift rename to llvm-api/LLVM/Types/Int.swift diff --git a/llvm-codegen/LLVM/Types/Other/Label.swift b/llvm-api/LLVM/Types/Other/Label.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/Label.swift rename to llvm-api/LLVM/Types/Other/Label.swift diff --git a/llvm-codegen/LLVM/Types/Other/Metadata.swift b/llvm-api/LLVM/Types/Other/Metadata.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/Metadata.swift rename to llvm-api/LLVM/Types/Other/Metadata.swift diff --git a/llvm-codegen/LLVM/Types/Other/TargetExt.swift b/llvm-api/LLVM/Types/Other/TargetExt.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/TargetExt.swift rename to llvm-api/LLVM/Types/Other/TargetExt.swift diff --git a/llvm-codegen/LLVM/Types/Other/Token.swift b/llvm-api/LLVM/Types/Other/Token.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/Token.swift rename to llvm-api/LLVM/Types/Other/Token.swift diff --git a/llvm-codegen/LLVM/Types/Other/Void.swift b/llvm-api/LLVM/Types/Other/Void.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/Void.swift rename to llvm-api/LLVM/Types/Other/Void.swift diff --git a/llvm-codegen/LLVM/Types/Other/X86AMX.swift b/llvm-api/LLVM/Types/Other/X86AMX.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/X86AMX.swift rename to llvm-api/LLVM/Types/Other/X86AMX.swift diff --git a/llvm-codegen/LLVM/Types/Other/X86MMX.swift b/llvm-api/LLVM/Types/Other/X86MMX.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Other/X86MMX.swift rename to llvm-api/LLVM/Types/Other/X86MMX.swift diff --git a/llvm-codegen/LLVM/Types/Pointer.swift b/llvm-api/LLVM/Types/Pointer.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Pointer.swift rename to llvm-api/LLVM/Types/Pointer.swift diff --git a/llvm-codegen/LLVM/Types/Struct.swift b/llvm-api/LLVM/Types/Struct.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Struct.swift rename to llvm-api/LLVM/Types/Struct.swift diff --git a/llvm-codegen/LLVM/Types/Types.swift b/llvm-api/LLVM/Types/Types.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Types.swift rename to llvm-api/LLVM/Types/Types.swift diff --git a/llvm-codegen/LLVM/Types/Vector.swift b/llvm-api/LLVM/Types/Vector.swift similarity index 100% rename from llvm-codegen/LLVM/Types/Vector.swift rename to llvm-api/LLVM/Types/Vector.swift diff --git a/llvm-codegen/LLVM/Values/Values.swift b/llvm-api/LLVM/Values/Values.swift similarity index 100% rename from llvm-codegen/LLVM/Values/Values.swift rename to llvm-api/LLVM/Values/Values.swift diff --git a/llvm-codegen/cli/main.swift b/llvm-codegen/cli/main.swift deleted file mode 100644 index cd0ee1a..0000000 --- a/llvm-codegen/cli/main.swift +++ /dev/null @@ -1,4 +0,0 @@ -import Foundation -import LLVM - -print("Hello, World!") From b3e1018b0e79035a1878b668f73ce011229ed1c7 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Mon, 20 Sep 2021 00:01:28 +0200 Subject: [PATCH 05/38] Refactoring for LLVM-Core module --- llvm-api/LLVM/{ => Core}/AddressSpace.swift | 0 llvm-api/LLVM/{ => Core}/BasicBlock.swift | 0 llvm-api/LLVM/{ => Core}/Context.swift | 46 ++++++++----------- llvm-api/LLVM/Core/Core.swift | 2 + llvm-api/LLVM/Core/Diagnostic.swift | 33 +++++++++++++ llvm-api/LLVM/{ => Core}/Functions.swift | 0 llvm-api/LLVM/{ => Core}/Types/Array.swift | 0 llvm-api/LLVM/{ => Core}/Types/Float.swift | 0 llvm-api/LLVM/{ => Core}/Types/Function.swift | 0 llvm-api/LLVM/{ => Core}/Types/Int.swift | 0 .../LLVM/{ => Core}/Types/Other/Label.swift | 0 .../{ => Core}/Types/Other/Metadata.swift | 0 .../{ => Core}/Types/Other/TargetExt.swift | 0 .../LLVM/{ => Core}/Types/Other/Token.swift | 0 .../LLVM/{ => Core}/Types/Other/Void.swift | 0 .../LLVM/{ => Core}/Types/Other/X86AMX.swift | 0 .../LLVM/{ => Core}/Types/Other/X86MMX.swift | 0 llvm-api/LLVM/{ => Core}/Types/Pointer.swift | 0 llvm-api/LLVM/{ => Core}/Types/Struct.swift | 0 llvm-api/LLVM/{ => Core}/Types/Types.swift | 0 llvm-api/LLVM/{ => Core}/Types/Vector.swift | 0 llvm-api/LLVM/{ => Core}/Values/Values.swift | 0 22 files changed, 55 insertions(+), 26 deletions(-) rename llvm-api/LLVM/{ => Core}/AddressSpace.swift (100%) rename llvm-api/LLVM/{ => Core}/BasicBlock.swift (100%) rename llvm-api/LLVM/{ => Core}/Context.swift (83%) create mode 100644 llvm-api/LLVM/Core/Core.swift create mode 100644 llvm-api/LLVM/Core/Diagnostic.swift rename llvm-api/LLVM/{ => Core}/Functions.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Array.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Float.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Function.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Int.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/Label.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/Metadata.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/TargetExt.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/Token.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/Void.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/X86AMX.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Other/X86MMX.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Pointer.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Struct.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Types.swift (100%) rename llvm-api/LLVM/{ => Core}/Types/Vector.swift (100%) rename llvm-api/LLVM/{ => Core}/Values/Values.swift (100%) diff --git a/llvm-api/LLVM/AddressSpace.swift b/llvm-api/LLVM/Core/AddressSpace.swift similarity index 100% rename from llvm-api/LLVM/AddressSpace.swift rename to llvm-api/LLVM/Core/AddressSpace.swift diff --git a/llvm-api/LLVM/BasicBlock.swift b/llvm-api/LLVM/Core/BasicBlock.swift similarity index 100% rename from llvm-api/LLVM/BasicBlock.swift rename to llvm-api/LLVM/Core/BasicBlock.swift diff --git a/llvm-api/LLVM/Context.swift b/llvm-api/LLVM/Core/Context.swift similarity index 83% rename from llvm-api/LLVM/Context.swift rename to llvm-api/LLVM/Core/Context.swift index 75a8e3b..4dff095 100644 --- a/llvm-api/LLVM/Context.swift +++ b/llvm-api/LLVM/Core/Context.swift @@ -19,7 +19,7 @@ public class Context: ContextRef { public var contextRef: LLVMContextRef { llvm } /// Diagnostic handler type - public typealias DiagnosticHandler = @convention(c) (LLVMDiagnosticInfoRef, UnsafeMutableRawPointer?) -> Void + public typealias DiagnosticHandler = @convention(c) (LLVMDiagnosticInfoRef?, UnsafeMutableRawPointer?) -> Void public typealias YieldCallback = @convention(c) (LLVMContextRef?, UnsafeMutableRawPointer?) -> Void @@ -48,16 +48,12 @@ public class Context: ContextRef { /// Get the diagnostic handler of current context. public var getDiagnosticHandler: DiagnosticHandler? { - if let handler = LLVMContextGetDiagnosticHandler(contextRef) { - return unsafeBitCast(handler, to: DiagnosticHandler.self) - } else { - return nil - } + LLVMContextGetDiagnosticHandler(llvm) } /// Set the diagnostic handler for current context. - public func setDiagnosticHandler(handler: LLVMDiagnosticHandler?, diagnosticContext: UnsafeMutableRawPointer?) { - LLVMContextSetDiagnosticHandler(contextRef, handler, diagnosticContext) + public func setDiagnosticHandler(handler: DiagnosticHandler?, diagnosticContext: UnsafeMutableRawPointer?) { + LLVMContextSetDiagnosticHandler(llvm, handler.self, diagnosticContext) } /// Retrieve whether the given context is set to discard all value names. @@ -100,14 +96,15 @@ public class Context: ContextRef { /// Return a string representation of the DiagnosticInfo. Use /// LLVMDisposeMessage to free the string. - public func getDiagInfoDescription(diagnosticInfo: DiagnosticInfoRef) -> String? { + public static func getDiagInfoDescription(diagnosticInfo: DiagnosticInfoRef) -> String? { guard let cString = LLVMGetDiagInfoDescription(diagnosticInfo.diagnosticInfoRef) else { return nil } + defer { LLVMDisposeMessage(cString) } return String(cString: cString) } /// Return an enum LLVMDiagnosticSeverity. - public func getDiagInfoSeverity(diagnosticInfo: DiagnosticInfoRef) -> LLVMDiagnosticSeverity { - LLVMGetDiagInfoSeverity(diagnosticInfo.diagnosticInfoRef) + public static func getDiagInfoSeverity(diagnosticInfo: DiagnosticInfoRef) -> DiagnosticSeverity? { + DiagnosticSeverity(from: LLVMGetDiagInfoSeverity(diagnosticInfo.diagnosticInfoRef)) } /// Get Metadata KindId by name in current Context. @@ -118,7 +115,7 @@ public class Context: ContextRef { } } - public func getMDKindID(name: String) -> UInt32 { + public static func getMDKindID(name: String) -> UInt32 { name.withCString { cString in LLVMGetMDKindID(cString, UInt32(name.utf8.count)) } @@ -133,13 +130,14 @@ public class Context: ContextRef { /// /// NB: Attribute names and/or id are subject to change without /// going through the C API deprecation cycle. - public func getEnumAttributeKindForName(name: String) -> UInt32 { + public static func getEnumAttributeKindForName(name: String) -> UInt32 { name.withCString { cString in LLVMGetEnumAttributeKindForName(cString, name.utf8.count) } } - public func getLastEnumAttributeKind() -> UInt32 { + /// Get last enum attribute + public static func getLastEnumAttributeKind() -> UInt32 { LLVMGetLastEnumAttributeKind() } @@ -154,12 +152,12 @@ public class Context: ContextRef { } /// Get the unique id corresponding to the enum attribute passed as argument. - public func getEnumAttributeKind(attributeRef: AttributeRef) -> UInt32 { + public static func getEnumAttributeKind(attributeRef: AttributeRef) -> UInt32 { LLVMGetEnumAttributeKind(attributeRef.attributeRef) } /// Get the enum attribute's value. 0 is returned if none exists. - public func getEnumAttributeValue(attributeRef: AttributeRef) -> UInt64 { + public static func getEnumAttributeValue(attributeRef: AttributeRef) -> UInt64 { LLVMGetEnumAttributeValue(attributeRef.attributeRef) } @@ -170,7 +168,7 @@ public class Context: ContextRef { } /// Get the type attribute's value. - public func getTypeAttributeValue(attributeRef: AttributeRef) -> TypeRef? { + public static func getTypeAttributeValue(attributeRef: AttributeRef) -> TypeRef? { guard let typeRef = LLVMGetTypeAttributeValue(attributeRef.attributeRef) else { return nil } return Types(llvm: typeRef) } @@ -186,12 +184,8 @@ public class Context: ContextRef { return Attribute(attributeRef: attributeRef) } - //=============================== - // ############################### - //=============================== - /// Get the string attribute's kind. - public func getStringAttributeKind(attributeRef: AttributeRef, length: UInt32) -> String? { + public static func getStringAttributeKind(attributeRef: AttributeRef, length: UInt32) -> String? { var mutLength = length guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in LLVMGetStringAttributeKind(attributeRef.attributeRef, lengthPtr) @@ -200,7 +194,7 @@ public class Context: ContextRef { } /// Get the string attribute's value. - public func getStringAttributeValue(attributeRef: AttributeRef, length: UInt32) -> String? { + public static func getStringAttributeValue(attributeRef: AttributeRef, length: UInt32) -> String? { var mutLength = length guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in LLVMGetStringAttributeValue(attributeRef.attributeRef, lengthPtr) @@ -209,17 +203,17 @@ public class Context: ContextRef { } /// Check for the types of attributes. - public func isEnumAttribute(attributeRef: AttributeRef) -> Bool { + public static func isEnumAttribute(attributeRef: AttributeRef) -> Bool { return LLVMIsEnumAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. - public func isStringAttribute(attributeRef: AttributeRef) -> Bool { + public static func isStringAttribute(attributeRef: AttributeRef) -> Bool { return LLVMIsStringAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. - public func isTypeAttribute(attributeRef: AttributeRef) -> Bool { + public static func isTypeAttribute(attributeRef: AttributeRef) -> Bool { return LLVMIsTypeAttribute(attributeRef.attributeRef) != 0 } diff --git a/llvm-api/LLVM/Core/Core.swift b/llvm-api/LLVM/Core/Core.swift new file mode 100644 index 0000000..7ba120a --- /dev/null +++ b/llvm-api/LLVM/Core/Core.swift @@ -0,0 +1,2 @@ +import CLLVM + diff --git a/llvm-api/LLVM/Core/Diagnostic.swift b/llvm-api/LLVM/Core/Diagnostic.swift new file mode 100644 index 0000000..3b70ebd --- /dev/null +++ b/llvm-api/LLVM/Core/Diagnostic.swift @@ -0,0 +1,33 @@ +import CLLVM + +/// Diagnostic functionality +public struct Diagnostic: DiagnosticInfoRef { + private var llvm: LLVMDiagnosticInfoRef + public var diagnosticInfoRef: LLVMDiagnosticInfoRef { llvm } + + /// Init DIagnosticInfo + public init(llvm: LLVMDiagnosticInfoRef) { + self.llvm = llvm + } + + /// Return a string representation of the DiagnosticInfo. + public var getDiagInfoDescription: String? { + Context.getDiagInfoDescription(diagnosticInfo: self) + } + + /// Return an enum LLVMDiagnosticSeverity. + public var getDiagInfoSeverity: DiagnosticSeverity? { + Context.getDiagInfoSeverity(diagnosticInfo: self) + } +} + +public enum DiagnosticSeverity: Int { + case error = 0 + case warning = 1 + case remark = 2 + case note = 3 + + public init?(from cSeverity: LLVMDiagnosticSeverity) { + self.init(rawValue: Int(cSeverity.rawValue)) + } +} diff --git a/llvm-api/LLVM/Functions.swift b/llvm-api/LLVM/Core/Functions.swift similarity index 100% rename from llvm-api/LLVM/Functions.swift rename to llvm-api/LLVM/Core/Functions.swift diff --git a/llvm-api/LLVM/Types/Array.swift b/llvm-api/LLVM/Core/Types/Array.swift similarity index 100% rename from llvm-api/LLVM/Types/Array.swift rename to llvm-api/LLVM/Core/Types/Array.swift diff --git a/llvm-api/LLVM/Types/Float.swift b/llvm-api/LLVM/Core/Types/Float.swift similarity index 100% rename from llvm-api/LLVM/Types/Float.swift rename to llvm-api/LLVM/Core/Types/Float.swift diff --git a/llvm-api/LLVM/Types/Function.swift b/llvm-api/LLVM/Core/Types/Function.swift similarity index 100% rename from llvm-api/LLVM/Types/Function.swift rename to llvm-api/LLVM/Core/Types/Function.swift diff --git a/llvm-api/LLVM/Types/Int.swift b/llvm-api/LLVM/Core/Types/Int.swift similarity index 100% rename from llvm-api/LLVM/Types/Int.swift rename to llvm-api/LLVM/Core/Types/Int.swift diff --git a/llvm-api/LLVM/Types/Other/Label.swift b/llvm-api/LLVM/Core/Types/Other/Label.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/Label.swift rename to llvm-api/LLVM/Core/Types/Other/Label.swift diff --git a/llvm-api/LLVM/Types/Other/Metadata.swift b/llvm-api/LLVM/Core/Types/Other/Metadata.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/Metadata.swift rename to llvm-api/LLVM/Core/Types/Other/Metadata.swift diff --git a/llvm-api/LLVM/Types/Other/TargetExt.swift b/llvm-api/LLVM/Core/Types/Other/TargetExt.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/TargetExt.swift rename to llvm-api/LLVM/Core/Types/Other/TargetExt.swift diff --git a/llvm-api/LLVM/Types/Other/Token.swift b/llvm-api/LLVM/Core/Types/Other/Token.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/Token.swift rename to llvm-api/LLVM/Core/Types/Other/Token.swift diff --git a/llvm-api/LLVM/Types/Other/Void.swift b/llvm-api/LLVM/Core/Types/Other/Void.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/Void.swift rename to llvm-api/LLVM/Core/Types/Other/Void.swift diff --git a/llvm-api/LLVM/Types/Other/X86AMX.swift b/llvm-api/LLVM/Core/Types/Other/X86AMX.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/X86AMX.swift rename to llvm-api/LLVM/Core/Types/Other/X86AMX.swift diff --git a/llvm-api/LLVM/Types/Other/X86MMX.swift b/llvm-api/LLVM/Core/Types/Other/X86MMX.swift similarity index 100% rename from llvm-api/LLVM/Types/Other/X86MMX.swift rename to llvm-api/LLVM/Core/Types/Other/X86MMX.swift diff --git a/llvm-api/LLVM/Types/Pointer.swift b/llvm-api/LLVM/Core/Types/Pointer.swift similarity index 100% rename from llvm-api/LLVM/Types/Pointer.swift rename to llvm-api/LLVM/Core/Types/Pointer.swift diff --git a/llvm-api/LLVM/Types/Struct.swift b/llvm-api/LLVM/Core/Types/Struct.swift similarity index 100% rename from llvm-api/LLVM/Types/Struct.swift rename to llvm-api/LLVM/Core/Types/Struct.swift diff --git a/llvm-api/LLVM/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift similarity index 100% rename from llvm-api/LLVM/Types/Types.swift rename to llvm-api/LLVM/Core/Types/Types.swift diff --git a/llvm-api/LLVM/Types/Vector.swift b/llvm-api/LLVM/Core/Types/Vector.swift similarity index 100% rename from llvm-api/LLVM/Types/Vector.swift rename to llvm-api/LLVM/Core/Types/Vector.swift diff --git a/llvm-api/LLVM/Values/Values.swift b/llvm-api/LLVM/Core/Values/Values.swift similarity index 100% rename from llvm-api/LLVM/Values/Values.swift rename to llvm-api/LLVM/Core/Values/Values.swift From 6759dc7fdd875d660494b20db35de5dcd4cfb2d3 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 21 Sep 2021 01:48:16 +0200 Subject: [PATCH 06/38] Added Core module --- llvm-api/LLVM/Core/Context.swift | 4 +- llvm-api/LLVM/Core/Core.swift | 80 ++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/llvm-api/LLVM/Core/Context.swift b/llvm-api/LLVM/Core/Context.swift index 4dff095..08a1b16 100644 --- a/llvm-api/LLVM/Core/Context.swift +++ b/llvm-api/LLVM/Core/Context.swift @@ -95,10 +95,10 @@ public class Context: ContextRef { } /// Return a string representation of the DiagnosticInfo. Use - /// LLVMDisposeMessage to free the string. + /// `Core.disposeMessage` (`LLVMDisposeMessage`) to free the string. public static func getDiagInfoDescription(diagnosticInfo: DiagnosticInfoRef) -> String? { guard let cString = LLVMGetDiagInfoDescription(diagnosticInfo.diagnosticInfoRef) else { return nil } - defer { LLVMDisposeMessage(cString) } + defer { Core.disposeMessage(cString) } return String(cString: cString) } diff --git a/llvm-api/LLVM/Core/Core.swift b/llvm-api/LLVM/Core/Core.swift index 7ba120a..e9a19e2 100644 --- a/llvm-api/LLVM/Core/Core.swift +++ b/llvm-api/LLVM/Core/Core.swift @@ -1,2 +1,82 @@ import CLLVM +/// This modules provide an interface to libLLVMCore, which implements the LLVM intermediate representation as well +/// as other related types and utilities. +/// +/// Many exotic languages can interoperate with C code but have a harder time with C++ due to name mangling. So in addition to C, +/// this interface enables tools written in such languages. +/// - SeeAlso: https://llvm.org/doxygen/group__LLVMCCore.html +enum Core { + /// Return the major, minor, and patch version of LLVM + /// The version components are returned via the function's three output + /// parameters or skipped if a NULL pointer was supplied - return 0. + public static func getVersion() -> (major: UInt32, minor: UInt32, patch: UInt32) { + var major: UInt32 = 0 + var minor: UInt32 = 0 + var patch: UInt32 = 0 + + withUnsafeMutablePointer(to: &major) { majorPtr in + withUnsafeMutablePointer(to: &minor) { minorPtr in + withUnsafeMutablePointer(to: &patch) { patchPtr in + LLVMGetVersion(majorPtr, minorPtr, patchPtr) + } + } + } + return (major, minor, patch) + } + + /// Create message string reference. Run [disposeMessage] to free message. + /// It useful when LLVM wait as parameter LLVM-string + /// + /// - SeeAlso: `disposeLLVMMessage` + public static func createMessage(with message: String) -> UnsafeMutablePointer? { + return message.withCString { cString in + LLVMCreateMessage(cString) + } + } + + /// Dispose LLVM message + public static func disposeMessage(_ message: UnsafeMutablePointer?) { + LLVMDisposeMessage(message) + } + + /// This function permanently loads the dynamic library at the given path. + /// It is safe to call this function multiple times for the same library. + public static func loadLibraryPermanently(filename: String) -> Bool { + return filename.withCString { cString in + LLVMLoadLibraryPermanently(cString) != 0 + } + } + + /// This function parses the given arguments using the LLVM command line parser. + /// Note that the only stable thing about this function is its signature; you + /// cannot rely on any particular set of command line arguments being interpreted + /// the same way across LLVM versions. + public static func parseCommandLineOptions(arguments: [String], overview: String) { + let cArgs = arguments.map { $0.withCString(strdup) } + defer { cArgs.forEach { free($0) } } + overview.withCString { cOverview in + let cArgsPointers = cArgs.map { UnsafePointer($0) } + cArgsPointers.withUnsafeBufferPointer { cArgsPointersBuffer in + LLVMParseCommandLineOptions(Int32(arguments.count), cArgsPointersBuffer.baseAddress, cOverview) + } + } + } + + /// This function will search through all previously loaded dynamic + /// libraries for the symbol `symbolName`. If it is found, the address of + /// that symbol is returned. If not, null is returned. + public static func searchForAddressOfSymbol(symbolName: String) -> UnsafeMutableRawPointer? { + return symbolName.withCString { cString in + LLVMSearchForAddressOfSymbol(cString) + } + } + + /// This functions permanently adds the symbol \p symbolName with the + /// value `symbolValue`. These symbols are searched before any libraries. + public static func addSymbol(symbolName: String, symbolValue: UnsafeMutableRawPointer) { + symbolName.withCString { cString in + LLVMAddSymbol(cString, symbolValue) + } + } +} From 1a36abac464abee0c11fa52562b1a2e35d092ddb Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 24 Sep 2021 00:37:02 +0200 Subject: [PATCH 07/38] Added LLVMOpcode. Changed LLVMTypeKind --- llvm-api/LLVM/Core/Types/Types.swift | 224 ++++++++++++++++++--------- 1 file changed, 151 insertions(+), 73 deletions(-) diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift index f159c63..2ef6b96 100644 --- a/llvm-api/LLVM/Core/Types/Types.swift +++ b/llvm-api/LLVM/Core/Types/Types.swift @@ -96,7 +96,7 @@ public extension TypeRef { var getConcreteTypeInContext: TypeRef { let ty = Types(typeRef: self) switch ty.getTypeKind { - case .integerTypeKind: + case .IntegerTypeKind: let intWidth = IntType.getIntTypeWidth(ty: self) return switch intWidth { case 1: Int1Type(typeRef: self, context: ty.getTypeContext) @@ -107,33 +107,33 @@ public extension TypeRef { case 128: Int128Type(typeRef: self, context: ty.getTypeContext) default: IntType(bits: intWidth, in: ty.getTypeContext) } - case .voidTypeKind: return VoidType(typeRef: self, context: ty.getTypeContext) - case .halfTypeKind: return HalfType(typeRef: self, context: ty.getTypeContext) - case .floatTypeKind: return FloatType(typeRef: self, context: ty.getTypeContext) - case .doubleTypeKind: return DoubleType(typeRef: self, context: ty.getTypeContext) - case .x86_FP80TypeKind: return X86FP80Type(typeRef: self, context: ty.getTypeContext) - case .fp128TypeKind: return FP128Type(typeRef: self, context: ty.getTypeContext) - case .ppc_FP128TypeKind: return PPCFP128Type(typeRef: self, context: ty.getTypeContext) - case .labelTypeKind: return LabelType(typeRef: self, context: ty.getTypeContext) - case .functionTypeKind: + case .VoidTypeKind: return VoidType(typeRef: self, context: ty.getTypeContext) + case .HalfTypeKind: return HalfType(typeRef: self, context: ty.getTypeContext) + case .FloatTypeKind: return FloatType(typeRef: self, context: ty.getTypeContext) + case .DoubleTypeKind: return DoubleType(typeRef: self, context: ty.getTypeContext) + case .X86_FP80TypeKind: return X86FP80Type(typeRef: self, context: ty.getTypeContext) + case .FP128TypeKind: return FP128Type(typeRef: self, context: ty.getTypeContext) + case .PPC_FP128TypeKind: return PPCFP128Type(typeRef: self, context: ty.getTypeContext) + case .LabelTypeKind: return LabelType(typeRef: self, context: ty.getTypeContext) + case .FunctionTypeKind: let paramTypes = FunctionType.getParamTypes(funcType: self) let returnTy = FunctionType.getReturnType(funcType: self) let isVarArg = FunctionType.isFunctionVarArg(funcType: self) return FunctionType(returnType: returnTy, parameterTypes: paramTypes, isVariadic: isVarArg) - case .structTypeKind: return StructType(typeRef: self) - case .arrayTypeKind: return ArrayType(typeRef: self) - case .pointerTypeKind: + case .StructTypeKind: return StructType(typeRef: self) + case .ArrayTypeKind: return ArrayType(typeRef: self) + case .PointerTypeKind: let pointee = PointerType.getElementType(typeRef: self)! let addressSpace = PointerType.getPointerAddressSpace(typeRef: self) return PointerType(pointee: pointee, addressSpace: addressSpace) - case .vectorTypeKind: return VectorType(typeRef: self) - case .metadataTypeKind: return MetadataType(typeRef: self, context: ty.getTypeContext) - case .x86_MMXTypeKind: return X86MMXType(typeRef: self, context: ty.getTypeContext) - case .tokenTypeKind: return TokenType(typeRef: self, context: ty.getTypeContext) - case .scalableVectorTypeKind: return ScalableVectorType(typeRef: self) - case .bFloatTypeKind: return BFloatType(typeRef: self, context: ty.getTypeContext) - case .x86_AMXTypeKind: return X86AMXType(typeRef: self, context: ty.getTypeContext) - case .targetExtTypeKind: return TargetExtType(typeRef: self, context: ty.getTypeContext) + case .VectorTypeKind: return VectorType(typeRef: self) + case .MetadataTypeKind: return MetadataType(typeRef: self, context: ty.getTypeContext) + case .X86_MMXTypeKind: return X86MMXType(typeRef: self, context: ty.getTypeContext) + case .TokenTypeKind: return TokenType(typeRef: self, context: ty.getTypeContext) + case .ScalableVectorTypeKind: return ScalableVectorType(typeRef: self) + case .BFloatTypeKind: return BFloatType(typeRef: self, context: ty.getTypeContext) + case .X86_AMXTypeKind: return X86AMXType(typeRef: self, context: ty.getTypeContext) + case .TargetExtTypeKind: return TargetExtType(typeRef: self, context: ty.getTypeContext) } } } @@ -155,57 +155,6 @@ public protocol ValueRef { var valueRef: LLVMValueRef { get } } -public enum TypeKind { - case voidTypeKind /** < type with no size */ - case halfTypeKind /** < 16 bit floating point type */ - case floatTypeKind /** < 32 bit floating point type */ - case doubleTypeKind /** < 64 bit floating point type */ - case x86_FP80TypeKind /** < 80 bit floating point type (X87) */ - case fp128TypeKind /** < 128 bit floating point type (112-bit mantissa) */ - case ppc_FP128TypeKind /** < 128 bit floating point type (two 64-bits) */ - case labelTypeKind /** < Labels */ - case integerTypeKind /** < Arbitrary bit width integers */ - case functionTypeKind /** < Functions */ - case structTypeKind /** < Structures */ - case arrayTypeKind /** < Arrays */ - case pointerTypeKind /** < Pointers */ - case vectorTypeKind /** < Fixed width SIMD vector type */ - case metadataTypeKind /** < Metadata */ - case x86_MMXTypeKind /** < X86 MMX */ - case tokenTypeKind /** < Tokens */ - case scalableVectorTypeKind /** < Scalable SIMD vector type */ - case bFloatTypeKind /** < 16 bit brain floating point type */ - case x86_AMXTypeKind /** < X86 AMX */ - case targetExtTypeKind /** < Target extension type */ - - public init?(ty: LLVMTypeKind) { - switch ty { - case LLVMVoidTypeKind: self = .voidTypeKind - case LLVMHalfTypeKind: self = .halfTypeKind - case LLVMFloatTypeKind: self = .floatTypeKind - case LLVMDoubleTypeKind: self = .doubleTypeKind - case LLVMX86_FP80TypeKind: self = .x86_FP80TypeKind - case LLVMFP128TypeKind: self = .fp128TypeKind - case LLVMPPC_FP128TypeKind: self = .ppc_FP128TypeKind - case LLVMLabelTypeKind: self = .labelTypeKind - case LLVMIntegerTypeKind: self = .integerTypeKind - case LLVMFunctionTypeKind: self = .functionTypeKind - case LLVMStructTypeKind: self = .structTypeKind - case LLVMArrayTypeKind: self = .arrayTypeKind - case LLVMPointerTypeKind: self = .pointerTypeKind - case LLVMVectorTypeKind: self = .vectorTypeKind - case LLVMMetadataTypeKind: self = .metadataTypeKind - case LLVMX86_MMXTypeKind: self = .x86_MMXTypeKind - case LLVMTokenTypeKind: self = .tokenTypeKind - case LLVMScalableVectorTypeKind: self = .scalableVectorTypeKind - case LLVMBFloatTypeKind: self = .bFloatTypeKind - case LLVMX86_AMXTypeKind: self = .x86_AMXTypeKind - case LLVMTargetExtTypeKind: self = .targetExtTypeKind - default: return nil - } - } -} - public struct Types: TypeRef { let llvm: LLVMTypeRef @@ -224,7 +173,7 @@ public struct Types: TypeRef { /// Obtain the enumerated type of a Type instance. public var getTypeKind: TypeKind { - TypeKind(ty: LLVMGetTypeKind(typeRef))! + TypeKind(from: LLVMGetTypeKind(typeRef))! } /// Whether the type has a known size. @@ -253,3 +202,132 @@ public extension Bool { /// Get `LLVM` representation for Boolean type var llvm: Int32 { self ? 1 : 0 } } + +/// Declarations for `LLVMOpcode` +public enum Opcode: UInt32 { + /* Terminator Instructions */ + case Ret = 1 + case Br = 2 + case Switch = 3 + case IndirectBr = 4 + case Invoke = 5 + /* removed 6 due to API changes */ + case Unreachable = 7 + case CallBr = 67 + + /* Standard Unary Operators */ + case FNeg = 66 + + /* Standard Binary Operators */ + case Add = 8 + case FAdd = 9 + case Sub = 10 + case FSub = 11 + case Mul = 12 + case FMul = 13 + case UDiv = 14 + case SDiv = 15 + case FDiv = 16 + case URem = 17 + case SRem = 18 + case FRem = 19 + + /* Logical Operators */ + case Shl = 20 + case LShr = 21 + case AShr = 22 + case And = 23 + case Or = 24 + case Xor = 25 + + /* Memory Operators */ + case Alloca = 26 + case Load = 27 + case Store = 28 + case GetElementPtr = 29 + + /* Cast Operators */ + case Trunc = 30 + case ZExt = 31 + case SExt = 32 + case FPToUI = 33 + case FPToSI = 34 + case UIToFP = 35 + case SIToFP = 36 + case FPTrunc = 37 + case FPExt = 38 + case PtrToInt = 39 + case IntToPtr = 40 + case BitCast = 41 + case AddrSpaceCast = 60 + + /* Other Operators */ + case ICmp = 42 + case FCmp = 43 + case PHI = 44 + case Call = 45 + case Select = 46 + case UserOp1 = 47 + case UserOp2 = 48 + case AArg = 49 + case ExtractElement = 50 + case InsertElement = 51 + case ShuffleVector = 52 + case ExtractValue = 53 + case InsertValue = 54 + case Freeze = 68 + + /* Atomic operators */ + case Fence = 55 + case AtomicCmpXchg = 56 + case AtomicRMW = 57 + + /* Exception Handling Operators */ + case Resume = 58 + case LandingPad = 59 + case CleanupRet = 61 + case CatchRet = 62 + case CatchPad = 63 + case CleanupPad = 64 + case CatchSwitch = 65 + + /// Init enum from `LLVMOpcode` + public init?(from val: LLVMOpcode) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMOpcode` from current type + public var llvm: LLVMOpcode { LLVMOpcode(rawValue: rawValue) } +} + +public enum TypeKind: UInt32 { + case VoidTypeKind = 0 /** < type with no size */ + case HalfTypeKind /** < 16 bit floating point type */ + case FloatTypeKind /** < 32 bit floating point type */ + case DoubleTypeKind /** < 64 bit floating point type */ + case X86_FP80TypeKind /** < 80 bit floating point type (X87) */ + case FP128TypeKind /** < 128 bit floating point type (112-bit mantissa) */ + case PPC_FP128TypeKind /** < 128 bit floating point type (two 64-bits) */ + case LabelTypeKind /** < Labels */ + case IntegerTypeKind /** < Arbitrary bit width integers */ + case FunctionTypeKind /** < Functions */ + case StructTypeKind /** < Structures */ + case ArrayTypeKind /** < Arrays */ + case PointerTypeKind /** < Pointers */ + case VectorTypeKind /** < Fixed width SIMD vector type */ + case MetadataTypeKind /** < Metadata */ + case X86_MMXTypeKind /** < X86 MMX */ + case TokenTypeKind /** < Tokens */ + case ScalableVectorTypeKind /** < Scalable SIMD vector type */ + case BFloatTypeKind /** < 16 bit brain floating point type */ + case X86_AMXTypeKind /** < X86 AMX */ + case TargetExtTypeKind /** < Target extension type */ + + /// Init enum from `LLVMTypeKind` + public init?(from ty: LLVMTypeKind) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMTypeKind` from current type + public var llvm: LLVMTypeKind { LLVMTypeKind(rawValue: rawValue) } +} From 9015a8c59e00472faa3c13ddf0ba4837e1ffd07e Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sat, 25 Sep 2021 01:21:34 +0200 Subject: [PATCH 08/38] Extend Types with: Linkage, Visibility, UnnamedAddr, DLLStorageClass, CallConv --- llvm-api/LLVM/Core/Types/Types.swift | 123 +++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift index 2ef6b96..abc98ed 100644 --- a/llvm-api/LLVM/Core/Types/Types.swift +++ b/llvm-api/LLVM/Core/Types/Types.swift @@ -331,3 +331,126 @@ public enum TypeKind: UInt32 { /// Get `LLVMTypeKind` from current type public var llvm: LLVMTypeKind { LLVMTypeKind(rawValue: rawValue) } } + +public enum Linkage: UInt32 { + case ExternalLinkage = 0 /** < Externally visible function */ + case AvailableExternallyLinkage + case LinkOnceAnyLinkage /** < Keep one copy of function when linking (inline) */ + case LinkOnceODRLinkage /** < Same, but only replaced by something equivalent. */ + case LinkOnceODRAutoHideLinkage /** < Obsolete */ + case WeakAnyLinkage /** < Keep one copy of function when linking (weak) */ + case WeakODRLinkage /** < Same, but only replaced by equivalent. */ + case AppendingLinkage /** < Special purpose, only applies to global arrays */ + case InternalLinkage /** < Rename collisions when linking functions) */ + case PrivateLinkage /** < Like Internal, but omit from symbol table */ + case DLLImportLinkage /** < Obsolete */ + case DLLExportLinkage /** < Obsolete */ + case ExternalWeakLinkage /** < ExternalWeak linkage description */ + case GhostLinkage /** < Obsolete */ + case CommonLinkage /** < Tentative definitions */ + case LinkerPrivateLinkage /** < Like Private, but linker removes. */ + case LinkerPrivateWeakLinkage /** < Like LinkerPrivate, but is weak. */ + + /// Init enum from `LLVMLinkage` + public init?(from ty: LLVMLinkage) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMLinkage` from current type + public var llvm: LLVMLinkage { LLVMLinkage(rawValue: rawValue) } +} + +public enum Visibility: UInt32 { + case DefaultVisibility = 0 /** < The GV is visible */ + case HiddenVisibility /** < The GV is hidden */ + case ProtectedVisibility /** < The GV is protected */ + + /// Init enum from `LLVMTVisibility` + public init?(from ty: LLVMVisibility) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMTypeKind` from current type + public var llvm: LLVMVisibility { LLVMVisibility(rawValue: rawValue) } +} + +public enum UnnamedAddr: UInt32 { + case NoUnnamedAddr = 0 /** < Address of the GV is significant. */ + case LocalUnnamedAddr /** < Address of the GV is locally insignificant. */ + case GlobalUnnamedAddr /** < Address of the GV is globally insignificant. */ + + /// Init enum from `LLVMUnnamedAddr` + public init?(from ty: LLVMUnnamedAddr) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMUnnamedAddr` from current type + public var llvm: LLVMUnnamedAddr { LLVMUnnamedAddr(rawValue: rawValue) } +} + +public enum DLLStorageClass: UInt32 { + case DefaultStorageClass = 0 + case DLLImportStorageClass = 1 /** < Function to be imported from DLL. */ + case DLLExportStorageClass = 2 /** < Function to be accessible from DLL. */ + + /// Init enum from `LLVMDLLStorageClass` + public init?(from ty: LLVMDLLStorageClass) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMDLLStorageClass` from current type + public var llvm: LLVMDLLStorageClass { LLVMDLLStorageClass(rawValue: rawValue) } +} + +public enum CallConv: UInt32 { + case CCallConv = 0 + case FastCallConv = 8 + case ColdCallConv = 9 + case GHCCallConv = 10 + case HiPECallConv = 11 + case WebKitJSCallConv = 12 + case AnyRegCallConv = 13 + case PreserveMostCallConv = 14 + case PreserveAllCallConv = 15 + case SwiftCallConv = 16 + case CXXFASTTLSCallConv = 17 + case X86StdcallCallConv = 64 + case X86FastcallCallConv = 65 + case ARMAPCSCallConv = 66 + case ARMAAPCSCallConv = 67 + case ARMAAPCSVFPCallConv = 68 + case MSP430INTRCallConv = 69 + case X86ThisCallCallConv = 70 + case PTXKernelCallConv = 71 + case PTXDeviceCallConv = 72 + case SPIRFUNCCallConv = 75 + case SPIRKERNELCallConv = 76 + case IntelOCLBICallConv = 77 + case X8664SysVCallConv = 78 + case Win64CallConv = 79 + case X86VectorCallCallConv = 80 + case HHVMCallConv = 81 + case HHVMCCallConv = 82 + case X86INTRCallConv = 83 + case AVRINTRCallConv = 84 + case AVRSIGNALCallConv = 85 + case AVRBUILTINCallConv = 86 + case AMDGPUVSCallConv = 87 + case AMDGPUGSCallConv = 88 + case AMDGPUPSCallConv = 89 + case AMDGPUCSCallConv = 90 + case AMDGPUKERNELCallConv = 91 + case X86RegCallCallConv = 92 + case AMDGPUHSCallConv = 93 + case MSP430BUILTINCallConv = 94 + case AMDGPULSCallConv = 95 + case AMDGPUESCallConv = 96 + + /// Init enum from `LLVMCallConv` + public init?(from ty: LLVMCallConv) { + self.init(rawValue: ty.rawValue) + } + + /// Get `LLVMCallConv` from current type + public var llvm: LLVMCallConv { LLVMCallConv(rawValue: rawValue) } +} From f03ee9653093582335377232ec9cda848c108038 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 26 Sep 2021 14:14:26 +0200 Subject: [PATCH 09/38] Extend types with: DiagnosticSeverity, AtomicRMWBinOp, AtomicOrdering, ThreadLocalMode, LandingPadClauseTy, RealPredicate, IntPredicate, ValueKind --- llvm-api/LLVM/Core/BasicBlock.swift | 2 +- llvm-api/LLVM/Core/Context.swift | 10 +- llvm-api/LLVM/Core/Core.swift | 6 +- llvm-api/LLVM/Core/Diagnostic.swift | 10 - llvm-api/LLVM/Core/Functions.swift | 2 +- llvm-api/LLVM/Core/Types/Array.swift | 2 +- llvm-api/LLVM/Core/Types/Float.swift | 2 +- llvm-api/LLVM/Core/Types/Function.swift | 2 +- llvm-api/LLVM/Core/Types/Int.swift | 2 +- llvm-api/LLVM/Core/Types/Other/Label.swift | 2 +- llvm-api/LLVM/Core/Types/Other/Metadata.swift | 2 +- .../LLVM/Core/Types/Other/TargetExt.swift | 2 +- llvm-api/LLVM/Core/Types/Other/Token.swift | 2 +- llvm-api/LLVM/Core/Types/Other/Void.swift | 2 +- llvm-api/LLVM/Core/Types/Other/X86AMX.swift | 2 +- llvm-api/LLVM/Core/Types/Other/X86MMX.swift | 2 +- llvm-api/LLVM/Core/Types/Pointer.swift | 2 +- llvm-api/LLVM/Core/Types/Struct.swift | 4 +- llvm-api/LLVM/Core/Types/Types.swift | 209 +++++++++++++++++- llvm-api/LLVM/Core/Types/Vector.swift | 2 +- utils/make-pkg-config.swift | 4 +- 21 files changed, 228 insertions(+), 45 deletions(-) diff --git a/llvm-api/LLVM/Core/BasicBlock.swift b/llvm-api/LLVM/Core/BasicBlock.swift index 94874ea..65cf61e 100644 --- a/llvm-api/LLVM/Core/BasicBlock.swift +++ b/llvm-api/LLVM/Core/BasicBlock.swift @@ -360,6 +360,6 @@ public struct BasicBlock: BasicBlockRef { extension BasicBlock: Equatable { public static func == (lhs: BasicBlock, rhs: BasicBlock) -> Bool { - return lhs.basicBlockRef == rhs.basicBlockRef + lhs.basicBlockRef == rhs.basicBlockRef } } diff --git a/llvm-api/LLVM/Core/Context.swift b/llvm-api/LLVM/Core/Context.swift index 08a1b16..d0c7f32 100644 --- a/llvm-api/LLVM/Core/Context.swift +++ b/llvm-api/LLVM/Core/Context.swift @@ -58,7 +58,7 @@ public class Context: ContextRef { /// Retrieve whether the given context is set to discard all value names. public func shouldDiscardValueNames() -> Bool { - return LLVMContextShouldDiscardValueNames(llvm) != 0 + LLVMContextShouldDiscardValueNames(llvm) != 0 } /// Set whether the given context discards all value names. @@ -76,7 +76,7 @@ public class Context: ContextRef { public var discardValueNames: Bool { get { // Retrieve whether the given context is set to discard all value names. - return shouldDiscardValueNames() + shouldDiscardValueNames() } set { // Set whether the given context discards all value names. @@ -204,17 +204,17 @@ public class Context: ContextRef { /// Check for the types of attributes. public static func isEnumAttribute(attributeRef: AttributeRef) -> Bool { - return LLVMIsEnumAttribute(attributeRef.attributeRef) != 0 + LLVMIsEnumAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. public static func isStringAttribute(attributeRef: AttributeRef) -> Bool { - return LLVMIsStringAttribute(attributeRef.attributeRef) != 0 + LLVMIsStringAttribute(attributeRef.attributeRef) != 0 } /// Check for the types of attributes. public static func isTypeAttribute(attributeRef: AttributeRef) -> Bool { - return LLVMIsTypeAttribute(attributeRef.attributeRef) != 0 + LLVMIsTypeAttribute(attributeRef.attributeRef) != 0 } /// Obtain a Type from a context by its registered name. diff --git a/llvm-api/LLVM/Core/Core.swift b/llvm-api/LLVM/Core/Core.swift index e9a19e2..3e0bd83 100644 --- a/llvm-api/LLVM/Core/Core.swift +++ b/llvm-api/LLVM/Core/Core.swift @@ -30,7 +30,7 @@ enum Core { /// /// - SeeAlso: `disposeLLVMMessage` public static func createMessage(with message: String) -> UnsafeMutablePointer? { - return message.withCString { cString in + message.withCString { cString in LLVMCreateMessage(cString) } } @@ -43,7 +43,7 @@ enum Core { /// This function permanently loads the dynamic library at the given path. /// It is safe to call this function multiple times for the same library. public static func loadLibraryPermanently(filename: String) -> Bool { - return filename.withCString { cString in + filename.withCString { cString in LLVMLoadLibraryPermanently(cString) != 0 } } @@ -67,7 +67,7 @@ enum Core { /// libraries for the symbol `symbolName`. If it is found, the address of /// that symbol is returned. If not, null is returned. public static func searchForAddressOfSymbol(symbolName: String) -> UnsafeMutableRawPointer? { - return symbolName.withCString { cString in + symbolName.withCString { cString in LLVMSearchForAddressOfSymbol(cString) } } diff --git a/llvm-api/LLVM/Core/Diagnostic.swift b/llvm-api/LLVM/Core/Diagnostic.swift index 3b70ebd..f57d6c8 100644 --- a/llvm-api/LLVM/Core/Diagnostic.swift +++ b/llvm-api/LLVM/Core/Diagnostic.swift @@ -21,13 +21,3 @@ public struct Diagnostic: DiagnosticInfoRef { } } -public enum DiagnosticSeverity: Int { - case error = 0 - case warning = 1 - case remark = 2 - case note = 3 - - public init?(from cSeverity: LLVMDiagnosticSeverity) { - self.init(rawValue: Int(cSeverity.rawValue)) - } -} diff --git a/llvm-api/LLVM/Core/Functions.swift b/llvm-api/LLVM/Core/Functions.swift index 215917f..ddf12ef 100644 --- a/llvm-api/LLVM/Core/Functions.swift +++ b/llvm-api/LLVM/Core/Functions.swift @@ -130,6 +130,6 @@ public struct Function: ValueRef { extension Function: Equatable { public static func == (lhs: Function, rhs: Function) -> Bool { - return lhs.valueRef == rhs.valueRef + lhs.valueRef == rhs.valueRef } } diff --git a/llvm-api/LLVM/Core/Types/Array.swift b/llvm-api/LLVM/Core/Types/Array.swift index 7cc47b2..9acaa2e 100644 --- a/llvm-api/LLVM/Core/Types/Array.swift +++ b/llvm-api/LLVM/Core/Types/Array.swift @@ -107,6 +107,6 @@ public struct ArrayType: TypeRef { extension ArrayType: Equatable { public static func == (lhs: ArrayType, rhs: ArrayType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Float.swift b/llvm-api/LLVM/Core/Types/Float.swift index 5eaa7ea..c39cfd1 100644 --- a/llvm-api/LLVM/Core/Types/Float.swift +++ b/llvm-api/LLVM/Core/Types/Float.swift @@ -152,6 +152,6 @@ public class PPCFP128Type: FloatingType { extension FloatingType: Equatable { public static func == (lhs: FloatingType, rhs: FloatingType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Function.swift b/llvm-api/LLVM/Core/Types/Function.swift index f62759d..ae75be4 100644 --- a/llvm-api/LLVM/Core/Types/Function.swift +++ b/llvm-api/LLVM/Core/Types/Function.swift @@ -77,6 +77,6 @@ public struct FunctionType: TypeRef { extension FunctionType: Equatable { public static func == (lhs: FunctionType, rhs: FunctionType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Int.swift b/llvm-api/LLVM/Core/Types/Int.swift index 89b4685..9704bc9 100644 --- a/llvm-api/LLVM/Core/Types/Int.swift +++ b/llvm-api/LLVM/Core/Types/Int.swift @@ -157,6 +157,6 @@ public class Int128Type: IntType { extension IntType: Equatable { public static func == (lhs: IntType, rhs: IntType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/Label.swift b/llvm-api/LLVM/Core/Types/Other/Label.swift index 0209d1e..4d0168b 100644 --- a/llvm-api/LLVM/Core/Types/Other/Label.swift +++ b/llvm-api/LLVM/Core/Types/Other/Label.swift @@ -31,6 +31,6 @@ public struct LabelType: TypeRef { extension LabelType: Equatable { public static func == (lhs: LabelType, rhs: LabelType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/Metadata.swift b/llvm-api/LLVM/Core/Types/Other/Metadata.swift index 691d001..4d86114 100644 --- a/llvm-api/LLVM/Core/Types/Other/Metadata.swift +++ b/llvm-api/LLVM/Core/Types/Other/Metadata.swift @@ -26,6 +26,6 @@ public struct MetadataType: TypeRef { extension MetadataType: Equatable { public static func == (lhs: MetadataType, rhs: MetadataType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/TargetExt.swift b/llvm-api/LLVM/Core/Types/Other/TargetExt.swift index 4dc52e1..a6faec5 100644 --- a/llvm-api/LLVM/Core/Types/Other/TargetExt.swift +++ b/llvm-api/LLVM/Core/Types/Other/TargetExt.swift @@ -37,6 +37,6 @@ public struct TargetExtType: TypeRef { extension TargetExtType: Equatable { public static func == (lhs: TargetExtType, rhs: TargetExtType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/Token.swift b/llvm-api/LLVM/Core/Types/Other/Token.swift index fca3db1..d0b2a5f 100644 --- a/llvm-api/LLVM/Core/Types/Other/Token.swift +++ b/llvm-api/LLVM/Core/Types/Other/Token.swift @@ -27,6 +27,6 @@ public struct TokenType: TypeRef { extension TokenType: Equatable { public static func == (lhs: TokenType, rhs: TokenType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/Void.swift b/llvm-api/LLVM/Core/Types/Other/Void.swift index c0630b6..6e99b1a 100644 --- a/llvm-api/LLVM/Core/Types/Other/Void.swift +++ b/llvm-api/LLVM/Core/Types/Other/Void.swift @@ -31,6 +31,6 @@ public struct VoidType: TypeRef { extension VoidType: Equatable { public static func == (lhs: VoidType, rhs: VoidType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/X86AMX.swift b/llvm-api/LLVM/Core/Types/Other/X86AMX.swift index 1624717..91905da 100644 --- a/llvm-api/LLVM/Core/Types/Other/X86AMX.swift +++ b/llvm-api/LLVM/Core/Types/Other/X86AMX.swift @@ -31,6 +31,6 @@ public struct X86AMXType: TypeRef { extension X86AMXType: Equatable { public static func == (lhs: X86AMXType, rhs: X86AMXType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Other/X86MMX.swift b/llvm-api/LLVM/Core/Types/Other/X86MMX.swift index bfc9208..a065b22 100644 --- a/llvm-api/LLVM/Core/Types/Other/X86MMX.swift +++ b/llvm-api/LLVM/Core/Types/Other/X86MMX.swift @@ -36,6 +36,6 @@ public struct X86MMXType: TypeRef { extension X86MMXType: Equatable { public static func == (lhs: X86MMXType, rhs: X86MMXType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Pointer.swift b/llvm-api/LLVM/Core/Types/Pointer.swift index 5c6fef4..64c3421 100644 --- a/llvm-api/LLVM/Core/Types/Pointer.swift +++ b/llvm-api/LLVM/Core/Types/Pointer.swift @@ -87,6 +87,6 @@ public struct PointerType: TypeRef { extension PointerType: Equatable { public static func == (lhs: PointerType, rhs: PointerType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Struct.swift b/llvm-api/LLVM/Core/Types/Struct.swift index a48cf49..53737df 100644 --- a/llvm-api/LLVM/Core/Types/Struct.swift +++ b/llvm-api/LLVM/Core/Types/Struct.swift @@ -66,7 +66,7 @@ public struct StructType: TypeRef { /// Determine whether a structure is opaque. public static func isOpaqueStruct(typeRef: TypeRef) -> Bool { - return LLVMIsOpaqueStruct(typeRef.typeRef) != 0 + LLVMIsOpaqueStruct(typeRef.typeRef) != 0 } /// Determine whether a structure is packed. @@ -169,6 +169,6 @@ public struct StructType: TypeRef { extension StructType: Equatable { public static func == (lhs: StructType, rhs: StructType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift index abc98ed..4ceebff 100644 --- a/llvm-api/LLVM/Core/Types/Types.swift +++ b/llvm-api/LLVM/Core/Types/Types.swift @@ -324,8 +324,8 @@ public enum TypeKind: UInt32 { case TargetExtTypeKind /** < Target extension type */ /// Init enum from `LLVMTypeKind` - public init?(from ty: LLVMTypeKind) { - self.init(rawValue: ty.rawValue) + public init?(from val: LLVMTypeKind) { + self.init(rawValue: val.rawValue) } /// Get `LLVMTypeKind` from current type @@ -366,8 +366,8 @@ public enum Visibility: UInt32 { case ProtectedVisibility /** < The GV is protected */ /// Init enum from `LLVMTVisibility` - public init?(from ty: LLVMVisibility) { - self.init(rawValue: ty.rawValue) + public init?(from val: LLVMVisibility) { + self.init(rawValue: val.rawValue) } /// Get `LLVMTypeKind` from current type @@ -394,8 +394,8 @@ public enum DLLStorageClass: UInt32 { case DLLExportStorageClass = 2 /** < Function to be accessible from DLL. */ /// Init enum from `LLVMDLLStorageClass` - public init?(from ty: LLVMDLLStorageClass) { - self.init(rawValue: ty.rawValue) + public init?(from val: LLVMDLLStorageClass) { + self.init(rawValue: val.rawValue) } /// Get `LLVMDLLStorageClass` from current type @@ -447,10 +447,203 @@ public enum CallConv: UInt32 { case AMDGPUESCallConv = 96 /// Init enum from `LLVMCallConv` - public init?(from ty: LLVMCallConv) { - self.init(rawValue: ty.rawValue) + public init?(from val: LLVMCallConv) { + self.init(rawValue: val.rawValue) } /// Get `LLVMCallConv` from current type public var llvm: LLVMCallConv { LLVMCallConv(rawValue: rawValue) } } + +public enum ValueKind: UInt32 { + case ArgumentValueKind = 0 + case BasicBlockValueKind + case MemoryUseValueKind + case MemoryDefValueKind + case MemoryPhiValueKind + + case FunctionValueKind + case GlobalAliasValueKind + case GlobalIFuncValueKind + case GlobalVariableValueKind + case lockAddressValueKind + case ConstantExprValueKind + case ConstantArrayValueKind + case ConstantStructValueKind + case ConstantVectorValueKind + + case UndefValueValueKind + case ConstantAggregateZeroValueKind + case ConstantDataArrayValueKind + case ConstantDataVectorValueKind + case ConstantIntValueKind + case ConstantFPValueKind + case ConstantPointerNullValueKind + case ConstantTokenNoneValueKind + + case MetadataAsValueValueKind + case InlineAsmValueKind + + case InstructionValueKind + case PoisonValueValueKind + case ConstantTargetNoneValueKind + + /// Init enum from `LLVMValueKind` + public init?(from val: LLVMValueKind) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMValueKind` from current type + public var llvm: LLVMValueKind { LLVMValueKind(rawValue: rawValue) } +} + +public enum IntPredicate: UInt32 { + case IntEQ = 32 /** < equal */ + case IntNE /** < not equal */ + case IntUGT /** < unsigned greater than */ + case IntUGE /** < unsigned greater or equal */ + case IntULT /** < unsigned less than */ + case IntULE /** < unsigned less or equal */ + case IntSGT /** < signed greater than */ + case IntSGE /** < signed greater or equal */ + case IntSLT /** < signed less than */ + case IntSLE /** < signed less or equal */ + + /// Init enum from `LLVMIntPredicate` + public init?(from val: LLVMIntPredicate) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMIntPredicate` from current type + public var llvm: LLVMIntPredicate { LLVMIntPredicate(rawValue: rawValue) } +} + +public enum RealPredicate: UInt32 { + case RealPredicateFalse = 0 /** < Always false (always folded) */ + case RealOEQ /** < True if ordered and equal */ + case EealOGT /** < True if ordered and greater than */ + case RealOGE /** < True if ordered and greater than or equal */ + case RealOLT /** < True if ordered and less than */ + case RealOLE /** < True if ordered and less than or equal */ + case RealONE /** < True if ordered and operands are unequal */ + case RealORD /** < True if ordered (no nans) */ + case RealUNO /** < True if unordered: isnan(X) | isnan(Y) */ + case RealUEQ /** < True if unordered or equal */ + case RealUGT /** < True if unordered or greater than */ + case RealUGE /** < True if unordered, greater than, or equal */ + case RealULT /** < True if unordered or less than */ + case RealULE /** < True if unordered, less than, or equal */ + case RealUNE /** < True if unordered or not equal */ + case RealPredicateTrue /** < Always true (always folded) */ + + /// Init enum from `LLVMRealPredicate` + public init?(from val: LLVMRealPredicate) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMRealPredicate` from current type + public var llvm: LLVMRealPredicate { LLVMRealPredicate(rawValue: rawValue) } +} + +public enum LandingPadClauseTy: UInt32 { + case LandingPadCatch = 0 /** < A catch clause */ + case LandingPadFilter /** < A filter clause */ + + /// Init enum from `LLVMLandingPadClauseTy` + public init?(from val: LLVMLandingPadClauseTy) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMLandingPadClauseTy` from current type + public var llvm: LLVMLandingPadClauseTy { LLVMLandingPadClauseTy(rawValue: rawValue) } +} + +public enum ThreadLocalMode: UInt32 { + case NotThreadLocal = 0 + case GeneralDynamicTLSModel + case LocalDynamicTLSModel + case InitialExecTLSModel + case LocalExecTLSModel + + /// Init enum from `LLVMThreadLocalMode` + public init?(from val: LLVMThreadLocalMode) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMThreadLocalMode` from current type + public var llvm: LLVMThreadLocalMode { LLVMThreadLocalMode(rawValue: rawValue) } +} + +public enum AtomicOrdering: UInt32 { + case AtomicOrderingNotAtomic = 0 /** < A load or store which is not atomic */ + case AtomicOrderingUnordered = 1 /** < Lowest level of atomicity, guarantees + somewhat sane results, lock free. */ + case AtomicOrderingMonotonic = 2 /** < guarantees that if you take all the + operations affecting a specific address, + a consistent ordering exists */ + case AtomicOrderingAcquire = 4 /** < Acquire provides a barrier of the sort + necessary to acquire a lock to access other + memory with normal loads and stores. */ + case AtomicOrderingRelease = 5 /** < Release is similar to Acquire, but with + a barrier of the sort necessary to release + a lock. */ + case AtomicOrderingAcquireRelease = 6 /** < provides both an Acquire and a + Release barrier (for fences and + operations which both read and write + memory). */ + case AtomicOrderingSequentiallyConsistent = 7 /** < provides Acquire semantics + for loads and Release + semantics for stores. + Additionally, it guarantees + that a total ordering exists + between all + SequentiallyConsistent + operations. */ + /// Init enum from `LLVMAtomicOrdering` + public init?(from val: LLVMAtomicOrdering) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMAtomicOrdering` from current type + public var llvm: LLVMAtomicOrdering { LLVMAtomicOrdering(rawValue: rawValue) } +} + +public enum AtomicRMWBinOp: UInt32 { + case AtomicRMWBinOpXchg = 0 /** < Set the new value and return the one old */ + case AtomicRMWBinOpAdd /** < Add a value and return the old one */ + case AtomicRMWBinOpSub /** < Subtract a value and return the old one */ + case AtomicRMWBinOpAnd /** < And a value and return the old one */ + case AtomicRMWBinOpNand /** < Not-And a value and return the old one */ + case AtomicRMWBinOpOr /** < OR a value and return the old one */ + case AtomicRMWBinOpXor /** < Xor a value and return the old one */ + case AtomicRMWBinOpMax /** < Sets the value if it's greater than the original using a signed comparison and return the old one */ + case AtomicRMWBinOpMin /** < Sets the value if it's Smaller than the original using a signed comparison and return the old one */ + case AtomicRMWBinOpUMax /** < Sets the value if it's greater than the original using an unsigned comparison and return the old one */ + case AtomicRMWBinOpUMin /** < Sets the value if it's greater than the original using an unsigned comparison and return the old one */ + case AtomicRMWBinOpFAdd /** < Add a floating point value and return the old one */ + case AtomicRMWBinOpFSub /** < Subtract a floating point value and return the old one */ + case AtomicRMWBinOpFMax /** < Sets the value if it's greater than the original using an floating point comparison return the old one */ + case AtomicRMWBinOpFMin /** < Sets the value if it's smaller than the original using an floating point comparison and return the old one */ + /// Init enum from `LLVMAtomicRMWBinOp` + public init?(from val: LLVMAtomicRMWBinOp) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMAtomicRMWBinOp` from current type + public var llvm: LLVMAtomicRMWBinOp { LLVMAtomicRMWBinOp(rawValue: rawValue) } +} + +public enum DiagnosticSeverity: UInt32 { + case DSError = 0 + case DSWarning + case DSRemark + case DSNote + + /// Init enum from `LLVMDiagnosticSeverity` + public init?(from val: LLVMDiagnosticSeverity) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMDiagnosticSeverity` from current type + public var llvm: LLVMDiagnosticSeverity { LLVMDiagnosticSeverity(rawValue: rawValue) } +} diff --git a/llvm-api/LLVM/Core/Types/Vector.swift b/llvm-api/LLVM/Core/Types/Vector.swift index e1b03a0..93c6ec8 100644 --- a/llvm-api/LLVM/Core/Types/Vector.swift +++ b/llvm-api/LLVM/Core/Types/Vector.swift @@ -79,7 +79,7 @@ public class VectorType: TypeRef { extension VectorType: Equatable { public static func == (lhs: VectorType, rhs: VectorType) -> Bool { - return lhs.typeRef == rhs.typeRef + lhs.typeRef == rhs.typeRef } } diff --git a/utils/make-pkg-config.swift b/utils/make-pkg-config.swift index 915a00d..22d7512 100755 --- a/utils/make-pkg-config.swift +++ b/utils/make-pkg-config.swift @@ -28,7 +28,7 @@ func run(_ path: String, args: [String] = []) -> String? { /// Finds the location of the provided binary on your system. func which(_ name: String) -> String? { - return run("/usr/bin/which", args: [name]) + run("/usr/bin/which", args: [name]) } extension String: Error { @@ -37,7 +37,7 @@ extension String: Error { func replacing(charactersIn characterSet: CharacterSet, with separator: String) -> String { - let components = self.components(separatedBy: characterSet) + let components = components(separatedBy: characterSet) return components.joined(separator: separator) } } From 21ad77682b6a740083c7ea240d2d56366fc63ae3 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 28 Sep 2021 17:38:45 +0200 Subject: [PATCH 10/38] Added Types: attributes --- llvm-api/LLVM/Core/Diagnostic.swift | 1 - llvm-api/LLVM/Core/Types/Types.swift | 120 ++++++++++++++++++++++----- 2 files changed, 97 insertions(+), 24 deletions(-) diff --git a/llvm-api/LLVM/Core/Diagnostic.swift b/llvm-api/LLVM/Core/Diagnostic.swift index f57d6c8..10d0ba8 100644 --- a/llvm-api/LLVM/Core/Diagnostic.swift +++ b/llvm-api/LLVM/Core/Diagnostic.swift @@ -20,4 +20,3 @@ public struct Diagnostic: DiagnosticInfoRef { Context.getDiagInfoSeverity(diagnosticInfo: self) } } - diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift index 4ceebff..216507a 100644 --- a/llvm-api/LLVM/Core/Types/Types.swift +++ b/llvm-api/LLVM/Core/Types/Types.swift @@ -576,29 +576,21 @@ public enum ThreadLocalMode: UInt32 { public enum AtomicOrdering: UInt32 { case AtomicOrderingNotAtomic = 0 /** < A load or store which is not atomic */ - case AtomicOrderingUnordered = 1 /** < Lowest level of atomicity, guarantees - somewhat sane results, lock free. */ - case AtomicOrderingMonotonic = 2 /** < guarantees that if you take all the - operations affecting a specific address, - a consistent ordering exists */ - case AtomicOrderingAcquire = 4 /** < Acquire provides a barrier of the sort - necessary to acquire a lock to access other - memory with normal loads and stores. */ - case AtomicOrderingRelease = 5 /** < Release is similar to Acquire, but with - a barrier of the sort necessary to release - a lock. */ - case AtomicOrderingAcquireRelease = 6 /** < provides both an Acquire and a - Release barrier (for fences and - operations which both read and write - memory). */ - case AtomicOrderingSequentiallyConsistent = 7 /** < provides Acquire semantics - for loads and Release - semantics for stores. - Additionally, it guarantees - that a total ordering exists - between all - SequentiallyConsistent - operations. */ + /// Lowest level of atomicity, guarantees somewhat sane results, lock free. + case AtomicOrderingUnordered = 1 + /// guarantees that if you take all the operations affecting a specific address, a consistent ordering exists + case AtomicOrderingMonotonic = 2 + /// Acquire provides a barrier of the sort + /// necessary to acquire a lock to access other memory with normal loads and stores. + case AtomicOrderingAcquire = 4 + /// Release is similar to Acquire, but with a barrier of the sort necessary to release a lock. + case AtomicOrderingRelease = 5 + /// provides both an Acquire and Release barrier (for fences and operations which both read and memory). + case AtomicOrderingAcquireRelease = 6 + /// provides Acquire semantics for loads and Release semantics for stores. + /// Additionally, it guarantees that a total ordering exists between + /// SequentiallyConsistent operations. + case AtomicOrderingSequentiallyConsistent = 7 /// Init enum from `LLVMAtomicOrdering` public init?(from val: LLVMAtomicOrdering) { self.init(rawValue: val.rawValue) @@ -647,3 +639,85 @@ public enum DiagnosticSeverity: UInt32 { /// Get `LLVMDiagnosticSeverity` from current type public var llvm: LLVMDiagnosticSeverity { LLVMDiagnosticSeverity(rawValue: rawValue) } } + +public enum InlineAsmDialect: UInt32 { + case InlineAsmDialectATT = 0 + case InlineAsmDialectIntel + + /// Init enum from `LLVMInlineAsmDialect` + public init?(from val: LLVMInlineAsmDialect) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMInlineAsmDialect` from current type + public var llvm: LLVMInlineAsmDialect { LLVMInlineAsmDialect(rawValue: rawValue) } +} + +public enum ModuleFlagBehavior: UInt32 { + /// Emits an error if two values disagree, otherwise the resulting value is + /// that of the operands. + case ModuleFlagBehaviorError = 0 + + /// Emits a warning if two values disagree. The result value will be the + /// operand for the flag from the first module being linked. + case ModuleFlagBehaviorWarning + + /// Adds a requirement that another module flag be present and have a + /// specified value after linking is performed. The value must be a metadata + /// pair, where the first element of the pair is the ID of the module flag + /// to be restricted, and the second element of the pair is the value the + /// module flag should be restricted to. This behavior can be used to + /// restrict the allowable results (via triggering of an error) of linking + /// IDs with the **Override** behavior. + case ModuleFlagBehaviorRequire + + /// Uses the specified value, regardless of the behavior or value of the + /// other module. If both modules specify **Override**, but the values + /// differ, an error will be emitted. + case ModuleFlagBehaviorOverride + + /// Appends the two values, which are required to be metadata nodes. + case ModuleFlagBehaviorAppend + + /// Appends the two values, which are required to be metadata + /// nodes. However, duplicate entries in the second list are dropped + /// during the append operation. + case ModuleFlagBehaviorAppendUnique + + /// Init enum from `LLVMModuleFlagBehavior` + public init?(from val: LLVMModuleFlagBehavior) { + self.init(rawValue: val.rawValue) + } + + /// Get `LLVMModuleFlagBehavior` from current type + public var llvm: LLVMModuleFlagBehavior { LLVMModuleFlagBehavior(rawValue: rawValue) } +} + +/// Attribute index is parameter number from 1 to N. +public struct AttributeIndex2 { + let llvm: LLVMAttributeIndex + + public init?(from val: LLVMAttributeIndex) { + llvm = val + } + + public init(index: UInt32) { + llvm = LLVMAttributeIndex(index) + } + + /// Get attribute index + public var index: UInt32 { llvm } +} + +/// `LLVMAttributeReturnIndex` is anonymous enum +public struct AttributeReturnIndex { + public var llvm = LLVMAttributeReturnIndex +} + +/// `LLVMAttributeFunctionIndex` is anonymous enum +/// ISO C restricts enumerator values to range of 'int' +/// (4294967295 is too large) +/// LLVMAttributeFunctionIndex = ~0U, +public struct AttributeFunctionIndex { + public var llvm = LLVMAttributeFunctionIndex +} From 169d1de1118e7afdf6752435857d491e90fd59ab Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 1 Oct 2021 01:17:03 +0200 Subject: [PATCH 11/38] Added Constants --- llvm-api/LLVM/Core/BasicBlock.swift | 16 +++++--- .../Core/Values/Constants/Constants.swift | 40 +++++++++++++++++++ .../Core/Values/{Values.swift => Value.swift} | 2 +- 3 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 llvm-api/LLVM/Core/Values/Constants/Constants.swift rename llvm-api/LLVM/Core/Values/{Values.swift => Value.swift} (91%) diff --git a/llvm-api/LLVM/Core/BasicBlock.swift b/llvm-api/LLVM/Core/BasicBlock.swift index 65cf61e..9bac86a 100644 --- a/llvm-api/LLVM/Core/BasicBlock.swift +++ b/llvm-api/LLVM/Core/BasicBlock.swift @@ -97,6 +97,12 @@ public struct BasicBlock: BasicBlockRef { self.context = context } + /// Create a new basic block without inserting it into a function. + public static func createBasicBlockInContext(context: Context, name: String) -> BasicBlockRef? { + guard let blockRef = LLVMCreateBasicBlockInContext(context.contextRef, name) else { return nil } + return BasicBlock(llvm: blockRef) + } + /// Given that this block and a given block share a parent function, move this /// block before the given block in that function's basic block list. /// @@ -146,7 +152,7 @@ public struct BasicBlock: BasicBlockRef { /// Returns the first instruction in the basic block, if it exists. public static func getFirstInstruction(basicBlock: BasicBlockRef) -> ValueRef? { guard let val = LLVMGetFirstInstruction(basicBlock.basicBlockRef) else { return nil } - return Values(llvm: val) + return Value(llvm: val) } /// Returns the first instruction in the basic block, if it exists. @@ -157,7 +163,7 @@ public struct BasicBlock: BasicBlockRef { /// Returns the first instruction in the basic block, if it exists. public static func getLastInstruction(basicBlock: BasicBlockRef) -> ValueRef? { guard let val = LLVMGetLastInstruction(basicBlock.basicBlockRef) else { return nil } - return Values(llvm: val) + return Value(llvm: val) } /// Returns the parent function of this basic block, if it exists. @@ -249,7 +255,7 @@ public struct BasicBlock: BasicBlockRef { /// Convert a basic block instance to a value type. public static func basicBlockAsValue(basicBlockRef: BasicBlockRef) -> ValueRef? { guard let valueRef = LLVMBasicBlockAsValue(basicBlockRef.basicBlockRef) else { return nil } - return Values(llvm: valueRef) + return Value(llvm: valueRef) } /// Determine whether an LLVMValueRef is itself a basic block. @@ -347,14 +353,14 @@ public struct BasicBlock: BasicBlockRef { /// Returns the terminator instruction for current block. If a basic block is well formed or `nil` if it is not well formed. public var getBasicBlockTerminator: ValueRef? { guard let valueRef = LLVMGetBasicBlockTerminator(llvm) else { return nil } - return Values(llvm: valueRef) + return Value(llvm: valueRef) } /// Returns the terminator instruction if a basic block is well formed or `nil` if it is not well formed. /// The returned LLVMValueRef corresponds to an llvm::Instruction. public static func getBasicBlockTerminator(basicBlockRef: BasicBlockRef) -> ValueRef? { guard let valueRef = LLVMGetBasicBlockTerminator(basicBlockRef.basicBlockRef) else { return nil } - return Values(llvm: valueRef) + return Value(llvm: valueRef) } } diff --git a/llvm-api/LLVM/Core/Values/Constants/Constants.swift b/llvm-api/LLVM/Core/Values/Constants/Constants.swift new file mode 100644 index 0000000..fa88c11 --- /dev/null +++ b/llvm-api/LLVM/Core/Values/Constants/Constants.swift @@ -0,0 +1,40 @@ +import CLLVM + +/// This section contains APIs for interacting with LLVMValueRef that correspond to llvm::Constant instances. More... +public enum Constants { + /// Obtain a constant value referring to the null instance of a type. + public static func constNull(typeRef: TypeRef) -> Value? { + guard let valueRef = LLVMConstNull(typeRef.typeRef) else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value referring to the instance of a type consisting of all ones. + /// This is only valid for integer types. + public static func constAllOnes(typeRef: TypeRef) -> Value? { + guard let valueRef = LLVMConstAllOnes(typeRef.typeRef) else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value referring to an undefined value of a type. + public static func getUndef(typeRef: TypeRef) -> Value? { + guard let valueRef = LLVMGetUndef(typeRef.typeRef) else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value referring to a poison value of a type. + public static func getPoison(typeRef: TypeRef) -> Value? { + guard let valueRef = LLVMGetPoison(typeRef.typeRef) else { return nil } + return Value(llvm: valueRef) + } + + // Determine whether a value instance is null. + public static func constPointerNull(valueRef: ValueRef) -> Bool { + LLVMIsNull(valueRef.valueRef) != 0 + } + + /// Obtain a constant that is a constant pointer pointing to NULL for a specified type. + public static func constPointerNull(typeRef: TypeRef) -> Value? { + guard let valueRef = LLVMConstPointerNull(typeRef.typeRef) else { return nil } + return Value(llvm: valueRef) + } +} diff --git a/llvm-api/LLVM/Core/Values/Values.swift b/llvm-api/LLVM/Core/Values/Value.swift similarity index 91% rename from llvm-api/LLVM/Core/Values/Values.swift rename to llvm-api/LLVM/Core/Values/Value.swift index f91e96b..f5dac51 100644 --- a/llvm-api/LLVM/Core/Values/Values.swift +++ b/llvm-api/LLVM/Core/Values/Value.swift @@ -1,6 +1,6 @@ import CLLVM -public struct Values: ValueRef { +public struct Value: ValueRef { let llvm: LLVMValueRef /// Retrieves the underlying LLVM type object. From f20adb8db57a3f7d9f3c1ef332a8bc897ed7786c Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sat, 2 Oct 2021 01:18:28 +0200 Subject: [PATCH 12/38] Scalar constants --- .../LLVM/Core/Values/Constants/Scalar.swift | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 llvm-api/LLVM/Core/Values/Constants/Scalar.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Scalar.swift b/llvm-api/LLVM/Core/Values/Constants/Scalar.swift new file mode 100644 index 0000000..e563dd2 --- /dev/null +++ b/llvm-api/LLVM/Core/Values/Constants/Scalar.swift @@ -0,0 +1,90 @@ +import CLLVM + +/// Functions in this group model ValueRef instances that correspond to constants referring to scalar types. +public enum ScalarConstants { + /// Obtain a constant value for an integer type. + public static func constInt(intTy: TypeRef, n: UInt64, signExtend: Bool) -> Value? { + guard let valueRef = LLVMConstInt(intTy.typeRef, n, signExtend.llvm) else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value for an integer of arbitrary precision. + public static func constIntOfArbitraryPrecision(intType: TypeRef, words: [UInt64]) -> Value? { + let numWords = UInt32(words.count) + let val = words.withUnsafeBufferPointer { bufferPointer in + LLVMConstIntOfArbitraryPrecision(intType.typeRef, numWords, bufferPointer.baseAddress) + } + guard let valueRef = val else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value for an integer parsed from a string. + /// A similar API, `constIntOfStringAndSize` is also available. If the + /// string's length is available, it is preferred to call that function instead. + public static func constIntOfString(intType: TypeRef, text: String, radix: UInt8) -> Value? { + let val = text.withCString { cString in + LLVMConstIntOfString(intType.typeRef, cString, radix) + } + guard let valueRef = val else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value for an integer parsed from a string with specified length. + public static func constIntOfStringAndSize(intType: TypeRef, text: String, radix: UInt8) -> Value? { + let val = text.withCString { cString in + let length = UInt32(text.utf8.count) + return LLVMConstIntOfStringAndSize(intType.typeRef, cString, length, radix) + } + guard let valueRef = val else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant value referring to a double floating point value. + public static func constReal(realType: TypeRef, n: Double) -> Value? { + guard let valueRef = LLVMConstReal(realType.typeRef, n) else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant for a floating point value parsed from a string. + /// A similar API, LLVMConstRealOfStringAndSize is also available. It + /// should be used if the input string's length is known. + public static func constRealOfString(realType: TypeRef, text: String) -> Value? { + let val = text.withCString { cString in + LLVMConstRealOfString(realType.typeRef, cString) + } + guard let valueRef = val else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain a constant for a floating point value parsed from a string. + public static func constRealOfStringAndSize(realType: TypeRef, text: String) -> Value? { + let val = text.withCString { cString in + let length = UInt32(text.utf8.count) + return LLVMConstRealOfStringAndSize(realType.typeRef, cString, length) + } + guard let valueRef = val else { return nil } + return Value(llvm: valueRef) + } + + /// Obtain the zero extended value for an integer constant value. + // unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal); +// public static func getLLVMConstIntZExtValue(constantVal: LLVMValueRef) -> UInt64 { +// return LLVMConstIntGetZExtValue(constantVal) +// } + + + /// Obtain the sign extended value for an integer constant value. + // long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal); +// public static func constIntSExtValue(constantVal: LLVMValueRef) -> Int64 { +// return LLVMConstIntGetSExtValue(constantVal) +// } + + /// Obtain the double value for an floating point constant value. + /// losesInfo indicates if some precision was lost in the conversion. + // double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *losesInfo); + // public static func constRealGetDouble(constantVal: LLVMValueRef) -> (Double, Bool) { +// var losesInfo: LLVMBool = 0 +// let result = LLVMConstRealGetDouble(constantVal, &losesInfo) +// return (result, losesInfo != 0) +// } +} From 7ce4e175cfc5733b48dba8171871d98c5163b5bd Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 3 Oct 2021 09:36:08 +0200 Subject: [PATCH 13/38] Scalar constants - extend --- .../LLVM/Core/Values/Constants/Scalar.swift | 69 ++++++++----------- 1 file changed, 30 insertions(+), 39 deletions(-) diff --git a/llvm-api/LLVM/Core/Values/Constants/Scalar.swift b/llvm-api/LLVM/Core/Values/Constants/Scalar.swift index e563dd2..50cfac7 100644 --- a/llvm-api/LLVM/Core/Values/Constants/Scalar.swift +++ b/llvm-api/LLVM/Core/Values/Constants/Scalar.swift @@ -1,90 +1,81 @@ import CLLVM /// Functions in this group model ValueRef instances that correspond to constants referring to scalar types. -public enum ScalarConstants { +public enum ScalarConstant { /// Obtain a constant value for an integer type. - public static func constInt(intTy: TypeRef, n: UInt64, signExtend: Bool) -> Value? { - guard let valueRef = LLVMConstInt(intTy.typeRef, n, signExtend.llvm) else { return nil } + public static func constInt(intTy: TypeRef, n: UInt64, signExtend: Bool) -> Value { + let valueRef = LLVMConstInt(intTy.typeRef, n, signExtend.llvm)! return Value(llvm: valueRef) } /// Obtain a constant value for an integer of arbitrary precision. public static func constIntOfArbitraryPrecision(intType: TypeRef, words: [UInt64]) -> Value? { let numWords = UInt32(words.count) - let val = words.withUnsafeBufferPointer { bufferPointer in - LLVMConstIntOfArbitraryPrecision(intType.typeRef, numWords, bufferPointer.baseAddress) + let valueRef = words.withUnsafeBufferPointer { bufferPointer in + LLVMConstIntOfArbitraryPrecision(intType.typeRef, numWords, bufferPointer.baseAddress)! } - guard let valueRef = val else { return nil } return Value(llvm: valueRef) } /// Obtain a constant value for an integer parsed from a string. /// A similar API, `constIntOfStringAndSize` is also available. If the /// string's length is available, it is preferred to call that function instead. - public static func constIntOfString(intType: TypeRef, text: String, radix: UInt8) -> Value? { - let val = text.withCString { cString in - LLVMConstIntOfString(intType.typeRef, cString, radix) + public static func constIntOfString(intType: TypeRef, text: String, radix: UInt8) -> Value { + let valueRef = text.withCString { cString in + LLVMConstIntOfString(intType.typeRef, cString, radix)! } - guard let valueRef = val else { return nil } return Value(llvm: valueRef) } /// Obtain a constant value for an integer parsed from a string with specified length. - public static func constIntOfStringAndSize(intType: TypeRef, text: String, radix: UInt8) -> Value? { - let val = text.withCString { cString in + public static func constIntOfStringAndSize(intType: TypeRef, text: String, radix: UInt8) -> Value { + let valueRef = text.withCString { cString in let length = UInt32(text.utf8.count) - return LLVMConstIntOfStringAndSize(intType.typeRef, cString, length, radix) + return LLVMConstIntOfStringAndSize(intType.typeRef, cString, length, radix)! } - guard let valueRef = val else { return nil } return Value(llvm: valueRef) } /// Obtain a constant value referring to a double floating point value. - public static func constReal(realType: TypeRef, n: Double) -> Value? { - guard let valueRef = LLVMConstReal(realType.typeRef, n) else { return nil } + public static func constReal(realType: TypeRef, n: Double) -> Value { + let valueRef = LLVMConstReal(realType.typeRef, n)! return Value(llvm: valueRef) } /// Obtain a constant for a floating point value parsed from a string. /// A similar API, LLVMConstRealOfStringAndSize is also available. It /// should be used if the input string's length is known. - public static func constRealOfString(realType: TypeRef, text: String) -> Value? { - let val = text.withCString { cString in - LLVMConstRealOfString(realType.typeRef, cString) + public static func constRealOfString(realType: TypeRef, text: String) -> Value { + let valueRef = text.withCString { cString in + LLVMConstRealOfString(realType.typeRef, cString)! } - guard let valueRef = val else { return nil } return Value(llvm: valueRef) } /// Obtain a constant for a floating point value parsed from a string. - public static func constRealOfStringAndSize(realType: TypeRef, text: String) -> Value? { - let val = text.withCString { cString in + public static func constRealOfStringAndSize(realType: TypeRef, text: String) -> Value { + let valueRef = text.withCString { cString in let length = UInt32(text.utf8.count) - return LLVMConstRealOfStringAndSize(realType.typeRef, cString, length) + return LLVMConstRealOfStringAndSize(realType.typeRef, cString, length)! } - guard let valueRef = val else { return nil } return Value(llvm: valueRef) } /// Obtain the zero extended value for an integer constant value. - // unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal); -// public static func getLLVMConstIntZExtValue(constantVal: LLVMValueRef) -> UInt64 { -// return LLVMConstIntGetZExtValue(constantVal) -// } - + public static func constIntZExtValue(constantVal: ValueRef) -> UInt64 { + LLVMConstIntGetZExtValue(constantVal.valueRef) + } /// Obtain the sign extended value for an integer constant value. - // long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal); -// public static func constIntSExtValue(constantVal: LLVMValueRef) -> Int64 { -// return LLVMConstIntGetSExtValue(constantVal) -// } + public static func constIntSExtValue(constantVal: ValueRef) -> Int64 { + LLVMConstIntGetSExtValue(constantVal.valueRef) + } /// Obtain the double value for an floating point constant value. /// losesInfo indicates if some precision was lost in the conversion. - // double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *losesInfo); - // public static func constRealGetDouble(constantVal: LLVMValueRef) -> (Double, Bool) { -// var losesInfo: LLVMBool = 0 -// let result = LLVMConstRealGetDouble(constantVal, &losesInfo) -// return (result, losesInfo != 0) -// } + public static func constRealGetDouble(constantVal: ValueRef) -> (Double, Bool) { + var losesInfo: LLVMBool = 0 + let val = LLVMConstRealGetDouble(constantVal.valueRef, &losesInfo) + return (val, losesInfo != 0) + } } From 21f4aef3a9559f4adf665b9b0b6d766447f2b63a Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Mon, 4 Oct 2021 19:19:17 +0200 Subject: [PATCH 14/38] Added CompositeConstant --- .../Core/Values/Constants/Composite.swift | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 llvm-api/LLVM/Core/Values/Constants/Composite.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Composite.swift b/llvm-api/LLVM/Core/Values/Constants/Composite.swift new file mode 100644 index 0000000..1b6c574 --- /dev/null +++ b/llvm-api/LLVM/Core/Values/Constants/Composite.swift @@ -0,0 +1,130 @@ +import CLLVM + +/// Functions in this group operate on composite constants. +public enum CompositeConstant { + /// Create a ConstantDataSequential and initialize it with a string. + public static func constStringInContext(context: ContextRef, str: String, dontNullTerminate: Bool) -> Value { + let valueRef = str.withCString { cStr in + let length = UInt32(str.utf8.count) + return LLVMConstStringInContext(context.contextRef, cStr, length, dontNullTerminate.llvm)! + } + return Value(llvm: valueRef) + } + + /// Create a ConstantDataSequential with string content in the global context. + /// This is the same as `constStringInContext` except it operates on the global context. + public static func constString(str: String, dontNullTerminate: Bool) -> Value { + let valueRef = str.withCString { cStr in + let length = UInt32(str.utf8.count) + return LLVMConstString(cStr, length, dontNullTerminate.llvm)! + } + return Value(llvm: valueRef) + } + + /// Returns true if the specified constant is an array of i8. + public static func isConstantString(value: ValueRef) -> Bool { + LLVMIsConstantString(value.valueRef) != 0 + } + + /// Get the given constant data sequential as a string. + public static func getString(value: ValueRef) -> (String, UInt) { + var length: UInt = 0 + let lengthPtr = UnsafeMutablePointer.allocate(capacity: 1) + defer { + lengthPtr.deallocate() + } + + if let cStr = LLVMGetAsString(value.valueRef, lengthPtr) { + length = lengthPtr.pointee + let swiftStr = String(cString: cStr) + return (swiftStr, length) + } else { + return ("", 0) + } + } + + /// Create an anonymous `ConstantStruct` with the specified values. + public static func constStructInContext(context: ContextRef, constantVals: [ValueRef], packed: Bool) -> Value? { + let count = UInt32(constantVals.count) + let vals = UnsafeMutablePointer.allocate(capacity: Int(count)) + defer { + vals.deallocate() + } + + for (index, val) in constantVals.enumerated() { + vals[index] = val.valueRef + } + guard let valueRef = LLVMConstStructInContext(context.contextRef, vals, count, packed.llvm) else { return nil } + return Value(llvm: valueRef) + } + + /// Create a `ConstantStruct` in the global Context. + /// This is the same as `constStructInContext` except it operates on the global `Context`. + public static func createLLVMConstStruct(constantVals: [ValueRef], packed: Bool) -> Value? { + let count = UInt32(constantVals.count) + let vals = UnsafeMutablePointer.allocate(capacity: Int(count)) + defer { + vals.deallocate() + } + + for (index, val) in constantVals.enumerated() { + vals[index] = val.valueRef + } + guard let valueRef = LLVMConstStruct(vals, count, packed.llvm) else { return nil } + return Value(llvm: valueRef) + } + + /// Create a `ConstantArray` from values. + @available(*, deprecated, message: "ConstArray is deprecated in favor of the API accurate constArray2") + public static func createLLVMConstArray(elementType: TypeRef, constantValues: [ValueRef]) -> Value? { + let length = UInt32(constantValues.count) + let values = UnsafeMutablePointer.allocate(capacity: Int(length)) + defer { + values.deallocate() + } + + for (index, value) in constantValues.enumerated() { + values[index] = value.valueRef + } + guard let valueRef = LLVMConstArray(elementType.typeRef, values, length) else { return nil } + return Value(llvm: valueRef) + } + + /// Create a ConstantArray from values. + public static func constArray2(elementType: TypeRef, constantValues: [ValueRef]) -> Value? { + let length = UInt64(constantValues.count) + let values = UnsafeMutablePointer.allocate(capacity: Int(length)) + defer { + values.deallocate() + } + + for (index, value) in constantValues.enumerated() { + values[index] = value.valueRef + } + guard let valueRef = LLVMConstArray2(elementType.typeRef, values, length) else { return nil } + return Value(llvm: valueRef) + } + + /** + * Create a non-anonymous ConstantStruct from values. + */ + // LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy, LLVMValueRef *ConstantVals, unsigned Count); + + /** + * Get element of a constant aggregate (struct, array or vector) at the + * specified index. Returns null if the index is out of range, or it's not + * possible to determine the element (e.g., because the constant is a + * constant expression.) + */ + // LLVMValueRef LLVMGetAggregateElement(LLVMValueRef C, unsigned Idx); + + /** + * Get an element at specified index as a constant. + */ + // LLVM_ATTRIBUTE_C_DEPRECATED( LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx), "Use LLVMGetAggregateElement instead"); + + /** + * Create a ConstantVector from values. + */ + // LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size); +} From 86c39735b3b83fb53ac6439e65279e9ba5b9151f Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 5 Oct 2021 18:58:19 +0200 Subject: [PATCH 15/38] Extend: CompositeConstant --- .../Core/Values/Constants/Composite.swift | 60 ++++++++++++------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/llvm-api/LLVM/Core/Values/Constants/Composite.swift b/llvm-api/LLVM/Core/Values/Constants/Composite.swift index 1b6c574..31b5f49 100644 --- a/llvm-api/LLVM/Core/Values/Constants/Composite.swift +++ b/llvm-api/LLVM/Core/Values/Constants/Composite.swift @@ -105,26 +105,42 @@ public enum CompositeConstant { return Value(llvm: valueRef) } - /** - * Create a non-anonymous ConstantStruct from values. - */ - // LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy, LLVMValueRef *ConstantVals, unsigned Count); - - /** - * Get element of a constant aggregate (struct, array or vector) at the - * specified index. Returns null if the index is out of range, or it's not - * possible to determine the element (e.g., because the constant is a - * constant expression.) - */ - // LLVMValueRef LLVMGetAggregateElement(LLVMValueRef C, unsigned Idx); - - /** - * Get an element at specified index as a constant. - */ - // LLVM_ATTRIBUTE_C_DEPRECATED( LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx), "Use LLVMGetAggregateElement instead"); - - /** - * Create a ConstantVector from values. - */ - // LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size); + /// Create a non-anonymous `ConstantStruct` from values. + public static func constNamedStruct(structType: TypeRef, constantValues: [ValueRef]) -> Value? { + let count = UInt32(constantValues.count) + let values = UnsafeMutablePointer.allocate(capacity: Int(count)) + defer { + values.deallocate() + } + + for (index, value) in constantValues.enumerated() { + values[index] = value.valueRef + } + guard let valueRef = LLVMConstNamedStruct(structType.typeRef, values, count) else { return nil } + return Value(llvm: valueRef) + } + + /// Get element of a constant aggregate (struct, array or vector) at the + /// specified index. Returns null if the index is out of range, or it's not + /// possible to determine the element (e.g., because the constant is a + /// constant expression.) + public static func getAggregateElement(aggregate: ValueRef, index: UInt32) -> Value? { + guard let valueRef = LLVMGetAggregateElement(aggregate.valueRef, index) else { return nil } + return Value(llvm: valueRef) + } + + /// Create a ConstantVector from values. + public static func constVector(scalarConstantValues: [ValueRef]) -> Value? { + let size = UInt32(scalarConstantValues.count) + let values = UnsafeMutablePointer.allocate(capacity: Int(size)) + defer { + values.deallocate() + } + + for (index, value) in scalarConstantValues.enumerated() { + values[index] = value.valueRef + } + guard let valueRef = LLVMConstVector(values, size) else { return nil } + return Value(llvm: valueRef) + } } From 2ae6d1341fa3c9f0d269fff5b0c4508061966e54 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 7 Oct 2021 20:39:49 +0200 Subject: [PATCH 16/38] Added constant expressions --- .../Core/Values/Constants/Expressions.swift | 252 ++++++++++++++++++ techstack.md | 80 ------ techstack.yml | 53 ---- 3 files changed, 252 insertions(+), 133 deletions(-) create mode 100644 llvm-api/LLVM/Core/Values/Constants/Expressions.swift delete mode 100644 techstack.md delete mode 100644 techstack.yml diff --git a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift new file mode 100644 index 0000000..2792d20 --- /dev/null +++ b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift @@ -0,0 +1,252 @@ +import CLLVM + +/// Functions in this group correspond to APIs on `ConstantExpressions` . +public enum ConstantExpressions { + public static func getConstOpcode(constantVal: ValueRef) -> Opcode { + let opcode = LLVMGetConstOpcode(constantVal.valueRef) + return Opcode(from: opcode)! + } + + public static func alignOf(typeRef: TypeRef) -> Value { + let valueRef = LLVMAlignOf(typeRef.typeRef)! + return Value(llvm: valueRef) + } + + public static func sizeOf(typeRef: TypeRef) -> Value { + let valueRef = LLVMSizeOf(typeRef.typeRef)! + return Value(llvm: valueRef) + } + + public func constNSWNeg(_ constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNSWNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWNeg(_ constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNUWNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public static func constNeg(constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public func constNot(_ constantVal: LLVMValueRef) -> LLVMValueRef { + LLVMConstNot(constantVal) + } + + public func constAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constAnd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAnd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constOr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstOr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constXor(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstXor(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constICmp(_ predicate: IntPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstICmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constFCmp(_ predicate: RealPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstFCmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constShl(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstShl(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constLShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstLShr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constAShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAShr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + func constGEP2(_ type: LLVMTypeRef, _ constantVal: LLVMValueRef, _ constantIndices: [LLVMValueRef], _ numIndices: UInt32) -> LLVMValueRef { + let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) + defer { + indices.deallocate() + } + + for (index, value) in constantIndices.enumerated() { + guard index < numIndices else { break } + indices[index] = value + } + + return LLVMConstGEP2(type, constantVal, indices, numIndices) + } + + func constInBoundsGEP2(_ type: LLVMTypeRef, _ constantVal: LLVMValueRef, _ constantIndices: [LLVMValueRef], _ numIndices: UInt32) -> LLVMValueRef { + let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) + defer { + indices.deallocate() + } + + for (index, value) in constantIndices.enumerated() { + guard index < numIndices else { break } + indices[index] = value + } + + return LLVMConstInBoundsGEP2(type, constantVal, indices, numIndices) + } + + func constTrunc(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstTrunc(constantVal, toType) + } + + func constSExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstSExt(constantVal, toType) + } + + func constZExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstZExt(constantVal, toType) + } + + func constFPTrunc(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstFPTrunc(constantVal, toType) + } + + func constFPExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstFPExt(constantVal, toType) + } + + func constUIToFP(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstUIToFP(constantVal, toType) + } + + func constSIToFP(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstSIToFP(constantVal, toType) + } + + func constFPToUI(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstFPToUI(constantVal, toType) + } + + func constFPToSI(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstFPToSI(constantVal, toType) + } + + func constPtrToInt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstPtrToInt(constantVal, toType) + } + + func constIntToPtr(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstIntToPtr(constantVal, toType) + } + + func constBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstBitCast(constantVal, toType) + } + + func constAddrSpaceCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstAddrSpaceCast(constantVal, toType) + } + + func constZExtOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstZExtOrBitCast(constantVal, toType) + } + + func constSExtOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstSExtOrBitCast(constantVal, toType) + } + + func constTruncOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstTruncOrBitCast(constantVal, toType) + } + + func constPointerCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstPointerCast(constantVal, toType) + } + + func constIntCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef, _ isSigned: Bool) -> LLVMValueRef { + LLVMConstIntCast(constantVal, toType, LLVMBool(isSigned ? 1 : 0)) + } + + func constFPCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { + LLVMConstFPCast(constantVal, toType) + } + + func constExtractElement(_ vectorConstant: LLVMValueRef, _ indexConstant: LLVMValueRef) -> LLVMValueRef { + LLVMConstExtractElement(vectorConstant, indexConstant) + } + + func constInsertElement(_ vectorConstant: LLVMValueRef, _ elementValueConstant: LLVMValueRef, _ indexConstant: LLVMValueRef) -> LLVMValueRef { + LLVMConstInsertElement(vectorConstant, elementValueConstant, indexConstant) + } + + func constShuffleVector(_ vectorAConstant: LLVMValueRef, _ vectorBConstant: LLVMValueRef, _ maskConstant: LLVMValueRef) -> LLVMValueRef { + LLVMConstShuffleVector(vectorAConstant, vectorBConstant, maskConstant) + } + + func blockAddress(_ function: LLVMValueRef, _ basicBlock: LLVMBasicBlockRef) -> LLVMValueRef { + LLVMBlockAddress(function, basicBlock) + } + + @available(*, deprecated, message: "Use LLVMGetInlineAsm instead") + func constInlineAsm(type: LLVMTypeRef, asmString: String, constraints: String, hasSideEffects: Bool, isAlignStack: Bool) -> LLVMValueRef { + asmString.withCString { asmStr in + constraints.withCString { consStr in + LLVMConstInlineAsm(type, asmStr, consStr, LLVMBool(hasSideEffects ? 1 : 0), LLVMBool(isAlignStack ? 1 : 0)) + } + } + } +} diff --git a/techstack.md b/techstack.md deleted file mode 100644 index 015e4bf..0000000 --- a/techstack.md +++ /dev/null @@ -1,80 +0,0 @@ - -
- -# Tech Stack File -![](https://img.stackshare.io/repo.svg "repo") [mrLSD/llvm-codegen](https://github.com/mrLSD/llvm-codegen)![](https://img.stackshare.io/public_badge.svg "public") -

-|4
Tools used|01/20/24
Report generated| -|------|------| -
- -## Languages (2) - - - - - - -
- C lang -
- C lang -
- -
- Swift -
- Swift -
- -
- -## DevOps (2) - - - - - - -
- Git -
- Git -
- -
- GitHub Actions -
- GitHub Actions -
- -
- -
-
- -Generated via [Stack File](https://github.com/marketplace/stack-file) diff --git a/techstack.yml b/techstack.yml deleted file mode 100644 index 5a3f6ae..0000000 --- a/techstack.yml +++ /dev/null @@ -1,53 +0,0 @@ -repo_name: mrLSD/llvm-codegen -report_id: a41b946dc26669f61269f027fe8e228c -version: 0.1 -repo_type: Public -timestamp: '2024-01-20T08:48:50+00:00' -requested_by: mrLSD -provider: github -branch: master -detected_tools_count: 4 -tools: -- name: C lang - description: One of the most widely used programming languages of all time - website_url: http://en.wikipedia.org/wiki/C_(programming_language) - open_source: true - hosted_saas: false - category: Languages & Frameworks - sub_category: Languages - image_url: https://img.stackshare.io/no-img-open-source.png - detection_source_url: https://github.com/mrLSD/llvm-codegen - detection_source: Repo Metadata -- name: Swift - description: 'An innovative new programming language for Cocoa and Cocoa Touch. ' - website_url: https://developer.apple.com/swift/ - license: Apache-2.0 - open_source: true - hosted_saas: false - category: Languages & Frameworks - sub_category: Languages - image_url: https://img.stackshare.io/service/1009/tuHsaI2U.png - detection_source_url: https://github.com/mrLSD/llvm-codegen - detection_source: Repo Metadata -- name: Git - description: Fast, scalable, distributed revision control system - website_url: http://git-scm.com/ - open_source: true - hosted_saas: false - category: Build, Test, Deploy - sub_category: Version Control System - image_url: https://img.stackshare.io/service/1046/git.png - detection_source_url: https://github.com/mrLSD/llvm-codegen - detection_source: Repo Metadata -- name: GitHub Actions - description: Automate your workflow from idea to production - website_url: https://github.com/features/actions - open_source: false - hosted_saas: true - category: Build, Test, Deploy - sub_category: Continuous Integration - image_url: https://img.stackshare.io/service/11563/actions.png - detection_source_url: https://github.com/mrLSD/llvm-codegen/blob/master/.github/workflows/swift.yaml - detection_source: ".github/workflows/swift.yaml" - last_updated_by: Evgeny Ukhanov - last_updated_on: 2021-07-03 22:01:07.000000000 Z From 3ed76ed6a024a522b6ba48cfdca701abee4de2df Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 8 Oct 2021 01:23:57 +0200 Subject: [PATCH 17/38] Extend ConstantExpressions --- .../Core/Values/Constants/Expressions.swift | 136 +++++++++++------- 1 file changed, 81 insertions(+), 55 deletions(-) diff --git a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift index 2792d20..68372b9 100644 --- a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift +++ b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift @@ -121,7 +121,7 @@ public enum ConstantExpressions { return Value(llvm: valueRef) } - func constGEP2(_ type: LLVMTypeRef, _ constantVal: LLVMValueRef, _ constantIndices: [LLVMValueRef], _ numIndices: UInt32) -> LLVMValueRef { + public func constGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) defer { indices.deallocate() @@ -129,13 +129,14 @@ public enum ConstantExpressions { for (index, value) in constantIndices.enumerated() { guard index < numIndices else { break } - indices[index] = value + indices[index] = value.valueRef } - return LLVMConstGEP2(type, constantVal, indices, numIndices) + let valueRef = LLVMConstGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! + return Value(llvm: valueRef) } - func constInBoundsGEP2(_ type: LLVMTypeRef, _ constantVal: LLVMValueRef, _ constantIndices: [LLVMValueRef], _ numIndices: UInt32) -> LLVMValueRef { + public func constInBoundsGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) defer { indices.deallocate() @@ -143,110 +144,135 @@ public enum ConstantExpressions { for (index, value) in constantIndices.enumerated() { guard index < numIndices else { break } - indices[index] = value + indices[index] = value.valueRef } - return LLVMConstInBoundsGEP2(type, constantVal, indices, numIndices) + let valueRef = LLVMConstInBoundsGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! + return Value(llvm: valueRef) } - func constTrunc(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstTrunc(constantVal, toType) + public func constTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstTrunc(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constSExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstSExt(constantVal, toType) + public func constSExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constZExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstZExt(constantVal, toType) + public func constZExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstZExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constFPTrunc(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstFPTrunc(constantVal, toType) + public func constFPTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPTrunc(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constFPExt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstFPExt(constantVal, toType) + public func constFPExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constUIToFP(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstUIToFP(constantVal, toType) + public func constUIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstUIToFP(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constSIToFP(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstSIToFP(constantVal, toType) + public func constSIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSIToFP(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constFPToUI(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstFPToUI(constantVal, toType) + public func constFPToUI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPToUI(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constFPToSI(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstFPToSI(constantVal, toType) + public func constFPToSI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPToSI(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constPtrToInt(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstPtrToInt(constantVal, toType) + public func constPtrToInt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstPtrToInt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constIntToPtr(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstIntToPtr(constantVal, toType) + public func constIntToPtr(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstIntToPtr(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstBitCast(constantVal, toType) + public func constBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constAddrSpaceCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstAddrSpaceCast(constantVal, toType) + public func constAddrSpaceCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstAddrSpaceCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constZExtOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstZExtOrBitCast(constantVal, toType) + public func constZExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstZExtOrBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constSExtOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstSExtOrBitCast(constantVal, toType) + public func constSExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSExtOrBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constTruncOrBitCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstTruncOrBitCast(constantVal, toType) + public func constTruncOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstTruncOrBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constPointerCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstPointerCast(constantVal, toType) + public func constPointerCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstPointerCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constIntCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef, _ isSigned: Bool) -> LLVMValueRef { - LLVMConstIntCast(constantVal, toType, LLVMBool(isSigned ? 1 : 0)) + public func constIntCast(_ constantVal: ValueRef, _ toType: TypeRef, _ isSigned: Bool) -> Value { + let valueRef = LLVMConstIntCast(constantVal.valueRef, toType.typeRef, isSigned.llvm)! + return Value(llvm: valueRef) } - func constFPCast(_ constantVal: LLVMValueRef, _ toType: LLVMTypeRef) -> LLVMValueRef { - LLVMConstFPCast(constantVal, toType) + public func constFPCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) } - func constExtractElement(_ vectorConstant: LLVMValueRef, _ indexConstant: LLVMValueRef) -> LLVMValueRef { - LLVMConstExtractElement(vectorConstant, indexConstant) + public func constExtractElement(_ vectorConstant: ValueRef, _ indexConstant: ValueRef) -> Value { + let valueRef = LLVMConstExtractElement(vectorConstant.valueRef, indexConstant.valueRef)! + return Value(llvm: valueRef) } - func constInsertElement(_ vectorConstant: LLVMValueRef, _ elementValueConstant: LLVMValueRef, _ indexConstant: LLVMValueRef) -> LLVMValueRef { - LLVMConstInsertElement(vectorConstant, elementValueConstant, indexConstant) + public func constInsertElement(_ vectorConstant: ValueRef, _ elementValueConstant: ValueRef, _ indexConstant: ValueRef) -> Value { + let valueRef = LLVMConstInsertElement(vectorConstant.valueRef, elementValueConstant.valueRef, indexConstant.valueRef)! + return Value(llvm: valueRef) } - func constShuffleVector(_ vectorAConstant: LLVMValueRef, _ vectorBConstant: LLVMValueRef, _ maskConstant: LLVMValueRef) -> LLVMValueRef { - LLVMConstShuffleVector(vectorAConstant, vectorBConstant, maskConstant) + public func constShuffleVector(_ vectorAConstant: ValueRef, _ vectorBConstant: ValueRef, _ maskConstant: ValueRef) -> Value { + let valueRef = LLVMConstShuffleVector(vectorAConstant.valueRef, vectorBConstant.valueRef, maskConstant.valueRef)! + return Value(llvm: valueRef) } - func blockAddress(_ function: LLVMValueRef, _ basicBlock: LLVMBasicBlockRef) -> LLVMValueRef { - LLVMBlockAddress(function, basicBlock) + public func blockAddress(_ function: ValueRef, _ basicBlock: BasicBlockRef) -> Value { + let valueRef = LLVMBlockAddress(function.valueRef, basicBlock.basicBlockRef)! + return Value(llvm: valueRef) } @available(*, deprecated, message: "Use LLVMGetInlineAsm instead") - func constInlineAsm(type: LLVMTypeRef, asmString: String, constraints: String, hasSideEffects: Bool, isAlignStack: Bool) -> LLVMValueRef { - asmString.withCString { asmStr in + public func constInlineAsm(type: TypeRef, asmString: String, constraints: String, hasSideEffects: Bool, isAlignStack: Bool) -> Value { + let valueRef = asmString.withCString { asmStr in constraints.withCString { consStr in - LLVMConstInlineAsm(type, asmStr, consStr, LLVMBool(hasSideEffects ? 1 : 0), LLVMBool(isAlignStack ? 1 : 0)) + LLVMConstInlineAsm(type.typeRef, asmStr, consStr, hasSideEffects.llvm, isAlignStack.llvm)! } } + return Value(llvm: valueRef) } } From 8e590190792bf12a0b1d0215fe165fb537d41e22 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 14 Oct 2021 00:15:43 +0200 Subject: [PATCH 18/38] Update to LLVM-18 --- .github/workflows/swift.yaml | 3 ++- README.md | 7 ++++--- utils/make-pkg-config.swift | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 960b278..237596a 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -18,7 +18,7 @@ jobs: - name: Pre-install run: | brew update - brew install llvm@17 + brew install llvm@18 echo 'export PATH="/usr/local/opt/llvm/bin:$PATH"' >> /Users/runner/.bash_profile echo 'export LDFLAGS="-L/usr/local/opt/llvm/lib"' >> /Users/runner/.bash_profile echo 'export CPPFLAGS="-I/usr/local/opt/llvm/include"' >> /Users/runner/.bash_profile @@ -31,3 +31,4 @@ jobs: run: swift build -v # - name: Run tests # run: swift test -v + diff --git a/README.md b/README.md index 86b5a8c..7e58e16 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ At the same time adhering to the principles of a safety and reliability implemen brew install llvm ``` - Set Environment variables, that provided during `brew` llvm install -- initialize `pkg-config`: +- initializes `pkg-config`: ``` ./utils/make-pkg-config.swift ``` @@ -32,14 +32,15 @@ brew install llvm ### Supported LLVM version - [x] v17.0 +- [x] v18.0 ### Troubleshooting -If `LLVM-C` head files during compulation doesn't found, make sure that you: +If `LLVM-C` head files during compilation doesn't found, make sure that you are: - installed LLVM ``` -llv --version +llc --version ``` - Set environment variables for your terminal (for example in `.zshrc`). To get instruction about variables run: ``` diff --git a/utils/make-pkg-config.swift b/utils/make-pkg-config.swift index 22d7512..be10086 100755 --- a/utils/make-pkg-config.swift +++ b/utils/make-pkg-config.swift @@ -60,7 +60,7 @@ func makeFile() throws { let brewLLVMConfig = { which("\(brewPrefix)/opt/llvm/bin/llvm-config") } /// Ensure we have llvm-config in the PATH - guard let llvmConfig = which("llvm-config-11") ?? which("llvm-config") ?? brewLLVMConfig() else { + guard let llvmConfig = which("llvm-config-15") ?? which("llvm-config") ?? brewLLVMConfig() else { throw "Failed to find llvm-config. Ensure llvm-config is installed and " + "in your PATH" } @@ -82,7 +82,7 @@ func makeFile() throws { let version = (components[0], components[1], components[2]) guard version >= (11, 0, 0) else { - throw "LLVMSwift requires LLVM version >=11.0.0, but you have \(versionStr)" + throw "LLVMSwift requires LLVM version >=15.0.0, but you have \(versionStr)" } print("LLVM version is \(versionStr)") From 514aadb9f6f45e807259457c7da1f614575ca1ae Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 12 Oct 2021 01:03:07 +0200 Subject: [PATCH 19/38] Update CI --- .github/workflows/swift.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 237596a..ff42b8b 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -24,6 +24,8 @@ jobs: echo 'export CPPFLAGS="-I/usr/local/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile clang --version + echo "=====> Checking LLC" + llc --version swift --version swift utils/make-pkg-config.swift From ffac36d6126ebb9a7c36c62e6a71a67dbeb627b8 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 12 Oct 2021 10:01:11 +0200 Subject: [PATCH 20/38] Update CI --- .github/workflows/swift.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index ff42b8b..ee951bd 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -24,7 +24,7 @@ jobs: echo 'export CPPFLAGS="-I/usr/local/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile clang --version - echo "=====> Checking LLC" + echo "=====> Checking LLC" llc --version swift --version swift utils/make-pkg-config.swift From c8ccd2d457cd58bf6159e8f3f26924fc6f0e0628 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 12 Oct 2021 10:12:34 +0200 Subject: [PATCH 21/38] Update CI --- .github/workflows/swift.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index ee951bd..b084a38 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -18,10 +18,10 @@ jobs: - name: Pre-install run: | brew update - brew install llvm@18 - echo 'export PATH="/usr/local/opt/llvm/bin:$PATH"' >> /Users/runner/.bash_profile - echo 'export LDFLAGS="-L/usr/local/opt/llvm/lib"' >> /Users/runner/.bash_profile - echo 'export CPPFLAGS="-I/usr/local/opt/llvm/include"' >> /Users/runner/.bash_profile + brew install llvm@17 + echo 'export PATH="/opt/homebrew/llvm/opt/bin:$PATH"' >> /Users/runner/.bash_profile + echo 'export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"' >> /Users/runner/.bash_profile + echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile clang --version echo "=====> Checking LLC" From 8051752462dde68ac7105943849e287a19af2817 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 15 Oct 2021 10:30:12 +0200 Subject: [PATCH 22/38] Update CI --- .github/workflows/swift.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index b084a38..15530da 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -18,7 +18,7 @@ jobs: - name: Pre-install run: | brew update - brew install llvm@17 + brew install llvm@18 echo 'export PATH="/opt/homebrew/llvm/opt/bin:$PATH"' >> /Users/runner/.bash_profile echo 'export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"' >> /Users/runner/.bash_profile echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile From 74953effc27a7f947e6efd4e9f4c28a93392dee1 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 15 Oct 2021 10:31:20 +0200 Subject: [PATCH 23/38] Update CI --- .github/workflows/swift.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 15530da..2efd308 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -19,6 +19,8 @@ jobs: run: | brew update brew install llvm@18 + # Important: add empty string + echo "" >> /Users/runner/.bash_profile echo 'export PATH="/opt/homebrew/llvm/opt/bin:$PATH"' >> /Users/runner/.bash_profile echo 'export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"' >> /Users/runner/.bash_profile echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile From 7e193db934af97b78627e9be16e3daa07baee3a6 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 15 Oct 2021 10:31:20 +0200 Subject: [PATCH 24/38] Update CI --- .github/workflows/swift.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 2efd308..c0e7e7f 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -26,6 +26,8 @@ jobs: echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile clang --version + cat /Users/runner/.bash_profile + whereis llc echo "=====> Checking LLC" llc --version swift --version From dee9045083babd070093d3485fac32f7b9e712f4 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 15 Oct 2021 10:31:20 +0200 Subject: [PATCH 25/38] Update CI --- .github/workflows/swift.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index c0e7e7f..597f6ae 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -21,7 +21,7 @@ jobs: brew install llvm@18 # Important: add empty string echo "" >> /Users/runner/.bash_profile - echo 'export PATH="/opt/homebrew/llvm/opt/bin:$PATH"' >> /Users/runner/.bash_profile + echo 'export PATH="/opt/homebrew/opt/bin:$PATH"' >> /Users/runner/.bash_profile echo 'export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"' >> /Users/runner/.bash_profile echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile From 03b1e5ff1a090922eb93033245b564dfedc76f9f Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 15 Oct 2021 10:31:20 +0200 Subject: [PATCH 26/38] Update CI --- .github/workflows/swift.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 597f6ae..3b17140 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -21,7 +21,7 @@ jobs: brew install llvm@18 # Important: add empty string echo "" >> /Users/runner/.bash_profile - echo 'export PATH="/opt/homebrew/opt/bin:$PATH"' >> /Users/runner/.bash_profile + echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> /Users/runner/.bash_profile echo 'export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"' >> /Users/runner/.bash_profile echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile From 1c3523c8905f7e41a0a4c09a598b8f64575e0484 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sat, 16 Oct 2021 19:56:09 +0200 Subject: [PATCH 27/38] Remove: Value constant expressions --- .github/workflows/swift.yaml | 4 --- .../Core/Values/Constants/Expressions.swift | 35 ++++++++++--------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 3b17140..969d750 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -26,10 +26,6 @@ jobs: echo 'export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"' >> /Users/runner/.bash_profile source /Users/runner/.bash_profile clang --version - cat /Users/runner/.bash_profile - whereis llc - echo "=====> Checking LLC" - llc --version swift --version swift utils/make-pkg-config.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift index 68372b9..c90005f 100644 --- a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift +++ b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift @@ -1,5 +1,6 @@ import CLLVM +/* /// Functions in this group correspond to APIs on `ConstantExpressions` . public enum ConstantExpressions { public static func getConstOpcode(constantVal: ValueRef) -> Opcode { @@ -191,10 +192,10 @@ public enum ConstantExpressions { return Value(llvm: valueRef) } - public func constFPToSI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstFPToSI(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } +// public func constFPToSI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { +// let valueRef = LLVMConstFPToSI(constantVal.valueRef, toType.typeRef)! +// return Value(llvm: valueRef) +// } public func constPtrToInt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { let valueRef = LLVMConstPtrToInt(constantVal.valueRef, toType.typeRef)! @@ -216,10 +217,10 @@ public enum ConstantExpressions { return Value(llvm: valueRef) } - public func constZExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstZExtOrBitCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } +// public func constZExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { +// let valueRef = LLVMConstZExtOrBitCast(constantVal.valueRef, toType.typeRef)! +// return Value(llvm: valueRef) +// } public func constSExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { let valueRef = LLVMConstSExtOrBitCast(constantVal.valueRef, toType.typeRef)! @@ -236,15 +237,15 @@ public enum ConstantExpressions { return Value(llvm: valueRef) } - public func constIntCast(_ constantVal: ValueRef, _ toType: TypeRef, _ isSigned: Bool) -> Value { - let valueRef = LLVMConstIntCast(constantVal.valueRef, toType.typeRef, isSigned.llvm)! - return Value(llvm: valueRef) - } +// public func constIntCast(_ constantVal: ValueRef, _ toType: TypeRef, _ isSigned: Bool) -> Value { +// let valueRef = LLVMConstIntCast(constantVal.valueRef, toType.typeRef, isSigned.llvm)! +// return Value(llvm: valueRef) +// } - public func constFPCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstFPCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } +// public func constFPCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { +// let valueRef = LLVMConstFPCast(constantVal.valueRef, toType.typeRef)! +// return Value(llvm: valueRef) +// } public func constExtractElement(_ vectorConstant: ValueRef, _ indexConstant: ValueRef) -> Value { let valueRef = LLVMConstExtractElement(vectorConstant.valueRef, indexConstant.valueRef)! @@ -276,3 +277,5 @@ public enum ConstantExpressions { return Value(llvm: valueRef) } } + */ + From 3a5e36938642ba80ec2d701bad9b4c37c6c1e75a Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 17 Oct 2021 12:29:16 +0200 Subject: [PATCH 28/38] Refactored Package LLVM config --- .github/workflows/swift.yaml | 4 +- Package.swift | 78 ++++++++++++++++++++++++++++++++---- utils/make-pkg-config.swift | 10 +---- 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 969d750..e043200 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -18,7 +18,7 @@ jobs: - name: Pre-install run: | brew update - brew install llvm@18 + brew install llvm@18.1.8 # Important: add empty string echo "" >> /Users/runner/.bash_profile echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> /Users/runner/.bash_profile @@ -27,7 +27,7 @@ jobs: source /Users/runner/.bash_profile clang --version swift --version - swift utils/make-pkg-config.swift +# swift utils/make-pkg-config.swift - name: Build run: swift build -v diff --git a/Package.swift b/Package.swift index 9c31421..84d7710 100644 --- a/Package.swift +++ b/Package.swift @@ -2,6 +2,9 @@ // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription +import Foundation + +let (cFlags, linkFlags) = try! getLLVMConfig() let package = Package( name: "llvm-api", @@ -11,17 +14,76 @@ let package = Package( targets: [ .systemLibrary( name: "CLLVM", - path: "llvm-api/CLLVM", - pkgConfig: "CLLVM", - providers: [ - .brew(["llvm"]), - ] + path: "llvm-api/CLLVM" ), .target( name: "LLVM", dependencies: ["CLLVM"], - path: "llvm-api/LLVM" + path: "llvm-api/LLVM", + cSettings: [ + .unsafeFlags(cFlags) + ], + linkerSettings: [ + .unsafeFlags(linkFlags) + ] ), - ], - cxxLanguageStandard: .cxx20 + ] ) + +/// Get LLVM config flags +func getLLVMConfig() throws -> ([String], [String]) { + let brewPrefix = { + guard let brew = which("brew") else { return nil } + return run(brew, args: ["--prefix"]) + }() ?? "/usr/local" + /// Ensure we have llvm-config in the PATH + guard let llvmConfig = which("llvm-config") ?? which("\(brewPrefix)/opt/llvm/bin/llvm-config") else { + throw "Failed to find llvm-config. Ensure llvm-config is installed and in your PATH" + } + // Get linkage (LD) flags + let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", "--system-libs"])! + .replacing(charactersIn: .newlines, with: " ") + .components(separatedBy: " ") + .filter { !$0.hasPrefix("-W") } + // Get C flags + let cFlags = run(llvmConfig, args: ["--cflags"])! + .replacing(charactersIn: .newlines, with: "") + .components(separatedBy: " ") + .filter { $0.hasPrefix("-I") } + return (cFlags, ldFlags) +} + +/// Runs the specified program at the provided path. +/// - parameter path: The full path of the executable you wish to run. +/// - parameter args: The arguments you wish to pass to the process. +/// - returns: The standard output of the process, or nil if it was empty. +func run(_ path: String, args: [String] = []) -> String? { + let pipe = Pipe() + let process = Process() + process.executableURL = URL(fileURLWithPath: path) + process.arguments = args + process.standardOutput = pipe + try? process.run() + process.waitUntilExit() + + let data = pipe.fileHandleForReading.readDataToEndOfFile() + guard let result = String(data: data, encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !result.isEmpty else { return nil } + return result +} + +/// Finds the location of the provided binary on your system. +func which(_ name: String) -> String? { + run("/usr/bin/which", args: [name]) +} + +extension String: Error { + /// Replaces all occurrences of characters in the provided set with the provided string. + func replacing(charactersIn characterSet: CharacterSet, + with separator: String) -> String + { + let components = components(separatedBy: characterSet) + return components.joined(separator: separator) + } +} diff --git a/utils/make-pkg-config.swift b/utils/make-pkg-config.swift index be10086..a41b77e 100755 --- a/utils/make-pkg-config.swift +++ b/utils/make-pkg-config.swift @@ -10,7 +10,7 @@ let libCPP = "-lc++" /// process. /// - returns: The standard output of the process, or nil if it was empty. func run(_ path: String, args: [String] = []) -> String? { - print("Running \(path) \(args.joined(separator: " "))...") + print("Run: \(path) \(args.joined(separator: " "))") let pipe = Pipe() let process = Process() process.executableURL = URL(fileURLWithPath: path) @@ -60,7 +60,7 @@ func makeFile() throws { let brewLLVMConfig = { which("\(brewPrefix)/opt/llvm/bin/llvm-config") } /// Ensure we have llvm-config in the PATH - guard let llvmConfig = which("llvm-config-15") ?? which("llvm-config") ?? brewLLVMConfig() else { + guard let llvmConfig = which("llvm-config") ?? brewLLVMConfig() else { throw "Failed to find llvm-config. Ensure llvm-config is installed and " + "in your PATH" } @@ -79,12 +79,6 @@ func makeFile() throws { throw "Invalid version number \(versionStr)" } - let version = (components[0], components[1], components[2]) - - guard version >= (11, 0, 0) else { - throw "LLVMSwift requires LLVM version >=15.0.0, but you have \(versionStr)" - } - print("LLVM version is \(versionStr)") let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", From 503e134277f6e49544337eb47156f537501974af Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 17 Oct 2021 12:40:38 +0200 Subject: [PATCH 29/38] Added LLVM-18 --- .github/workflows/swift.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index e043200..bde2c35 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -18,7 +18,7 @@ jobs: - name: Pre-install run: | brew update - brew install llvm@18.1.8 + brew install llvm@18 # Important: add empty string echo "" >> /Users/runner/.bash_profile echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> /Users/runner/.bash_profile From 2b9ee1ca896b814911dd4754adf9f48bf7d7ee3a Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Mon, 18 Oct 2021 10:09:36 +0200 Subject: [PATCH 30/38] Remove utils, and updated CI --- .github/workflows/swift.yaml | 1 - Package.swift | 13 +++- utils/make-pkg-config.swift | 124 ----------------------------------- 3 files changed, 10 insertions(+), 128 deletions(-) delete mode 100755 utils/make-pkg-config.swift diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index bde2c35..73253eb 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -27,7 +27,6 @@ jobs: source /Users/runner/.bash_profile clang --version swift --version -# swift utils/make-pkg-config.swift - name: Build run: swift build -v diff --git a/Package.swift b/Package.swift index 84d7710..03b2b59 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,8 @@ import PackageDescription import Foundation -let (cFlags, linkFlags) = try! getLLVMConfig() +// Get LLVM flags and version +let (cFlags, linkFlags, _version) = try! getLLVMConfig() let package = Package( name: "llvm-api", @@ -31,7 +32,7 @@ let package = Package( ) /// Get LLVM config flags -func getLLVMConfig() throws -> ([String], [String]) { +func getLLVMConfig() throws -> ([String], [String], [Int]) { let brewPrefix = { guard let brew = which("brew") else { return nil } return run(brew, args: ["--prefix"]) @@ -40,6 +41,12 @@ func getLLVMConfig() throws -> ([String], [String]) { guard let llvmConfig = which("llvm-config") ?? which("\(brewPrefix)/opt/llvm/bin/llvm-config") else { throw "Failed to find llvm-config. Ensure llvm-config is installed and in your PATH" } + // Fetch LLVM version + let versionStr = run(llvmConfig, args: ["--version"])! + .replacing(charactersIn: .newlines, with: "") + .replacingOccurrences(of: "svn", with: "") + let versionComponents = versionStr.components(separatedBy: ".") + .compactMap { Int($0) } // Get linkage (LD) flags let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", "--system-libs"])! .replacing(charactersIn: .newlines, with: " ") @@ -50,7 +57,7 @@ func getLLVMConfig() throws -> ([String], [String]) { .replacing(charactersIn: .newlines, with: "") .components(separatedBy: " ") .filter { $0.hasPrefix("-I") } - return (cFlags, ldFlags) + return (cFlags, ldFlags, versionComponents) } /// Runs the specified program at the provided path. diff --git a/utils/make-pkg-config.swift b/utils/make-pkg-config.swift deleted file mode 100755 index a41b77e..0000000 --- a/utils/make-pkg-config.swift +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env swift -import Foundation - -let libCPP = "-lc++" - -/// Runs the specified program at the provided path. -/// - parameter path: The full path of the executable you -/// wish to run. -/// - parameter args: The arguments you wish to pass to the -/// process. -/// - returns: The standard output of the process, or nil if it was empty. -func run(_ path: String, args: [String] = []) -> String? { - print("Run: \(path) \(args.joined(separator: " "))") - let pipe = Pipe() - let process = Process() - process.executableURL = URL(fileURLWithPath: path) - process.arguments = args - process.standardOutput = pipe - try? process.run() - process.waitUntilExit() - - let data = pipe.fileHandleForReading.readDataToEndOfFile() - guard let result = String(data: data, encoding: .utf8)? - .trimmingCharacters(in: .whitespacesAndNewlines), - !result.isEmpty else { return nil } - return result -} - -/// Finds the location of the provided binary on your system. -func which(_ name: String) -> String? { - run("/usr/bin/which", args: [name]) -} - -extension String: Error { - /// Replaces all occurrences of characters in the provided set with - /// the provided string. - func replacing(charactersIn characterSet: CharacterSet, - with separator: String) -> String - { - let components = components(separatedBy: characterSet) - return components.joined(separator: separator) - } -} - -func makeFile() throws { - let brewPrefix = { - guard let brew = which("brew") else { return nil } - return run(brew, args: ["--prefix"]) - }() ?? "/usr/local" - - let pkgConfigPath = "\(brewPrefix)/lib/pkgconfig" - let pkgConfigDir = URL(fileURLWithPath: pkgConfigPath) - - // Make /lib/pkgconfig if it doesn't already exist - if !FileManager.default.fileExists(atPath: pkgConfigPath) { - try FileManager.default.createDirectory(at: pkgConfigDir, - withIntermediateDirectories: true) - } - let cllvmPath = pkgConfigDir.appendingPathComponent("cllvm.pc") - let brewLLVMConfig = { which("\(brewPrefix)/opt/llvm/bin/llvm-config") } - - /// Ensure we have llvm-config in the PATH - guard let llvmConfig = which("llvm-config") ?? brewLLVMConfig() else { - throw "Failed to find llvm-config. Ensure llvm-config is installed and " + - "in your PATH" - } - - /// Extract the info we need from llvm-config - - print("Found llvm-config at \(llvmConfig)...") - - let versionStr = run(llvmConfig, args: ["--version"])! - .replacing(charactersIn: .newlines, with: "") - .replacingOccurrences(of: "svn", with: "") - let components = versionStr.components(separatedBy: ".") - .compactMap { Int($0) } - - guard components.count == 3 else { - throw "Invalid version number \(versionStr)" - } - - print("LLVM version is \(versionStr)") - - let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", - "--system-libs"])! - .replacing(charactersIn: .newlines, with: " ") - .components(separatedBy: " ") - .filter { !$0.hasPrefix("-W") } - .joined(separator: " ") - - // SwiftPM has a whitelisted set of cflags that it understands, and - // unfortunately that includes almost everything but the include dir. - - let cFlags = run(llvmConfig, args: ["--cflags"])! - .replacing(charactersIn: .newlines, with: "") - .components(separatedBy: " ") - .filter { $0.hasPrefix("-I") } - .joined(separator: " ") - - /// Emit the pkg-config file to the path - - let s = [ - "Name: cllvm", - "Description: The llvm library", - "Version: \(versionStr)", - "Libs: \(ldFlags) \(libCPP)", - "Requires.private:", - "Cflags: \(cFlags)", - ].joined(separator: "\n") - - print("Writing pkg-config file to \(cllvmPath.path)...") - - try s.write(toFile: cllvmPath.path, atomically: true, encoding: .utf8) - - print("\nSuccessfully wrote pkg-config file!") - print("Make sure to re-run this script when you update LLVM.") -} - -do { - try makeFile() -} catch { - print("error: \(error)") - exit(-1) -} From b11616f08c1786c7980205e06040eb288adf15ee Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Mon, 18 Oct 2021 11:24:07 +0200 Subject: [PATCH 31/38] Update README --- README.md | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 7e58e16..aace604 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![Swift CI](https://github.com/mrLSD/llvm-api-swift/actions/workflows/swift.yaml/badge.svg)](https://github.com/mrLSD/llvm-api-swift/actions/workflows/swift.yaml) + # `llvm-api-swift` `llvm-api-swift` is a library representing Swift LLVM API, a pure Swift interface to the [LLVM API](https://llvm.org/docs/) and its associated libraries. @@ -14,22 +17,23 @@ At the same time adhering to the principles of a safety and reliability implemen ### Requirements + - Supported OS: MacOS 12.0 or above + - Swift lang: 5.9 or above -- Install LLVM: +- Install latest LLVM: ``` brew install llvm ``` + - Set Environment variables, that provided during `brew` llvm install -- initializes `pkg-config`: -``` -./utils/make-pkg-config.swift -``` -**NOTE:** Every time, when LLVM is updated or installed new version should be run `pkg-config` step. +- You don't need additional configurations like `pkg-config` files, if your LLVM installation is correct and you successfully set environment variable. + +:arrow_right: If you have problems, just check [Troubleshooting](#troubleshooting). -### Supported LLVM version +### Supported LLVM versions - [x] v17.0 - [x] v18.0 @@ -38,22 +42,17 @@ brew install llvm ### Troubleshooting If `LLVM-C` head files during compilation doesn't found, make sure that you are: -- installed LLVM + +- installed LLVM correctly ``` llc --version ``` + - Set environment variables for your terminal (for example in `.zshrc`). To get instruction about variables run: ``` brew info llvm ``` -- run pkg-config utility: -``` -./utils/make-pkg-config.swift -``` -- if utility doesn't have access right to run: -``` -chmod +x ./utils/make-pkg-config.swift -./utils/make-pkg-config.swift -``` + +- To get more insights take a look current project [Github CI config](.github/workflows/swift.yaml). ### LICENS: [MIT](LICENSE) From 28627f811d87ea35bf9c456095adb798aa5634a0 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Mon, 18 Oct 2021 11:26:29 +0200 Subject: [PATCH 32/38] Update README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aace604..9f6827c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ brew install llvm - Set Environment variables, that provided during `brew` llvm install -- You don't need additional configurations like `pkg-config` files, if your LLVM installation is correct and you successfully set environment variable. +- You don't need additional configurations like `pkg-config` files, if your LLVM installation is correct and you successfully set environment variables. `Package.swift` **automatically configure** all needed things to build correctly and you don't need care more. :arrow_right: If you have problems, just check [Troubleshooting](#troubleshooting). From 7c12785ac7a47ce78558496747b82621bc76bf64 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 19 Oct 2021 12:12:39 +0200 Subject: [PATCH 33/38] Extend Modules --- .github/workflows/swift.yaml | 2 +- Package.swift | 15 +- llvm-api/LLVM/Core/Context.swift | 19 +- llvm-api/LLVM/Core/Modules.swift | 109 ++++ .../Core/Values/Constants/Expressions.swift | 555 +++++++++--------- 5 files changed, 405 insertions(+), 295 deletions(-) create mode 100644 llvm-api/LLVM/Core/Modules.swift diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 73253eb..1f7b555 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -29,7 +29,7 @@ jobs: swift --version - name: Build - run: swift build -v + run: swift build -Xswiftc -DCLI_BUILD # - name: Run tests # run: swift test -v diff --git a/Package.swift b/Package.swift index 03b2b59..923351e 100644 --- a/Package.swift +++ b/Package.swift @@ -1,11 +1,15 @@ // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. -import PackageDescription import Foundation +import PackageDescription // Get LLVM flags and version -let (cFlags, linkFlags, _version) = try! getLLVMConfig() +#if CLI_BUILD + let (cFlags, linkFlags, _version) = try! getLLVMConfig() +#else + let (cFlags, linkFlags, _version) = ([String](), [String](), [Int]()) +#endif let package = Package( name: "llvm-api", @@ -15,17 +19,18 @@ let package = Package( targets: [ .systemLibrary( name: "CLLVM", - path: "llvm-api/CLLVM" + path: "llvm-api/CLLVM", + pkgConfig: "cllvm" ), .target( name: "LLVM", dependencies: ["CLLVM"], path: "llvm-api/LLVM", cSettings: [ - .unsafeFlags(cFlags) + .unsafeFlags(cFlags), ], linkerSettings: [ - .unsafeFlags(linkFlags) + .unsafeFlags(linkFlags), ] ), ] diff --git a/llvm-api/LLVM/Core/Context.swift b/llvm-api/LLVM/Core/Context.swift index d0c7f32..88fda05 100644 --- a/llvm-api/LLVM/Core/Context.swift +++ b/llvm-api/LLVM/Core/Context.swift @@ -12,7 +12,7 @@ import CLLVM /// context, it is recommended that each thread of execution be assigned a unique /// context. LLVM's core infrastructure and API provides no locking guarantees /// and no atomicity guarantees. -public class Context: ContextRef { +public final class Context: ContextRef { private let llvm: LLVMContextRef /// Retrieves the underlying LLVM type object. @@ -185,20 +185,17 @@ public class Context: ContextRef { } /// Get the string attribute's kind. - public static func getStringAttributeKind(attributeRef: AttributeRef, length: UInt32) -> String? { - var mutLength = length - guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in - LLVMGetStringAttributeKind(attributeRef.attributeRef, lengthPtr) - }) else { return nil } + public static func getStringAttributeKind(attributeRef: AttributeRef) -> String? { + var length: UInt32 = 0 + guard let cString = LLVMGetStringAttributeKind(attributeRef.attributeRef, &length) else { return nil } return String(cString: cString) } /// Get the string attribute's value. - public static func getStringAttributeValue(attributeRef: AttributeRef, length: UInt32) -> String? { - var mutLength = length - guard let cString = withUnsafeMutablePointer(to: &mutLength, { lengthPtr in - LLVMGetStringAttributeValue(attributeRef.attributeRef, lengthPtr) - }) else { return nil } + public static func getStringAttributeValue(attributeRef: AttributeRef) -> String? { + var length: UInt32 = 0 + guard let cString = + LLVMGetStringAttributeValue(attributeRef.attributeRef, &length) else { return nil } return String(cString: cString) } diff --git a/llvm-api/LLVM/Core/Modules.swift b/llvm-api/LLVM/Core/Modules.swift new file mode 100644 index 0000000..6a97bbd --- /dev/null +++ b/llvm-api/LLVM/Core/Modules.swift @@ -0,0 +1,109 @@ +import CLLVM + +/// Modules represent the top-level structure in an LLVM program. An LLVM +/// module is effectively a translation unit or a collection of +/// translation units merged together. +public final class Module: ModuleRef { + private let llvm: LLVMModuleRef + + /// Retrieves the underlying LLVM value object. + public var moduleRef: LLVMModuleRef { llvm } + + /// Init function by LLVM Value + public init(llvm: LLVMModuleRef) { + self.llvm = llvm + } + + /// Create a new, empty module in the global context. + /// + /// This is equivalent to calling LLVMModuleCreateWithNameInContext with + /// LLVMGetGlobalContext() as the context parameter. + /// + /// Every invocation should be paired with LLVMDisposeModule() or memory will be leaked. + public init(name: String) { + llvm = name.withCString { cString in + LLVMModuleCreateWithName(cString) + } + } + + /// Create a new, empty module in a specific context. + /// + /// Every invocation should be paired with LLVMDisposeModule() or memory will be leaked. + public init(name: String, context: ContextRef) { + llvm = name.withCString { cString in + LLVMModuleCreateWithNameInContext(cString, context.contextRef) + } + } + + /// Return an exact copy of the specified module. + public func clone_nodule() -> ModuleRef { + let new_module = LLVMCloneModule(llvm)! + return Self(llvm: new_module) + } + + /// Obtain the identifier of a module. + public var getLLVMModuleIdentifier: String { + var length: UInt = 0 + guard let cString = LLVMGetModuleIdentifier(llvm, &length) else { return "" } + return String(cString: cString) + } + + public func setLLVMModuleIdentifier(module: LLVMModuleRef, identifier: String) { + identifier.withCString { cString in + LLVMSetModuleIdentifier(module, cString, identifier.count) + } + } + + public var getModuleIdentifier: String? { + var length: UInt = 0 + guard let cString = LLVMGetModuleIdentifier(llvm, &length) else { + return nil + } + return String(cString: cString) + } + + /// Set the identifier of a module to a string Ident with length Len. + public func setSourceFileName(fileName: String) { + fileName.withCString { cString in + LLVMSetSourceFileName(llvm, cString, fileName.utf8.count) + } + } + + /// Obtain the module's original source file name. + public var getSourceFileName: String? { + var length: size_t = 0 + guard let cString = LLVMGetSourceFileName(llvm, &length) else { + return nil + } + return String(cString: cString) + } + + /// Set the data layout for a module. + public func setDataLayout(module: LLVMModuleRef, dataLayout: String) { + dataLayout.withCString { cString in + LLVMSetDataLayout(module, cString) + } + } + + /// Obtain the data layout for a module. + public var getDataLayout: String? { + guard let cString = LLVMGetDataLayoutStr(llvm) else { + return nil + } + return String(cString: cString) + } + + /// Set the target triple for a module. + public func setTarget(triple: String) { + triple.withCString { cString in + LLVMSetTarget(llvm, cString) + } + } + + /// Destroy a module instance. + /// + /// This must be called for every created module or memory will be leaked. + deinit { + LLVMDisposeModule(llvm) + } +} diff --git a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift index c90005f..f5f74a8 100644 --- a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift +++ b/llvm-api/LLVM/Core/Values/Constants/Expressions.swift @@ -1,281 +1,280 @@ import CLLVM /* -/// Functions in this group correspond to APIs on `ConstantExpressions` . -public enum ConstantExpressions { - public static func getConstOpcode(constantVal: ValueRef) -> Opcode { - let opcode = LLVMGetConstOpcode(constantVal.valueRef) - return Opcode(from: opcode)! - } - - public static func alignOf(typeRef: TypeRef) -> Value { - let valueRef = LLVMAlignOf(typeRef.typeRef)! - return Value(llvm: valueRef) - } - - public static func sizeOf(typeRef: TypeRef) -> Value { - let valueRef = LLVMSizeOf(typeRef.typeRef)! - return Value(llvm: valueRef) - } - - public func constNSWNeg(_ constantVal: ValueRef) -> Value { - let valueRef = LLVMConstNSWNeg(constantVal.valueRef)! - return Value(llvm: valueRef) - } - - public func constNUWNeg(_ constantVal: ValueRef) -> Value { - let valueRef = LLVMConstNUWNeg(constantVal.valueRef)! - return Value(llvm: valueRef) - } - - public static func constNeg(constantVal: ValueRef) -> Value { - let valueRef = LLVMConstNeg(constantVal.valueRef)! - return Value(llvm: valueRef) - } - - public func constNot(_ constantVal: LLVMValueRef) -> LLVMValueRef { - LLVMConstNot(constantVal) - } - - public func constAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstAdd(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNSWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNSWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNUWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNUWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstSub(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNSWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNSWSub(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNUWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNUWSub(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstMul(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNSWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNSWMul(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constNUWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstNUWMul(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constAnd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstAnd(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constOr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstOr(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constXor(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstXor(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constICmp(_ predicate: IntPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstICmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constFCmp(_ predicate: RealPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstFCmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constShl(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstShl(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constLShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstLShr(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constAShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { - let valueRef = LLVMConstAShr(lhsConstant.valueRef, rhsConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { - let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) - defer { - indices.deallocate() - } - - for (index, value) in constantIndices.enumerated() { - guard index < numIndices else { break } - indices[index] = value.valueRef - } - - let valueRef = LLVMConstGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! - return Value(llvm: valueRef) - } - - public func constInBoundsGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { - let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) - defer { - indices.deallocate() - } - - for (index, value) in constantIndices.enumerated() { - guard index < numIndices else { break } - indices[index] = value.valueRef - } - - let valueRef = LLVMConstInBoundsGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! - return Value(llvm: valueRef) - } - - public func constTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstTrunc(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constSExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstSExt(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constZExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstZExt(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constFPTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstFPTrunc(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constFPExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstFPExt(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constUIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstUIToFP(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constSIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstSIToFP(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constFPToUI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstFPToUI(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - -// public func constFPToSI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { -// let valueRef = LLVMConstFPToSI(constantVal.valueRef, toType.typeRef)! -// return Value(llvm: valueRef) -// } - - public func constPtrToInt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstPtrToInt(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constIntToPtr(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstIntToPtr(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstBitCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constAddrSpaceCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstAddrSpaceCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - -// public func constZExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { -// let valueRef = LLVMConstZExtOrBitCast(constantVal.valueRef, toType.typeRef)! -// return Value(llvm: valueRef) -// } - - public func constSExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstSExtOrBitCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constTruncOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstTruncOrBitCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - - public func constPointerCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { - let valueRef = LLVMConstPointerCast(constantVal.valueRef, toType.typeRef)! - return Value(llvm: valueRef) - } - -// public func constIntCast(_ constantVal: ValueRef, _ toType: TypeRef, _ isSigned: Bool) -> Value { -// let valueRef = LLVMConstIntCast(constantVal.valueRef, toType.typeRef, isSigned.llvm)! -// return Value(llvm: valueRef) -// } - -// public func constFPCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { -// let valueRef = LLVMConstFPCast(constantVal.valueRef, toType.typeRef)! -// return Value(llvm: valueRef) -// } - - public func constExtractElement(_ vectorConstant: ValueRef, _ indexConstant: ValueRef) -> Value { - let valueRef = LLVMConstExtractElement(vectorConstant.valueRef, indexConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constInsertElement(_ vectorConstant: ValueRef, _ elementValueConstant: ValueRef, _ indexConstant: ValueRef) -> Value { - let valueRef = LLVMConstInsertElement(vectorConstant.valueRef, elementValueConstant.valueRef, indexConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func constShuffleVector(_ vectorAConstant: ValueRef, _ vectorBConstant: ValueRef, _ maskConstant: ValueRef) -> Value { - let valueRef = LLVMConstShuffleVector(vectorAConstant.valueRef, vectorBConstant.valueRef, maskConstant.valueRef)! - return Value(llvm: valueRef) - } - - public func blockAddress(_ function: ValueRef, _ basicBlock: BasicBlockRef) -> Value { - let valueRef = LLVMBlockAddress(function.valueRef, basicBlock.basicBlockRef)! - return Value(llvm: valueRef) - } - - @available(*, deprecated, message: "Use LLVMGetInlineAsm instead") - public func constInlineAsm(type: TypeRef, asmString: String, constraints: String, hasSideEffects: Bool, isAlignStack: Bool) -> Value { - let valueRef = asmString.withCString { asmStr in - constraints.withCString { consStr in - LLVMConstInlineAsm(type.typeRef, asmStr, consStr, hasSideEffects.llvm, isAlignStack.llvm)! - } - } - return Value(llvm: valueRef) - } -} - */ - + /// Functions in this group correspond to APIs on `ConstantExpressions` . + public enum ConstantExpressions { + public static func getConstOpcode(constantVal: ValueRef) -> Opcode { + let opcode = LLVMGetConstOpcode(constantVal.valueRef) + return Opcode(from: opcode)! + } + + public static func alignOf(typeRef: TypeRef) -> Value { + let valueRef = LLVMAlignOf(typeRef.typeRef)! + return Value(llvm: valueRef) + } + + public static func sizeOf(typeRef: TypeRef) -> Value { + let valueRef = LLVMSizeOf(typeRef.typeRef)! + return Value(llvm: valueRef) + } + + public func constNSWNeg(_ constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNSWNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWNeg(_ constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNUWNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public static func constNeg(constantVal: ValueRef) -> Value { + let valueRef = LLVMConstNeg(constantVal.valueRef)! + return Value(llvm: valueRef) + } + + public func constNot(_ constantVal: LLVMValueRef) -> LLVMValueRef { + LLVMConstNot(constantVal) + } + + public func constAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWAdd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWAdd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWSub(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWSub(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNSWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNSWMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constNUWMul(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstNUWMul(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constAnd(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAnd(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constOr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstOr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constXor(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstXor(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constICmp(_ predicate: IntPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstICmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constFCmp(_ predicate: RealPredicate, _ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstFCmp(predicate.llvm, lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constShl(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstShl(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constLShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstLShr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constAShr(_ lhsConstant: ValueRef, _ rhsConstant: ValueRef) -> Value { + let valueRef = LLVMConstAShr(lhsConstant.valueRef, rhsConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { + let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) + defer { + indices.deallocate() + } + + for (index, value) in constantIndices.enumerated() { + guard index < numIndices else { break } + indices[index] = value.valueRef + } + + let valueRef = LLVMConstGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! + return Value(llvm: valueRef) + } + + public func constInBoundsGEP2(_ type: TypeRef, _ constantVal: ValueRef, _ constantIndices: [ValueRef], _ numIndices: UInt32) -> Value { + let indices = UnsafeMutablePointer.allocate(capacity: Int(numIndices)) + defer { + indices.deallocate() + } + + for (index, value) in constantIndices.enumerated() { + guard index < numIndices else { break } + indices[index] = value.valueRef + } + + let valueRef = LLVMConstInBoundsGEP2(type.typeRef, constantVal.valueRef, indices, numIndices)! + return Value(llvm: valueRef) + } + + public func constTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstTrunc(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constSExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constZExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstZExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constFPTrunc(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPTrunc(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constFPExt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPExt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constUIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstUIToFP(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constSIToFP(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSIToFP(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constFPToUI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstFPToUI(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + // public func constFPToSI(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + // let valueRef = LLVMConstFPToSI(constantVal.valueRef, toType.typeRef)! + // return Value(llvm: valueRef) + // } + + public func constPtrToInt(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstPtrToInt(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constIntToPtr(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstIntToPtr(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constAddrSpaceCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstAddrSpaceCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + // public func constZExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + // let valueRef = LLVMConstZExtOrBitCast(constantVal.valueRef, toType.typeRef)! + // return Value(llvm: valueRef) + // } + + public func constSExtOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstSExtOrBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constTruncOrBitCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstTruncOrBitCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + public func constPointerCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + let valueRef = LLVMConstPointerCast(constantVal.valueRef, toType.typeRef)! + return Value(llvm: valueRef) + } + + // public func constIntCast(_ constantVal: ValueRef, _ toType: TypeRef, _ isSigned: Bool) -> Value { + // let valueRef = LLVMConstIntCast(constantVal.valueRef, toType.typeRef, isSigned.llvm)! + // return Value(llvm: valueRef) + // } + + // public func constFPCast(_ constantVal: ValueRef, _ toType: TypeRef) -> Value { + // let valueRef = LLVMConstFPCast(constantVal.valueRef, toType.typeRef)! + // return Value(llvm: valueRef) + // } + + public func constExtractElement(_ vectorConstant: ValueRef, _ indexConstant: ValueRef) -> Value { + let valueRef = LLVMConstExtractElement(vectorConstant.valueRef, indexConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constInsertElement(_ vectorConstant: ValueRef, _ elementValueConstant: ValueRef, _ indexConstant: ValueRef) -> Value { + let valueRef = LLVMConstInsertElement(vectorConstant.valueRef, elementValueConstant.valueRef, indexConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func constShuffleVector(_ vectorAConstant: ValueRef, _ vectorBConstant: ValueRef, _ maskConstant: ValueRef) -> Value { + let valueRef = LLVMConstShuffleVector(vectorAConstant.valueRef, vectorBConstant.valueRef, maskConstant.valueRef)! + return Value(llvm: valueRef) + } + + public func blockAddress(_ function: ValueRef, _ basicBlock: BasicBlockRef) -> Value { + let valueRef = LLVMBlockAddress(function.valueRef, basicBlock.basicBlockRef)! + return Value(llvm: valueRef) + } + + @available(*, deprecated, message: "Use LLVMGetInlineAsm instead") + public func constInlineAsm(type: TypeRef, asmString: String, constraints: String, hasSideEffects: Bool, isAlignStack: Bool) -> Value { + let valueRef = asmString.withCString { asmStr in + constraints.withCString { consStr in + LLVMConstInlineAsm(type.typeRef, asmStr, consStr, hasSideEffects.llvm, isAlignStack.llvm)! + } + } + return Value(llvm: valueRef) + } + } + */ From c43e751647b88e83ae441200f92c74dbab105f27 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 20 Oct 2021 08:31:24 +0200 Subject: [PATCH 34/38] Update Package.swift conditional config --- Package.swift | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/Package.swift b/Package.swift index 923351e..ac154dc 100644 --- a/Package.swift +++ b/Package.swift @@ -7,8 +7,32 @@ import PackageDescription // Get LLVM flags and version #if CLI_BUILD let (cFlags, linkFlags, _version) = try! getLLVMConfig() + let customSystemLibrary: Target = .systemLibrary( + name: "CLLVM", + path: "llvm-api/CLLVM" + ) + let llvmTarget: Target = .target( + name: "LLVM", + dependencies: ["CLLVM"], + path: "llvm-api/LLVM", + cSettings: [ + .unsafeFlags(cFlags), + ], + linkerSettings: [ + .unsafeFlags(linkFlags), + ] + ) #else - let (cFlags, linkFlags, _version) = ([String](), [String](), [Int]()) + let customSystemLibrary: Target = .systemLibrary( + name: "CLLVM", + path: "llvm-api/CLLVM", + pkgConfig: "cllvm" + ) + let llvmTarget: Target = .target( + name: "LLVM", + dependencies: ["CLLVM"], + path: "llvm-api/LLVM" + ) #endif let package = Package( @@ -17,22 +41,8 @@ let package = Package( .library(name: "llvm-api", targets: ["LLVM"]), ], targets: [ - .systemLibrary( - name: "CLLVM", - path: "llvm-api/CLLVM", - pkgConfig: "cllvm" - ), - .target( - name: "LLVM", - dependencies: ["CLLVM"], - path: "llvm-api/LLVM", - cSettings: [ - .unsafeFlags(cFlags), - ], - linkerSettings: [ - .unsafeFlags(linkFlags), - ] - ), + customSystemLibrary, + llvmTarget, ] ) From 7b72ed6072898628c30b6eafeb3cf775b26d1a55 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 21 Oct 2021 14:11:49 +0200 Subject: [PATCH 35/38] Update CI conditional build --- .github/workflows/swift.yaml | 2 +- Package.swift | 75 +++++++++++++++++++----------------- 2 files changed, 41 insertions(+), 36 deletions(-) diff --git a/.github/workflows/swift.yaml b/.github/workflows/swift.yaml index 1f7b555..9740de5 100644 --- a/.github/workflows/swift.yaml +++ b/.github/workflows/swift.yaml @@ -29,7 +29,7 @@ jobs: swift --version - name: Build - run: swift build -Xswiftc -DCLI_BUILD + run: CLI_BUILD=1 swift build # - name: Run tests # run: swift test -v diff --git a/Package.swift b/Package.swift index ac154dc..89ee13f 100644 --- a/Package.swift +++ b/Package.swift @@ -4,46 +4,12 @@ import Foundation import PackageDescription -// Get LLVM flags and version -#if CLI_BUILD - let (cFlags, linkFlags, _version) = try! getLLVMConfig() - let customSystemLibrary: Target = .systemLibrary( - name: "CLLVM", - path: "llvm-api/CLLVM" - ) - let llvmTarget: Target = .target( - name: "LLVM", - dependencies: ["CLLVM"], - path: "llvm-api/LLVM", - cSettings: [ - .unsafeFlags(cFlags), - ], - linkerSettings: [ - .unsafeFlags(linkFlags), - ] - ) -#else - let customSystemLibrary: Target = .systemLibrary( - name: "CLLVM", - path: "llvm-api/CLLVM", - pkgConfig: "cllvm" - ) - let llvmTarget: Target = .target( - name: "LLVM", - dependencies: ["CLLVM"], - path: "llvm-api/LLVM" - ) -#endif - let package = Package( name: "llvm-api", products: [ .library(name: "llvm-api", targets: ["LLVM"]), ], - targets: [ - customSystemLibrary, - llvmTarget, - ] + targets: getTargets() ) /// Get LLVM config flags @@ -109,3 +75,42 @@ extension String: Error { return components.joined(separator: separator) } } + +/// Check Environ,ent variable +func hasEnvironmentVariable(_ name: String) -> Bool { + ProcessInfo.processInfo.environment[name] != nil +} + +func getTargets() -> [Target] { + if hasEnvironmentVariable("CLI_BUILD") { + let (cFlags, linkFlags, _) = try! getLLVMConfig() + let customSystemLibrary: Target = .systemLibrary( + name: "CLLVM", + path: "llvm-api/CLLVM" + ) + let llvmTarget: Target = .target( + name: "LLVM", + dependencies: ["CLLVM"], + path: "llvm-api/LLVM", + cSettings: [ + .unsafeFlags(cFlags), + ], + linkerSettings: [ + .unsafeFlags(linkFlags), + ] + ) + return [customSystemLibrary, llvmTarget] + } else { + let customSystemLibrary: Target = .systemLibrary( + name: "CLLVM", + path: "llvm-api/CLLVM", + pkgConfig: "cllvm" + ) + let llvmTarget: Target = .target( + name: "LLVM", + dependencies: ["CLLVM"], + path: "llvm-api/LLVM" + ) + return [customSystemLibrary, llvmTarget] + } +} From 4b5c32278ffa86524e04e4abf10a4f34ae4f05ad Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 17 Jul 2024 14:49:48 +0200 Subject: [PATCH 36/38] Restructure project and extend README --- Package.swift | 10 +- README.md | 10 ++ {llvm-api => Source}/CLLVM/bridge.h | 0 {llvm-api => Source}/CLLVM/module.modulemap | 0 .../LLVM/Core/AddressSpace.swift | 0 .../LLVM/Core/BasicBlock.swift | 0 {llvm-api => Source}/LLVM/Core/Context.swift | 0 {llvm-api => Source}/LLVM/Core/Core.swift | 0 .../LLVM/Core/Diagnostic.swift | 0 .../LLVM/Core/Functions.swift | 0 {llvm-api => Source}/LLVM/Core/Modules.swift | 0 .../LLVM/Core/Types/Array.swift | 0 .../LLVM/Core/Types/Float.swift | 0 .../LLVM/Core/Types/Function.swift | 0 .../LLVM/Core/Types/Int.swift | 0 .../LLVM/Core/Types/Other/Label.swift | 0 .../LLVM/Core/Types/Other/Metadata.swift | 0 .../LLVM/Core/Types/Other/TargetExt.swift | 0 .../LLVM/Core/Types/Other/Token.swift | 0 .../LLVM/Core/Types/Other/Void.swift | 0 .../LLVM/Core/Types/Other/X86AMX.swift | 0 .../LLVM/Core/Types/Other/X86MMX.swift | 0 .../LLVM/Core/Types/Pointer.swift | 0 .../LLVM/Core/Types/Struct.swift | 0 .../LLVM/Core/Types/Types.swift | 0 .../LLVM/Core/Types/Vector.swift | 0 .../Core/Values/Constants/Composite.swift | 0 .../Core/Values/Constants/Constants.swift | 0 .../Core/Values/Constants/Expressions.swift | 0 .../LLVM/Core/Values/Constants/Scalar.swift | 0 .../LLVM/Core/Values/Value.swift | 0 utils/llvm-pkg.swift | 134 ++++++++++++++++++ 32 files changed, 149 insertions(+), 5 deletions(-) rename {llvm-api => Source}/CLLVM/bridge.h (100%) rename {llvm-api => Source}/CLLVM/module.modulemap (100%) rename {llvm-api => Source}/LLVM/Core/AddressSpace.swift (100%) rename {llvm-api => Source}/LLVM/Core/BasicBlock.swift (100%) rename {llvm-api => Source}/LLVM/Core/Context.swift (100%) rename {llvm-api => Source}/LLVM/Core/Core.swift (100%) rename {llvm-api => Source}/LLVM/Core/Diagnostic.swift (100%) rename {llvm-api => Source}/LLVM/Core/Functions.swift (100%) rename {llvm-api => Source}/LLVM/Core/Modules.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Array.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Float.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Function.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Int.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/Label.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/Metadata.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/TargetExt.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/Token.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/Void.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/X86AMX.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Other/X86MMX.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Pointer.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Struct.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Types.swift (100%) rename {llvm-api => Source}/LLVM/Core/Types/Vector.swift (100%) rename {llvm-api => Source}/LLVM/Core/Values/Constants/Composite.swift (100%) rename {llvm-api => Source}/LLVM/Core/Values/Constants/Constants.swift (100%) rename {llvm-api => Source}/LLVM/Core/Values/Constants/Expressions.swift (100%) rename {llvm-api => Source}/LLVM/Core/Values/Constants/Scalar.swift (100%) rename {llvm-api => Source}/LLVM/Core/Values/Value.swift (100%) create mode 100755 utils/llvm-pkg.swift diff --git a/Package.swift b/Package.swift index 89ee13f..06fccd4 100644 --- a/Package.swift +++ b/Package.swift @@ -91,7 +91,7 @@ func getTargets() -> [Target] { let llvmTarget: Target = .target( name: "LLVM", dependencies: ["CLLVM"], - path: "llvm-api/LLVM", + // path: "llvm-api/LLVM", cSettings: [ .unsafeFlags(cFlags), ], @@ -103,13 +103,13 @@ func getTargets() -> [Target] { } else { let customSystemLibrary: Target = .systemLibrary( name: "CLLVM", - path: "llvm-api/CLLVM", - pkgConfig: "cllvm" + // path: "llvm-api/CLLVM", + pkgConfig: "llvm" ) let llvmTarget: Target = .target( name: "LLVM", - dependencies: ["CLLVM"], - path: "llvm-api/LLVM" + dependencies: ["CLLVM"] + // path: "llvm-api/LLVM" ) return [customSystemLibrary, llvmTarget] } diff --git a/README.md b/README.md index 9f6827c..0263259 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,13 @@ brew install llvm - [x] v18.0 +### XCode support + +To develop correctly with XCode it's necessary to generate package-config: `llvm.pc`: +- `sh utils/llvm-pkg.swift` - will generate package config and copy to your default `pkg-config` path. + +After that XCode should correctly recognize LLVM headers path, and can build project. + ### Troubleshooting If `LLVM-C` head files during compilation doesn't found, make sure that you are: @@ -53,6 +60,9 @@ llc --version brew info llvm ``` +- **conditional build**: `Package.swift` supports conditional builds: + - for CLI build: `CLI_BUILD swift build` - it get's LLVM veriabels form Environment sets. + - `swift build` - if presented `llvm.pc` package config - To get more insights take a look current project [Github CI config](.github/workflows/swift.yaml). ### LICENS: [MIT](LICENSE) diff --git a/llvm-api/CLLVM/bridge.h b/Source/CLLVM/bridge.h similarity index 100% rename from llvm-api/CLLVM/bridge.h rename to Source/CLLVM/bridge.h diff --git a/llvm-api/CLLVM/module.modulemap b/Source/CLLVM/module.modulemap similarity index 100% rename from llvm-api/CLLVM/module.modulemap rename to Source/CLLVM/module.modulemap diff --git a/llvm-api/LLVM/Core/AddressSpace.swift b/Source/LLVM/Core/AddressSpace.swift similarity index 100% rename from llvm-api/LLVM/Core/AddressSpace.swift rename to Source/LLVM/Core/AddressSpace.swift diff --git a/llvm-api/LLVM/Core/BasicBlock.swift b/Source/LLVM/Core/BasicBlock.swift similarity index 100% rename from llvm-api/LLVM/Core/BasicBlock.swift rename to Source/LLVM/Core/BasicBlock.swift diff --git a/llvm-api/LLVM/Core/Context.swift b/Source/LLVM/Core/Context.swift similarity index 100% rename from llvm-api/LLVM/Core/Context.swift rename to Source/LLVM/Core/Context.swift diff --git a/llvm-api/LLVM/Core/Core.swift b/Source/LLVM/Core/Core.swift similarity index 100% rename from llvm-api/LLVM/Core/Core.swift rename to Source/LLVM/Core/Core.swift diff --git a/llvm-api/LLVM/Core/Diagnostic.swift b/Source/LLVM/Core/Diagnostic.swift similarity index 100% rename from llvm-api/LLVM/Core/Diagnostic.swift rename to Source/LLVM/Core/Diagnostic.swift diff --git a/llvm-api/LLVM/Core/Functions.swift b/Source/LLVM/Core/Functions.swift similarity index 100% rename from llvm-api/LLVM/Core/Functions.swift rename to Source/LLVM/Core/Functions.swift diff --git a/llvm-api/LLVM/Core/Modules.swift b/Source/LLVM/Core/Modules.swift similarity index 100% rename from llvm-api/LLVM/Core/Modules.swift rename to Source/LLVM/Core/Modules.swift diff --git a/llvm-api/LLVM/Core/Types/Array.swift b/Source/LLVM/Core/Types/Array.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Array.swift rename to Source/LLVM/Core/Types/Array.swift diff --git a/llvm-api/LLVM/Core/Types/Float.swift b/Source/LLVM/Core/Types/Float.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Float.swift rename to Source/LLVM/Core/Types/Float.swift diff --git a/llvm-api/LLVM/Core/Types/Function.swift b/Source/LLVM/Core/Types/Function.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Function.swift rename to Source/LLVM/Core/Types/Function.swift diff --git a/llvm-api/LLVM/Core/Types/Int.swift b/Source/LLVM/Core/Types/Int.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Int.swift rename to Source/LLVM/Core/Types/Int.swift diff --git a/llvm-api/LLVM/Core/Types/Other/Label.swift b/Source/LLVM/Core/Types/Other/Label.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/Label.swift rename to Source/LLVM/Core/Types/Other/Label.swift diff --git a/llvm-api/LLVM/Core/Types/Other/Metadata.swift b/Source/LLVM/Core/Types/Other/Metadata.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/Metadata.swift rename to Source/LLVM/Core/Types/Other/Metadata.swift diff --git a/llvm-api/LLVM/Core/Types/Other/TargetExt.swift b/Source/LLVM/Core/Types/Other/TargetExt.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/TargetExt.swift rename to Source/LLVM/Core/Types/Other/TargetExt.swift diff --git a/llvm-api/LLVM/Core/Types/Other/Token.swift b/Source/LLVM/Core/Types/Other/Token.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/Token.swift rename to Source/LLVM/Core/Types/Other/Token.swift diff --git a/llvm-api/LLVM/Core/Types/Other/Void.swift b/Source/LLVM/Core/Types/Other/Void.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/Void.swift rename to Source/LLVM/Core/Types/Other/Void.swift diff --git a/llvm-api/LLVM/Core/Types/Other/X86AMX.swift b/Source/LLVM/Core/Types/Other/X86AMX.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/X86AMX.swift rename to Source/LLVM/Core/Types/Other/X86AMX.swift diff --git a/llvm-api/LLVM/Core/Types/Other/X86MMX.swift b/Source/LLVM/Core/Types/Other/X86MMX.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Other/X86MMX.swift rename to Source/LLVM/Core/Types/Other/X86MMX.swift diff --git a/llvm-api/LLVM/Core/Types/Pointer.swift b/Source/LLVM/Core/Types/Pointer.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Pointer.swift rename to Source/LLVM/Core/Types/Pointer.swift diff --git a/llvm-api/LLVM/Core/Types/Struct.swift b/Source/LLVM/Core/Types/Struct.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Struct.swift rename to Source/LLVM/Core/Types/Struct.swift diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/Source/LLVM/Core/Types/Types.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Types.swift rename to Source/LLVM/Core/Types/Types.swift diff --git a/llvm-api/LLVM/Core/Types/Vector.swift b/Source/LLVM/Core/Types/Vector.swift similarity index 100% rename from llvm-api/LLVM/Core/Types/Vector.swift rename to Source/LLVM/Core/Types/Vector.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Composite.swift b/Source/LLVM/Core/Values/Constants/Composite.swift similarity index 100% rename from llvm-api/LLVM/Core/Values/Constants/Composite.swift rename to Source/LLVM/Core/Values/Constants/Composite.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Constants.swift b/Source/LLVM/Core/Values/Constants/Constants.swift similarity index 100% rename from llvm-api/LLVM/Core/Values/Constants/Constants.swift rename to Source/LLVM/Core/Values/Constants/Constants.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Expressions.swift b/Source/LLVM/Core/Values/Constants/Expressions.swift similarity index 100% rename from llvm-api/LLVM/Core/Values/Constants/Expressions.swift rename to Source/LLVM/Core/Values/Constants/Expressions.swift diff --git a/llvm-api/LLVM/Core/Values/Constants/Scalar.swift b/Source/LLVM/Core/Values/Constants/Scalar.swift similarity index 100% rename from llvm-api/LLVM/Core/Values/Constants/Scalar.swift rename to Source/LLVM/Core/Values/Constants/Scalar.swift diff --git a/llvm-api/LLVM/Core/Values/Value.swift b/Source/LLVM/Core/Values/Value.swift similarity index 100% rename from llvm-api/LLVM/Core/Values/Value.swift rename to Source/LLVM/Core/Values/Value.swift diff --git a/utils/llvm-pkg.swift b/utils/llvm-pkg.swift new file mode 100755 index 0000000..5d1672f --- /dev/null +++ b/utils/llvm-pkg.swift @@ -0,0 +1,134 @@ +#!/usr/bin/env swift +import Foundation + +#if os(Linux) + let libCPP = "-L/usr/lib -lc++" +#elseif os(macOS) + let libCPP = "-lc++" +#endif + +/// Runs the specified program at the provided path. +/// - parameter path: The full path of the executable you +/// wish to run. +/// - parameter args: The arguments you wish to pass to the +/// process. +/// - returns: The standard output of the process, or nil if it was empty. +func run(_ path: String, args: [String] = []) -> String? { + print("Running \(path) \(args.joined(separator: " "))...") + let pipe = Pipe() + let process = Process() + process.executableURL = URL(fileURLWithPath: path) + process.arguments = args + process.standardOutput = pipe + try? process.run() + process.waitUntilExit() + + let data = pipe.fileHandleForReading.readDataToEndOfFile() + guard let result = String(data: data, encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !result.isEmpty else { return nil } + return result +} + +/// Finds the location of the provided binary on your system. +func which(_ name: String) -> String? { + return run("/usr/bin/which", args: [name]) +} + +extension String: Error { + /// Replaces all occurrences of characters in the provided set with + /// the provided string. + func replacing(charactersIn characterSet: CharacterSet, + with separator: String) -> String { + let components = self.components(separatedBy: characterSet) + return components.joined(separator: separator) + } +} + +func makeFile() throws { + let brewPrefix = { + guard let brew = which("brew") else { return nil } + return run(brew, args: ["--prefix"]) + }() ?? "/usr/local" + + let pkgConfigPath = "\(brewPrefix)/lib/pkgconfig" + let pkgConfigDir = URL(fileURLWithPath: pkgConfigPath) + + // Make /lib/pkgconfig if it doesn't already exist + if !FileManager.default.fileExists(atPath: pkgConfigPath) { + try FileManager.default.createDirectory(at: pkgConfigDir, + withIntermediateDirectories: true) + } + let cllvmPath = pkgConfigDir.appendingPathComponent("llvm.pc") + let brewLLVMConfig = { which("\(brewPrefix)/opt/llvm/bin/llvm-config") } + + /// Ensure we have llvm-config in the PATH + guard let llvmConfig = which("llvm-config-15") ?? which("llvm-config") ?? brewLLVMConfig() else { + throw "Failed to find llvm-config. Ensure llvm-config is installed and " + + "in your PATH" + } + + /// Extract the info we need from llvm-config + + print("Found llvm-config at \(llvmConfig)...") + + let versionStr = run(llvmConfig, args: ["--version"])! + .replacing(charactersIn: .newlines, with: "") + .replacingOccurrences(of: "svn", with: "") + let components = versionStr.components(separatedBy: ".") + .compactMap { Int($0) } + + guard components.count == 3 else { + throw "Invalid version number \(versionStr)" + } + + let version = (components[0], components[1], components[2]) + + guard version >= (15, 0, 0) else { + throw "LLVMSwift requires LLVM version >=15.0.0, but you have \(versionStr)" + } + + print("LLVM version is \(versionStr)") + + let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", + "--system-libs"])! + .replacing(charactersIn: .newlines, with: " ") + .components(separatedBy: " ") + .filter { !$0.hasPrefix("-W") } + .joined(separator: " ") + + // SwiftPM has a whitelisted set of cflags that it understands, and + // unfortunately that includes almost everything but the include dir. + + let cFlags = run(llvmConfig, args: ["--cflags"])! + .replacing(charactersIn: .newlines, with: "") + .components(separatedBy: " ") + .filter { $0.hasPrefix("-I") } + .joined(separator: " ") + + /// Emit the pkg-config file to the path + + let s = [ + "Name: cllvm", + "Description: The llvm library", + "Version: \(versionStr)", + "Libs: \(ldFlags) \(libCPP)", + "Requires.private:", + "Cflags: \(cFlags)", + ].joined(separator: "\n") + + print("Writing pkg-config file to \(cllvmPath.path)...") + + try s.write(toFile: cllvmPath.path, atomically: true, encoding: .utf8) + + print("\nSuccessfully wrote pkg-config file!") + print("Make sure to re-run this script when you update LLVM.") +} + +do { + try makeFile() +} catch { + print("error: \(error)") + exit(-1) +} + From 2c3a082755d4c0c8c84be40003fd199dfbf3c87f Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 22 Oct 2021 10:12:41 +0200 Subject: [PATCH 37/38] Exnted Module with Flag and Metadata funcitons --- llvm-api/LLVM/Core/Context.swift | 9 +- llvm-api/LLVM/Core/Modules.swift | 204 +++++++++++++++++++++++++-- llvm-api/LLVM/Core/Types/Types.swift | 6 +- 3 files changed, 202 insertions(+), 17 deletions(-) diff --git a/llvm-api/LLVM/Core/Context.swift b/llvm-api/LLVM/Core/Context.swift index 88fda05..2468a7f 100644 --- a/llvm-api/LLVM/Core/Context.swift +++ b/llvm-api/LLVM/Core/Context.swift @@ -222,12 +222,19 @@ public final class Context: ContextRef { } } + ///Destroy a context instance. + /// + /// This should be called for every call to LLVMContextCreate() or memory will be leaked. + public func dispose() { + LLVMContextDispose(llvm) + } + /// Deinitialize this value and dispose of its resources. /// /// Destroy a context instance. /// This should be called for every call to LLVMContextCreate() or memory /// will be leaked. deinit { - LLVMContextDispose(llvm) + self.dispose() } } diff --git a/llvm-api/LLVM/Core/Modules.swift b/llvm-api/LLVM/Core/Modules.swift index 6a97bbd..3212ab8 100644 --- a/llvm-api/LLVM/Core/Modules.swift +++ b/llvm-api/LLVM/Core/Modules.swift @@ -9,6 +9,152 @@ public final class Module: ModuleRef { /// Retrieves the underlying LLVM value object. public var moduleRef: LLVMModuleRef { llvm } + public enum InlineAsmDialect { + case att + case intel + } + + /// Named Metadata Node + public class NamedMetadataNode: NamedMetadataNodeRef { + private var llvm: LLVMNamedMDNodeRef + + /// Retrieves the underlying LLVM value object. + public var namedMetadataNodeRef: LLVMNamedMDNodeRef { llvm } + + init(llvm: LLVMNamedMDNodeRef) { + self.llvm = llvm + } + + /// Advance a `NamedMetaDataNode` iterator to the next `NamedMetaDataNode`. + /// + /// Returns NULL if the iterator was already at the end and there are no more + /// named metadata nodes. + public func getNext() -> NamedMetadataNode? { + guard let nextRef = LLVMGetNextNamedMetadata(llvm) else { + return nil + } + return NamedMetadataNode(llvm: nextRef) + } + + /// Decrement a `NamedMetaDataNode` iterator to the previous `NamedMetaDataNode`. + /// + /// Returns NULL if the iterator was already at the beginning and there are + /// no previously named metadata nodes. + public func getPrevious() -> NamedMetadataNode? { + guard let prevRef = LLVMGetPreviousNamedMetadata(llvm) else { + return nil + } + return NamedMetadataNode(llvm: prevRef) + } + + /// Retrieve the name of a `NamedMetadataNode`. + public func getName() -> String? { + var length: size_t = 0 + guard let cStr = LLVMGetNamedMetadataName(llvm, &length) else { + return nil + } + return String(cString: cStr) + } + } + + /// Enumerates the supported behaviors for resolving collisions when two + /// module flags share the same key. These collisions can occur when the + /// different flags are inserted under the same key, or when modules + /// containing flags under the same key are merged. + public enum ModuleFlagBehavior { + /// Emits an error if two values disagree, otherwise the resulting value + /// is that of the operands. + case error + /// Emits a warning if two values disagree. The result value will be the + /// operand for the flag from the first module being linked. + case warning + /// Adds a requirement that another module flag be present and have a + /// specified value after linking is performed. The value must be a + /// metadata pair, where the first element of the pair is the ID of the + /// module flag to be restricted, and the second element of the pair is + /// the value the module flag should be restricted to. This behavior can + /// be used to restrict the allowable results (via triggering of an error) + /// of linking IDs with the **Override** behavior. + case require + /// Uses the specified value, regardless of the behavior or value of the + /// other module. If both modules specify **Override**, but the values + /// differ, an error will be emitted. + case override + /// Appends the two values, which are required to be metadata nodes. + case append + /// Appends the two values, which are required to be metadata + /// nodes. However, duplicate entries in the second list are dropped + /// during the append operation. + case appendUnique + + init(raw: LLVMModuleFlagBehavior) { + switch raw { + case LLVMModuleFlagBehaviorError: + self = .error + case LLVMModuleFlagBehaviorWarning: + self = .warning + case LLVMModuleFlagBehaviorRequire: + self = .require + case LLVMModuleFlagBehaviorOverride: + self = .override + case LLVMModuleFlagBehaviorAppend: + self = .append + case LLVMModuleFlagBehaviorAppendUnique: + self = .appendUnique + default: + fatalError("Unknown behavior kind") + } + } + } + + class Metadata: MetadataRef { + private let llvm:LLVMMetadataRef + public var metadataRef: LLVMMetadataRef { + llvm } + public init(llvm: LLVMMetadataRef ) { + self.llvm = llvm + } + } + + public class ModuleFlagEntry { + private let llvm: OpaquePointer? + private let bounds: Int + + public init(llvm:OpaquePointer?, bounds: Int) { + self.llvm = llvm + self.bounds = bounds + } + + /// Get Metadata flags etries count + public var count: Int { self.bounds } + + /// Returns the flag behavior for a module flag entry at a specific index. + public func getFlagBehavior(at index: UInt32) -> ModuleFlagBehavior { + let bh = LLVMModuleFlagEntriesGetFlagBehavior(llvm, index) + return ModuleFlagBehavior(raw: bh) + } + + /// Returns the key for a module flag entry at a specific index. + public func getKey(at index: UInt32) -> String { + var length: Int = 0 + let keyPointer = LLVMModuleFlagEntriesGetKey(llvm, index, &length) + return String(cString: keyPointer!) + + } + + /// Returns the metadata for a module flag entry at a specific index. + public func getMetadata(at index: UInt32) -> MetadataRef { + let metadata = LLVMModuleFlagEntriesGetMetadata(llvm, index)! + return Metadata(llvm: metadata) + } + + /// Deinitialize this value and dispose of its resources. + deinit { + guard let ptr = llvm else { return } + LLVMDisposeModuleFlagsMetadata(ptr) + } + } + /// Init function by LLVM Value public init(llvm: LLVMModuleRef) { self.llvm = llvm @@ -36,33 +182,46 @@ public final class Module: ModuleRef { } /// Return an exact copy of the specified module. - public func clone_nodule() -> ModuleRef { + public func cloneModule() -> Self { let new_module = LLVMCloneModule(llvm)! return Self(llvm: new_module) } + /// Get and Set the identifier of a module. + public var moduleIdentifier: String { + get { + self.getModuleIdentifier + } + set { + self.setModuleIdentifier(identifier: newValue) + } + } + /// Obtain the identifier of a module. - public var getLLVMModuleIdentifier: String { + public var getModuleIdentifier: String { var length: UInt = 0 guard let cString = LLVMGetModuleIdentifier(llvm, &length) else { return "" } return String(cString: cString) } - public func setLLVMModuleIdentifier(module: LLVMModuleRef, identifier: String) { + /// Set the identifier of a module to a string Ident with length Len. + public func setModuleIdentifier(identifier: String) { identifier.withCString { cString in - LLVMSetModuleIdentifier(module, cString, identifier.count) + LLVMSetModuleIdentifier(llvm, cString, identifier.count) } } - public var getModuleIdentifier: String? { - var length: UInt = 0 - guard let cString = LLVMGetModuleIdentifier(llvm, &length) else { - return nil + /// Get and Set the original source file name of a module to a string Name + public var sourceFileName: String { + get { + self.getSourceFileName! + } + set { + self.setSourceFileName(fileName: newValue) } - return String(cString: cString) } - /// Set the identifier of a module to a string Ident with length Len. + ///Set the original source file name of a module to a string Name public func setSourceFileName(fileName: String) { fileName.withCString { cString in LLVMSetSourceFileName(llvm, cString, fileName.utf8.count) @@ -71,7 +230,7 @@ public final class Module: ModuleRef { /// Obtain the module's original source file name. public var getSourceFileName: String? { - var length: size_t = 0 + var length: Int = 0 guard let cString = LLVMGetSourceFileName(llvm, &length) else { return nil } @@ -79,9 +238,9 @@ public final class Module: ModuleRef { } /// Set the data layout for a module. - public func setDataLayout(module: LLVMModuleRef, dataLayout: String) { + public func setDataLayout(dataLayout: String) { dataLayout.withCString { cString in - LLVMSetDataLayout(module, cString) + LLVMSetDataLayout(llvm, cString) } } @@ -93,6 +252,15 @@ public final class Module: ModuleRef { return String(cString: cString) } + + /// Obtain the target triple for a module. + func getTargetTriple() -> String { + guard let targetTriplePointer = LLVMGetTarget(llvm) else { + return "" + } + return String(cString: targetTriplePointer) + } + /// Set the target triple for a module. public func setTarget(triple: String) { triple.withCString { cString in @@ -100,6 +268,16 @@ public final class Module: ModuleRef { } } + /// Returns the module flags as an array of flag-key-value triples. The caller + /// is responsible for freeing this array by calling + /// `LLVMDisposeModuleFlagsMetadata`. + public func copyModuleFlagsMetadata() -> ModuleFlagEntry? { + var length: Int = 0 + guard let flagsPointer = LLVMCopyModuleFlagsMetadata(llvm, &length) else { return nil } + + return ModuleFlagEntry(llvm: flagsPointer, bounds: length) + } + /// Destroy a module instance. /// /// This must be called for every created module or memory will be leaked. diff --git a/llvm-api/LLVM/Core/Types/Types.swift b/llvm-api/LLVM/Core/Types/Types.swift index 216507a..1231e6f 100644 --- a/llvm-api/LLVM/Core/Types/Types.swift +++ b/llvm-api/LLVM/Core/Types/Types.swift @@ -71,9 +71,9 @@ public protocol ModuleRef { var moduleRef: LLVMModuleRef { get } } -/// Represents an LLVM Named Metadata Node. -public protocol NamedMDNodeRef { - var namedMDNodeRef: LLVMNamedMDNodeRef { get } +/// Represents an LLVM Named Metadata Node (NamedMDNodeRef). +public protocol NamedMetadataNodeRef { + var namedMetadataNodeRef: LLVMNamedMDNodeRef { get } } public protocol OperandBundleRef { From 0157b3d2c1c2a6038ea17a17402a8c6d1d8756cd Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 23 Jul 2024 00:19:26 +0200 Subject: [PATCH 38/38] Extend README --- README.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9f6827c..2da030b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,68 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Swift CI](https://github.com/mrLSD/llvm-api-swift/actions/workflows/swift.yaml/badge.svg)](https://github.com/mrLSD/llvm-api-swift/actions/workflows/swift.yaml) -# `llvm-api-swift` +
+

mrLSD/llvm-api-swift

+
`llvm-api-swift` is a library representing Swift LLVM API, a pure Swift interface to the [LLVM API](https://llvm.org/docs/) and its associated libraries. It provides native, easy-to-use components to create compilers codegen backend. It contains LLVM bindings, components and toolset for efficiently use LLVM as compilers backend implementation on Swift. +## Overview + +The `llvm-api-swift` provides a robust and comprehensive interface to the LLVM Compiler Infrastructure, +leveraging the `LLVM-C API` to offer a blend of safety, flexibility, and extendability. This library +is designed to serve as a powerful tool for developers looking to create backends for compilers, enabling +them to harness the full potential of **LLVM** in a secure and user-friendly manner. + +## Safety + +Safety is a paramount concern in the design of this library. By building on the `LLVM-C API`, we ensure that +interactions +with the **LLVM** infrastructure are conducted in a type-safe and memory-safe manner. The library employs Swift’s +stringent +safety guarantees to prevent common issues such as null pointer dereferencing, buffer overflows, and memory leaks. This +commitment to safety allows developers to focus on the functionality of their compiler backends without worrying about +underlying security vulnerabilities. + +## Flexibility + +Flexibility is another core attribute of the `llvm-api-swift`. The library provides a rich set of APIs that cover a wide +range of LLVM’s capabilities, from module management and inline assembly to debugging metadata and function iteration. +Developers can easily access and manipulate **LLVM** constructs, enabling the creation of highly customized and +optimized +compiler backends. The library’s design ensures that it can adapt to various use cases and requirements, making it an +ideal choice for a diverse set of compiler development projects based on Swift. + +## Extendability + +The 'llvm-api-swift' is built with extendability in mind. It is designed to be easily extendable, allowing developers to +add +new functionalities and support for additional **LLVM** features as needed. The modular structure of the library +facilitates +the incorporation of new components, ensuring that it can grow and evolve alongside the **LLVM** ecosystem. This +extendability ensures that the library remains relevant and useful as **LLVM** continues to advance and expand its +capabilities. + +## Why LLVM? + +**LLVM** (Low-Level Virtual Machine) is a powerful and versatile compiler infrastructure that provides a collection of +modular and reusable compiler and toolchain technologies. It is widely used in the development of modern compilers, +providing a framework for optimizing intermediate representations and generating machine code for various target +architectures. LLVM’s ability to support multiple languages and platforms, coupled with its extensive optimization +capabilities, makes it an essential tool for compiler developers. By leveraging **LLVM**, developers can create highly +efficient and portable compilers that meet the demands of today’s diverse computing environments. + +## Design + +The `llvm-api-awift` library adheres to the structure of the `LLVM C API`, ensuring easy navigation through the extensive LLVM +functions. Logical elements are grouped into modules, providing a clear organizational structure. Within these modules, +Rust structures are introduced to wrap LLVM types, implementing corresponding functions for the wrapped LLVM types. This +approach enhances flexibility and usability while maintaining the original LLVM code structure. The design avoids +unnecessary complexity in the code and documentation, remaining fully aligned with the `LLVM API`. This alignment allows +developers to easily navigate the `llvm-api-swift` library using existing LLVM-C documentation. + ### Compatibility with LLVM-C API When creating the library, we were guided by **full compatibility** with [LLVM-C API](https://llvm.org/doxygen/group__LLVMC.html). @@ -15,8 +71,7 @@ And filling the components also with the appropriate `LLVM-C API`. When implementing Swift types, we were guided by the approach of abstracting away from C types, completely transforming them into Swift types. At the same time adhering to the principles of a safety and reliability implementation - without explicit memory management, means of safe techniques, functions provided by Swift. - -### Requirements +## Requirements - Supported OS: MacOS 12.0 or above