GCC Return optimiztion

六月ゝ 毕业季﹏ 提交于 2019-12-19 09:54:17

问题


I'd like to know if GCC can optimize code like

int foo(args) {
    if(is_true) {
        do_smth;
        n = call_func(args);
        do_smth;
        return n;
    }
    else {
        return call_func(args);
    }
}

so that if i'm in else branch call_func's call would be executed like there was no foo call? I'm writing kernel module, and for solving one particular issue I need it to look like this call_func was called directly. To be more specific call_func is some system call. Foo is my version of this system call. In is_true case I should do smth, call this system call and then return its return. But in !is_true I'd like to somehow change the call stack itself - so that on current level there was call_func instead of foo. Is it even possible?

Implementation of is_true:

struct task_struct * cur_task = current;
if(check_dir(cur_task)) {
...
}

check_dir is function to check if we want to do something with directory, from which system call was called.


回答1:


This is called tail-call optimization (it is not specified in any C standard; in contrast, some languages -e.g. Scheme and Ocaml- specify that tail-call optimization is required to happen). In some cases, recent GCC compilers can do that optimization.

But it really depends upon the details, in particular of the actual arguments passed to call_func

If you depend on it, please comment your code and check with gcc -fverbose-asm -O2 -S that your compiler is doing that.

Notice that this optimization is not required, and might be compiler, compilation flags, processor and ABI specific.

(so it could work on x86-64 but not on 32 bits ia32 or ARM; you really should check!)



来源:https://stackoverflow.com/questions/26775257/gcc-return-optimiztion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!