如何判断在GHC中是否发生共同的子表达式消除? [英] How to tell that common subexpression elimination is happening or not in GHC?

查看:166
本文介绍了如何判断在GHC中是否发生共同的子表达式消除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  quadratic abc =(ans1,ans2)
其中
ans1 =(( - b)+ sqrt(b * b - 4 * a * c))/(2 * a)
ans2 =(( - b) - sqrt(b * b - 4 * a * c))/(2 * a)

有多个相同的子表达式。如何在不读取核心的情况下知道是否发生了常见的子表达式消除以及这种情况的哪些部分? 使用 trace 可能会告诉你如

  import Debug.Trace 

二次函数abc =(ans1,ans2)
其中
ans1 =(( - b)+ tr1(sqrt(b * b - 4 * a * c)))/(2 * a)
2 =(( - b) - tr2(sqrt(b * b-4 * a * c)))/(2 * a)
tr1 = traceans1
tr2 = traceans2

main = print $ quadratic 1 10 3

-O2 -O3 显示 ans1 和<$ c跟踪输出中的$ c> ans2 指示GHC未执行CSE。如果您在两个地方都使用 tr1 ,您会得到相似的
结果。


$ b Haskell Wiki提到GHC只在有限的
情况下执行CSE -
(链接) - 并建议您如果你想确保它发生,你可以自己执行


Let's say I have a naively implemented function like this:

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + sqrt (b * b - 4 * a * c)) / (2 * a)
    ans2 = ((-b) - sqrt (b * b - 4 * a * c)) / (2 * a)

There are multiple identical subexpressions. How can I tell without reading core that common subexpression elimination is happening or not and to which parts of this?

解决方案

Using trace might tell you as demonstrated in this SO question.

import Debug.Trace

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + tr1 (sqrt (b * b - 4 * a * c))) / (2 * a)
    ans2 = ((-b) - tr2 (sqrt (b * b - 4 * a * c))) / (2 * a)
    tr1 = trace "ans1"
    tr2 = trace "ans2"

main = print $ quadratic 1 10 3

Compiling this with -O2 or -O3 shows both ans1 and ans2 in the trace output indicating that GHC did not perform the CSE. You get similar results if you use tr1 in both places.

The Haskell Wiki mentions that GHC only performs CSE in limited circumstances - (link) - and that you are advised to perform it yourself if you want to make sure it happens.

这篇关于如何判断在GHC中是否发生共同的子表达式消除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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