如何防止gcc优化C中的某些语句? [英] How to prevent gcc optimizing some statements in C?

查看:35
本文介绍了如何防止gcc优化C中的某些语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使页面变脏(打开页表条目中的脏位),我像这样触摸页面的第一个字节:

pageptr[0] = pageptr[0];

但实际上 gcc 会通过死存储消除来忽略该语句.为了防止gcc优化,我把语句改写如下:

volatile int tmp;tmp = pageptr[0];pageptr[0] = tmp;

看起来这个技巧有效,但有点难看.我想知道是否有任何指令或语法具有相同的效果?而且我不想使用 -O0 标志,因为它也会带来很大的性能损失.

解决方案

关闭优化可以解决问题,但没有必要.一个更安全的替代方法是使用 volatile 类型限定符使编译器优化存储是非法的.

//假设 pageptr 已经是 unsigned char * ...无符号字符 *pageptr = ...;((unsigned char volatile *)pageptr)[0] = pageptr[0];

volatile 类型限定符指示编译器严格执行内存存储和加载.volatile 的目的之一是让编译器知道内存访问有副作用,因此必须保留.在这种情况下,存储具有导致页面错误的副作用,并且您希望编译器保留页面错误.

这样,周围的代码仍然可以优化,并且您的代码可以移植到其他不理解 GCC 的#pragma__attribute__ 语法的编译器.>

In order to make a page dirty (switching on the dirty bit in the page table entry), I touch the first bytes of the page like this:

pageptr[0] = pageptr[0];

But in practice gcc will ignore the statement by dead store elimination. In order to prevent gcc optimizing it, I re-write the statement as follows:

volatile int tmp;
tmp = pageptr[0];
pageptr[0] = tmp;

It seems the trick works, but somewhat ugly. I would like to know is there any directives or syntax which has the same effect? And I don't want to use a -O0 flag, since it will bring great performance penalty as well.

解决方案

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

这篇关于如何防止gcc优化C中的某些语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆