Skip to content

Commit aa16c22

Browse files
committed
[LLVM-C] Upstream LLVMGetOrInsertFunction from rustc
1 parent fee71a3 commit aa16c22

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

llvm/include/llvm-c/Core.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2988,6 +2988,22 @@ LLVM_C_ABI char *LLVMIntrinsicCopyOverloadedName2(LLVMModuleRef Mod,
29882988
*/
29892989
LLVM_C_ABI LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID);
29902990

2991+
/**
2992+
* Obtain or insert a function into a module.
2993+
*
2994+
* If a function with the specified name already exists in the module, it
2995+
* is returned. Otherwise, a new function is created in the module with the
2996+
* specified name and type and is returned.
2997+
*
2998+
* The returned value corresponds to a llvm::Function instance.
2999+
*
3000+
* @see llvm::Module::getOrInsertFunction()
3001+
*/
3002+
LLVM_C_ABI LLVMValueRef LLVMGetOrInsertFunction(LLVMModuleRef M,
3003+
const char *Name,
3004+
size_t NameLen,
3005+
LLVMTypeRef FunctionTy);
3006+
29913007
/**
29923008
* Obtain the calling function of a function.
29933009
*

llvm/lib/IR/Core.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2523,6 +2523,14 @@ LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID) {
25232523
return llvm::Intrinsic::isOverloaded(IID);
25242524
}
25252525

2526+
LLVMValueRef LLVMGetOrInsertFunction(LLVMModuleRef M, const char *Name,
2527+
size_t NameLen, LLVMTypeRef FunctionTy) {
2528+
return wrap(unwrap(M)
2529+
->getOrInsertFunction(StringRef(Name, NameLen),
2530+
unwrap<FunctionType>(FunctionTy))
2531+
.getCallee());
2532+
}
2533+
25262534
unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {
25272535
return unwrap<Function>(Fn)->getCallingConv();
25282536
}

llvm/unittests/IR/FunctionTest.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,4 +625,23 @@ TEST(FunctionTest, Personality) {
625625
EXPECT_FALSE(LLVMHasPersonalityFn(wrap(F)));
626626
}
627627

628+
TEST(FunctionTest, LLVMGetOrInsertFunction) {
629+
LLVMContext Ctx;
630+
Module M("test", Ctx);
631+
Type *Int8Ty = Type::getInt8Ty(Ctx);
632+
FunctionType *FTy = FunctionType::get(Int8Ty, false);
633+
634+
// Create the function using the C API
635+
LLVMValueRef FuncRef = LLVMGetOrInsertFunction(wrap(&M), "F", 1, wrap(FTy));
636+
637+
// Verify that the returned value is a function and has the correct type
638+
Function *Func = unwrap<Function>(FuncRef);
639+
EXPECT_EQ(Func->getName(), "F");
640+
EXPECT_EQ(Func->getFunctionType(), FTy);
641+
642+
// Call LLVMGetOrInsertFunction again to ensure it returns the same function
643+
LLVMValueRef FuncRef2 = LLVMGetOrInsertFunction(wrap(&M), "F", 1, wrap(FTy));
644+
EXPECT_EQ(FuncRef, FuncRef2);
645+
}
646+
628647
} // end namespace

0 commit comments

Comments
 (0)