【问题标题】:Pass structure by parameter with LLVM使用 LLVM 通过参数传递结构
【发布时间】:2012-09-27 04:16:46
【问题描述】:

是否可以通过参数传递结构?

它与 C abi 兼容吗?

[编辑]

基本上,我想要一个包含两个成员的 C++ POD(结构将是一个胖指针,带有一个指针和一个整数),并且能够在调用指令中将此结构作为函数参数传递(甚至调用 C 代码时)。

我现在不使用胖指针(指针和整数都在不同的函数参数中),我想知道在开始一个相当大的重构之前是否有可能!

【问题讨论】:

  • 请详细说明。你试过什么?你能包含一些代码吗?
  • @SimonGermain 我添加了一些关于我的用例的上下文。暂时没有代码。

标签: c llvm


【解决方案1】:

你可以这样做。

您可以通过将 C 代码复制并粘贴到位于 http://llvm.org/demo/index.cgi 的 LLVM 在线演示中来了解示例 C 的 LLVM 代码。

如果您复制并粘贴 codepad.org 中的代码,您会看到 LLVM 为 myFunction 生成以下内容:

define void @_Z10myFunction10MyStruct_t(i8* %myStructAsParam.coerce0, i32     %myStructAsParam.coerce1) nounwind uwtable {
  %1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([23 x i8]* @.str, i64 0, i64 0), i8* %myStructAsParam.coerce0, i32 %myStructAsParam.coerce1)
  ret void
}

当然,如果您查看通话内容,您会注意到没有进行任何复制。这取决于调用函数。如果我们写一个小的 C 函数:

void myCallingFunction(MyStruct_t *foobar)
{
  myFunction(*foobar);
}

我们可以看到为myCallingFunction生成的LLVM bitcode是:

define void @_Z17myCallingFunctionP10MyStruct_t(%struct.MyStruct_t* nocapture %foobar)   nounwind uwtable {
  %foobar.0 = getelementptr inbounds %struct.MyStruct_t* %foobar, i64 0, i32 0
  %tmp = load i8** %foobar.0, align 8
  %foobar.1 = getelementptr inbounds %struct.MyStruct_t* %foobar, i64 0, i32 1
  %tmp1 = load i32* %foobar.1, align 8
  %1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([23 x i8]* @.str, i64 0, i64 0), i8* %tmp, i32 %tmp1) nounwind
  ret void
}

调用函数复制结构体,然后传入副本的地址。

【讨论】:

    【解决方案2】:

    当然可以。这是一个例子:

    struct MyStruct_t {
        char *charPointer;
        int number;
    };
    
    void myFunction(MyStruct_t myStructAsParam) {
    
        printf("String: %s, Number: %i", myStructAsParam.charPointer, myStructAsParam.number);
        // Your stuff here.
    }
    

    【讨论】:

    • 您的 myStructAsParam 是一个指针,但您使用的是 '.'操作员,什么是正确的?需要明确的是,我正在寻找将 myStructAsParam 作为值而不是指针 (codepad.org/H4Az2uKK) 传递。
    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多