Repository navigation
Expose function cloning and local IR transformation utilities #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
xushiwei
merged 2 commits into
xgo-dev:xgo
from
zhouguangyuan0718:codex/ir-cloning-go-api-20261007
Oct 10, 2026
+496
−0
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
| // See https://llvm.org/LICENSE.txt for license information. | ||
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
|
|
||
| // Generic LLVM utilities exposed to Go; policy belongs to the caller. | ||
| #include "transforms.h" | ||
| #include "llvm/IR/DebugInfoMetadata.h" | ||
| #include "llvm/IR/InlineAsm.h" | ||
| #include "llvm/IR/Instructions.h" | ||
| #include "llvm/IR/Module.h" | ||
| #include "llvm/Transforms/Utils/Cloning.h" | ||
| #include "llvm/Transforms/Utils/Local.h" | ||
| using namespace llvm; | ||
|
|
||
| // Keep the Go TailCallKind constants and the C boundary in sync with LLVM. | ||
| static_assert(CallInst::TCK_None == 0 && CallInst::TCK_Tail == 1 && | ||
| CallInst::TCK_MustTail == 2 && CallInst::TCK_NoTail == 3, | ||
| "update the Go TailCallKind constants for this LLVM version"); | ||
|
|
||
| LLVMValueRef LLVMGoGetNamedValue(LLVMModuleRef M, const char *Name, | ||
| size_t Len) { | ||
| return wrap(unwrap(M)->getNamedValue(StringRef(Name, Len))); | ||
| } | ||
| LLVMValueRef LLVMGoCloneFunction(LLVMValueRef Fn) { | ||
| auto *F = Fn ? dyn_cast<Function>(unwrap(Fn)) : nullptr; | ||
| if (!F) | ||
| return nullptr; | ||
| ValueToValueMapTy Map; | ||
| return wrap(CloneFunction(F, Map)); | ||
| } | ||
| LLVMBool LLVMGoSimplifyInstructionsInBlock(LLVMBasicBlockRef BB) { | ||
| return SimplifyInstructionsInBlock(unwrap(BB)); | ||
| } | ||
| LLVMBool LLVMGoConstantFoldTerminator(LLVMBasicBlockRef BB, | ||
| LLVMBool DeleteDead) { | ||
| return ConstantFoldTerminator(unwrap(BB), DeleteDead); | ||
| } | ||
| int LLVMGoRemoveUnreachableBlocks(LLVMValueRef Fn) { | ||
| auto *F = Fn ? dyn_cast<Function>(unwrap(Fn)) : nullptr; | ||
| if (!F || F->isDeclaration()) | ||
| return -1; | ||
| return removeUnreachableBlocks(*F); | ||
| } | ||
| LLVMBool LLVMGoSetSubprogramLinkageName(LLVMMetadataRef SP, const char *Name, | ||
| size_t Len) { | ||
| auto *Subprogram = SP ? dyn_cast<DISubprogram>(unwrap(SP)) : nullptr; | ||
| if (!Subprogram) | ||
| return false; | ||
| Subprogram->replaceLinkageName( | ||
| MDString::get(Subprogram->getContext(), StringRef(Name, Len))); | ||
| return true; | ||
| } | ||
| LLVMBool LLVMGoSetTailCallKind(LLVMValueRef Call, unsigned Kind) { | ||
| auto *CI = Call ? dyn_cast<CallInst>(unwrap(Call)) : nullptr; | ||
| if (!CI || Kind > CallInst::TCK_NoTail) | ||
| return false; | ||
| CI->setTailCallKind(static_cast<CallInst::TailCallKind>(Kind)); | ||
| return true; | ||
| } | ||
| unsigned LLVMGoGetTailCallKind(LLVMValueRef Call) { | ||
| auto *CI = Call ? dyn_cast<CallInst>(unwrap(Call)) : nullptr; | ||
| return CI ? CI->getTailCallKind() : ~0u; | ||
| } | ||
| LLVMGoInlineAsmInfo LLVMGoGetInlineAsmInfo(LLVMValueRef Asm) { | ||
| auto *A = Asm ? dyn_cast<InlineAsm>(unwrap(Asm)) : nullptr; | ||
| if (!A) | ||
| return {}; | ||
| // Borrow InlineAsm's storage with either the older std::string& API or the | ||
| // newer StringRef API. Copying a std::string here would return dangling data. | ||
| StringRef Text = A->getAsmString(); | ||
| StringRef Constraints = A->getConstraintString(); | ||
| return {wrap(A->getFunctionType()), | ||
| Text.data(), | ||
| Constraints.data(), | ||
| Text.size(), | ||
| Constraints.size(), | ||
| A->hasSideEffects(), | ||
| A->isAlignStack(), | ||
| A->canThrow(), | ||
| static_cast<LLVMInlineAsmDialect>(A->getDialect())}; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
| // See https://llvm.org/LICENSE.txt for license information. | ||
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
|
|
||
| package llvm | ||
|
|
||
| /* | ||
| #include "transforms.h" | ||
| #include <stdlib.h> | ||
| */ | ||
| import "C" | ||
| import "unsafe" | ||
|
|
||
| // CloneFunction copies a function into its module, including its attributes, | ||
| // blocks, instructions and debug information. Local references are remapped; | ||
| // references to other functions and globals remain unchanged. The caller can | ||
| // rename the returned function. The original function is not modified. | ||
| // It panics if v is nil or is not a function; declarations may be cloned. | ||
| func (v Value) CloneFunction() (clone Value) { | ||
| clone.C = C.LLVMGoCloneFunction(v.C) | ||
| if clone.IsNil() { | ||
| panic("llvm: CloneFunction requires a function") | ||
| } | ||
| return | ||
| } | ||
|
|
||
| // SimplifyInstructionsInBlock folds instructions using locally available facts. | ||
| // It returns whether the block changed and may erase instructions. | ||
| func (bb BasicBlock) SimplifyInstructionsInBlock() bool { | ||
| return C.LLVMGoSimplifyInstructionsInBlock(bb.C) != 0 | ||
| } | ||
|
|
||
| // ConstantFoldTerminator folds a constant branch or switch and updates successor | ||
| // PHIs. When deleteDead is true, it also removes dead condition instructions. | ||
| func (bb BasicBlock) ConstantFoldTerminator(deleteDead bool) bool { | ||
| return C.LLVMGoConstantFoldTerminator(bb.C, boolToLLVMBool(deleteDead)) != 0 | ||
| } | ||
|
|
||
| // RemoveUnreachableBlocks deletes blocks unreachable from the function entry | ||
| // and updates successor PHIs. It returns whether the function changed. | ||
| // It panics if v is nil or is not a function definition. | ||
| func (v Value) RemoveUnreachableBlocks() bool { | ||
| changed := C.LLVMGoRemoveUnreachableBlocks(v.C) | ||
| if changed < 0 { | ||
| panic("llvm: RemoveUnreachableBlocks requires a function definition") | ||
| } | ||
| return changed != 0 | ||
| } | ||
|
|
||
| // SetSubprogramLinkageName changes the linker name of a DISubprogram without | ||
| // changing its source-language display name. It panics if md is nil or is not | ||
| // a DISubprogram. | ||
| func (md Metadata) SetSubprogramLinkageName(name string) { | ||
| text := C.CString(name) | ||
| defer C.free(unsafe.Pointer(text)) | ||
| if C.LLVMGoSetSubprogramLinkageName(md.C, text, C.size_t(len(name))) == 0 { | ||
| panic("llvm: SetSubprogramLinkageName requires a DISubprogram") | ||
| } | ||
| } | ||
|
|
||
| // AsMetadata unwraps a MetadataAsValue, or wraps a constant, argument, or | ||
| // instruction as metadata using LLVMValueAsMetadata. | ||
| func (v Value) AsMetadata() (md Metadata) { | ||
| md.C = C.LLVMValueAsMetadata(v.C) | ||
| return | ||
| } | ||
|
|
||
| // TailCallKind distinguishes optional tail-call hints from mandatory tail calls. | ||
| type TailCallKind uint32 | ||
|
|
||
| const ( | ||
| // These values match llvm::CallInst::TailCallKind, checked in transforms.cpp. | ||
| TailCallKindNone TailCallKind = iota | ||
| TailCallKindTail | ||
| TailCallKindMustTail | ||
| TailCallKindNoTail | ||
| ) | ||
|
|
||
| // TailCallKind returns the tail-call kind of a call instruction. | ||
| // It panics if v is nil or is not a call instruction. | ||
| func (v Value) TailCallKind() TailCallKind { | ||
| kind := TailCallKind(C.LLVMGoGetTailCallKind(v.C)) | ||
| if kind > TailCallKindNoTail { | ||
| panic("llvm: TailCallKind requires a call instruction") | ||
| } | ||
| return kind | ||
| } | ||
|
|
||
| // SetTailCallKind sets the tail-call kind of a call instruction. The caller must | ||
| // satisfy LLVM's ABI and control-flow requirements for mandatory tail calls. | ||
| // It panics if v is nil, is not a call instruction, or kind is invalid. | ||
| func (v Value) SetTailCallKind(kind TailCallKind) { | ||
| if C.LLVMGoSetTailCallKind(v.C, C.unsigned(kind)) == 0 { | ||
| panic("llvm: SetTailCallKind requires a call instruction and a valid tail-call kind") | ||
| } | ||
| } | ||
|
|
||
| // InlineAsmInfo contains all properties needed to rebuild an inline assembly | ||
| // value while changing its text or constraints. | ||
| type InlineAsmInfo struct { | ||
| Type Type | ||
| Assembly, Constraints string | ||
| HasSideEffects, IsAlignStack, CanThrow bool | ||
| Dialect InlineAsmDialect | ||
| } | ||
|
|
||
| // InlineAsmInfo returns the properties of an inline assembly value. | ||
| // It panics if v is nil or is not an inline assembly value. | ||
| func (v Value) InlineAsmInfo() InlineAsmInfo { | ||
| a := C.LLVMGoGetInlineAsmInfo(v.C) | ||
| if a.Type == nil { | ||
| panic("llvm: InlineAsmInfo requires an inline assembly value") | ||
| } | ||
| return InlineAsmInfo{ | ||
| Type: Type{C: a.Type}, | ||
| Assembly: C.GoStringN(a.Assembly, C.int(a.AssemblyLen)), | ||
| Constraints: C.GoStringN(a.Constraints, C.int(a.ConstraintsLen)), | ||
| HasSideEffects: a.SideEffects != 0, | ||
| IsAlignStack: a.AlignStack != 0, | ||
| CanThrow: a.CanThrow != 0, | ||
| Dialect: InlineAsmDialect(a.Dialect), | ||
| } | ||
| } | ||
|
|
||
| // NamedValue looks up a symbol of any global kind, including functions, global | ||
| // variables, aliases and indirect functions. It returns a nil Value if absent. | ||
| func (m Module) NamedValue(name string) (value Value) { | ||
| text := C.CString(name) | ||
| defer C.free(unsafe.Pointer(text)) | ||
| value.C = C.LLVMGoGetNamedValue(m.C, text, C.size_t(len(name))) | ||
| return | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
| // See https://llvm.org/LICENSE.txt for license information. | ||
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
|
|
||
| // Generic IR transformation utilities missing from llvm-c. | ||
| #ifndef LLVM_BINDINGS_GO_TRANSFORMS_H | ||
| #define LLVM_BINDINGS_GO_TRANSFORMS_H | ||
| #include "llvm-c/Core.h" | ||
| #ifdef __cplusplus | ||
| extern "C" { | ||
| #endif | ||
| LLVMValueRef LLVMGoGetNamedValue(LLVMModuleRef M, const char *Name, size_t Len); | ||
| // Invalid inputs are reported to the Go layer, which raises a Go panic. | ||
| LLVMValueRef LLVMGoCloneFunction(LLVMValueRef Fn); // null on invalid input | ||
| LLVMBool LLVMGoSimplifyInstructionsInBlock(LLVMBasicBlockRef BB); | ||
| LLVMBool LLVMGoConstantFoldTerminator(LLVMBasicBlockRef BB, | ||
| LLVMBool DeleteDead); | ||
| // Returns -1 on invalid input, otherwise whether the function changed. | ||
| int LLVMGoRemoveUnreachableBlocks(LLVMValueRef Fn); | ||
| LLVMBool LLVMGoSetSubprogramLinkageName(LLVMMetadataRef SP, const char *Name, | ||
| size_t Len); | ||
| LLVMBool LLVMGoSetTailCallKind(LLVMValueRef Call, unsigned Kind); | ||
| // Returns ~0u on invalid input. | ||
| unsigned LLVMGoGetTailCallKind(LLVMValueRef Call); | ||
| struct LLVMGoInlineAsmInfo { | ||
| LLVMTypeRef Type; | ||
| const char *Assembly, *Constraints; | ||
| size_t AssemblyLen, ConstraintsLen; | ||
| LLVMBool SideEffects, AlignStack, CanThrow; | ||
| LLVMInlineAsmDialect Dialect; | ||
| }; | ||
| struct LLVMGoInlineAsmInfo LLVMGoGetInlineAsmInfo(LLVMValueRef Asm); | ||
| #ifdef __cplusplus | ||
| } | ||
| #endif | ||
| #endif |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.