循環不變代碼外提

維基百科,自由的百科全書

循環不變代碼外提(英語:loop-invariant code motion,縮寫LICM)在計算機編程中是指將循環不變的語句或表達式移到循環體之外,而不改變程序的語義。循環不變代碼外提在英文中又被稱為hoistingscalar promotion,是編譯器中常見的優化方法。

示例[編輯]

假設有如下代碼:

for (int i = 0; i < n; i++) {
    x = y + z;
    a[i] = 6 * i + x * x;
}

其中x = y + zx * x這兩步運算是循環不變的,會在優化中被移出循環體之外。經LICM優化後的代碼為:

x = y + z;
t1 = x * x;
for (int i = 0; i < n; i++) {
    a[i] = 6 * i + t1;
}

參見[編輯]

參考文獻[編輯]

  • Aho, Alfred V.; Sethi, Ravi; & Ullman, Jeffrey D. (1986). Compilers: Principles, Techniques, and Tools. Addison Wesley. ISBN 0-201-10088-6.
  • Compiler Optimizations — Hoisting