【问题标题】:MSVC and optimizing out constant expressionsMSVC 和优化常量表达式
【发布时间】:2014-01-12 10:19:19
【问题描述】:

我正在处理的项目是用 C 语言编写的,并使用预处理器宏来处理错误。

宏看起来像:

#define logevent(level, msg) \
    do {
        int _level = level; \
        somefunction(_level, msg); \
        someotherfunction(_level, msg); \
        if (_level >= ERROR) \
          __assume(0); \
    } while(0)

假设如果级别 >= ERROR,某个其他函数确实退出(1),并且当我们调用 logevent(ERROR, "something"); 时我们从未达到 if 条件;其中 ERROR 是一个已定义的常量。 问题是 MSVC 似乎无法优化 if 条件,因为 if 条件基于 _level 变量而不是 level 常量。需要 _level 变量来停止对级别表达式的多次评估。

某些其他编译器似乎能够优化掉 if 条件,但我想知道这是否是 MSVC 编译器的限制,或者我可以启用一些东西来让编译器优化这些 if 条件吗?

【问题讨论】:

  • 什么是__assume()

标签: c compiler-construction compiler-optimization


【解决方案1】:

MSVC 2013 将优化我们的表达方式。以下输入

#define ERROR 1

void somefunction(int level, char const* msg) {
  printf("FUNC1 %d: %s\n", level, msg);
}

void someotherfunction(int level, char const* msg) {
  printf("FUNC2 %d: %s\n", level, msg);

  if (level >= ERROR) {
    exit(1);
  }
}

#define logevent(level, msg) \
  do { \
    int _level = level; \
    somefunction(_level, msg); \
    someotherfunction(_level, msg); \
    if (_level >= ERROR) \
      __assume(0); \
    } while (0)

int _tmain(int argc, _TCHAR* argv[])
{
  logevent(ERROR, "HALLO");
  printf("Hallo\n");
  getchar();
  return 0;
}

将编译为

00CB1000  push        0CB2120h  
00CB1005  push        1  
00CB1007  push        0CB2100h  
00CB100C  call        dword ptr ds:[0CB2090h]  
00CB1012  push        0CB2120h  
00CB1017  push        1  
00CB1019  push        0CB2110h  
00CB101E  call        dword ptr ds:[0CB2090h]  
00CB1024  add         esp,18h  
00CB1027  push        1  
00CB1029  call        dword ptr ds:[0CB208Ch] 

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多