gpt4 book ai didi

c++ - 用于 gcc 或 clang 的 LTO 是否可以跨 C 和 C++ 方法进行优化

转载 作者:可可西里 更新时间:2023-11-01 17:39:57 25 4
gpt4 key购买 nike

如果链接时优化 (LTO) 与 gcc 一起使用或 clang , 是否可以跨 C 和 C++ 语言边界优化代码?

例如,C 函数是否可以内联到 C++ 调用程序中?

最佳答案

是的!

链接时优化通常适用于“胖”目标文件中存在的中间表示 (IR),它可以包含用于传统链接的机器代码和用于 LTO 链接的 IR。

在此阶段,不再有高级语言结构,因此链接时优化与语言无关。


海合会

海湾合作委员会的 link-time optimization (LTO) 在 GIMPLE 上工作,GIMPLE 是 GCC 的中间表示之一。 IR 始终与语言无关,因此任何链接时优化都适用于从任何语言生成的代码。

来自GCC Optimization Options文档:

Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:

gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran

Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation.


这里有一个示例可以向您展示这项技术的强大之处。我们将定义一个 C 函数并从 C++ 程序中调用它:

func.h

#ifndef FUNC_DOT_H
#define FUNC_DOT_H

#ifdef __cplusplus
extern "C" {
#endif

int func(int a, int b, int c);

#ifdef __cplusplus
}
#endif

#endif /* FUNC_DOT_H */

func.c

#include "func.h"

int func(int a, int b, int c)
{
return 3*a + 2*b + c;
}

main.cpp

#include "func.h"

int main()
{
int a = 1;
int b = 2;
int c = 3;

return func(a, b, c);
}

编译

gcc -o func.o -c -Wall -Werror -flto -O2 func.c
g++ -o main.o -c -Wall -Werror -flto -O2 main.cpp
g++ -o testlto -flto -O2 main.o func.o

反汇编(objdump -Mintel -d -R -C teSTLto)

Disassembly of section .text:

00000000004003d0 <main>:
4003d0: b8 0a 00 00 00 mov eax,0xa ; 1*3 + 2*2 + 3 = 10
4003d5: c3 ret

您可以看到,它不仅将我的 C func() 内联到我的 C++ main() 中,而且还将整个事情变成了一个常量表达式!


clang /LLVM

使用相同的语法,Clang 能够使用 LLVM IR 发出“胖”目标文件,这可以在链接时进行优化。参见 LLVM Link Time Optimization .

使用与上面相同的测试代码,clang 产生完全相同的结果:

00000000004004b0 <main>:
4004b0: b8 0a 00 00 00 mov eax,0xa
4004b5: c3 ret

关于c++ - 用于 gcc 或 clang 的 LTO 是否可以跨 C 和 C++ 方法进行优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com