[英]Why doesn't GCC optimize away memory writes in this summation loop?
Given the following C code, why does GCC (version 10.1, x86-64, -O3) write to memory inside the loop instead of just using two registers during summation and writing the result to memory only at the end?
void sum(unsigned int l, int *as, int *r) {
r[0] = 0;
r[1] = 0;
for (int i = 0; i < l; i++) {
r[0] += as[2 * i];
r[1] += as[2 * i + 1];
}
}
在此處生成說明。
我的猜測是,這種行為與“考慮到”並發性的 GCC 有關。 您可以有另一個線程,例如在執行求和時從同一地址的 memory 讀取。
這是真正的(也是唯一的)原因嗎? 它甚至可能由 C 標准定義嗎?
編譯器不知道as
和r
是否指向同一個數組,所以不知道r[0] += as[2 * i];
不改變as[2 * i + 1]
的值,這是r[1] += as[2 * i + 1];
,對於r[0]
、 r[1]
和as
的各種元素之間的其他交互也是類似的。
您可以通過將 function 聲明更改為void sum(unsigned int l, int * restrict as, int * restrict r)
來告訴編譯器通過as
和r
引用的元素不重疊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.