Skip to content

Commit 8082906

Browse files
committed
Fixed small issue with constant propagation
Constants directly assigned to other constants were not propagating: For instance, in local <const> k1 = 10 local <const> k2 = k1 'k2' were not treated as a compile-time constant.
1 parent d6af810 commit 8082906

2 files changed

Lines changed: 21 additions & 7 deletions

File tree

lcode.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ static int tonumeral (const expdesc *e, TValue *v) {
6767
}
6868

6969

70+
/*
71+
** Get the constant value from a constant expression
72+
*/
73+
static TValue *const2val (FuncState *fs, const expdesc *e) {
74+
lua_assert(e->k == VCONST);
75+
return &fs->ls->dyd->actvar.arr[e->u.info].k;
76+
}
77+
78+
7079
/*
7180
** If expression is a constant, fills 'v' with its value
7281
** and returns 1. Otherwise, returns 0.
@@ -85,6 +94,10 @@ int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {
8594
setsvalue(fs->ls->L, v, e->u.strval);
8695
return 1;
8796
}
97+
case VCONST: {
98+
setobj(fs->ls->L, v, const2val(fs, e));
99+
return 1;
100+
}
88101
default: return tonumeral(e, v);
89102
}
90103
}
@@ -730,14 +743,13 @@ void luaK_setoneret (FuncState *fs, expdesc *e) {
730743

731744

732745
/*
733-
** Ensure that expression 'e' is not a variable.
746+
** Ensure that expression 'e' is not a variable (nor a constant).
734747
** (Expression still may have jump lists.)
735748
*/
736749
void luaK_dischargevars (FuncState *fs, expdesc *e) {
737750
switch (e->k) {
738751
case VCONST: {
739-
TValue *val = &fs->ls->dyd->actvar.arr[e->u.info].k;
740-
const2exp(val, e);
752+
const2exp(const2val(fs, e), e);
741753
break;
742754
}
743755
case VLOCAL: { /* already in a register */

testes/code.lua

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ end
88
print "testing code generation and optimizations"
99

1010
-- to test constant propagation
11-
local <const> k0 = 0
11+
local <const> k0aux = 0
12+
local <const> k0 = k0aux
1213
local <const> k1 = 1
1314
local <const> k3 = 3
1415
local <const> k6 = k3 + (k3 << k0)
@@ -410,17 +411,18 @@ checkequal(function () return 6 and true or nil end,
410411

411412

412413
do -- string constants
414+
local <const> k0 = "00000000000000000000000000000000000000000000000000"
413415
local function f1 ()
414-
local <const> k = "00000000000000000000000000000000000000000000000000"
416+
local <const> k = k0
415417
return function ()
416418
return function () return k end
417419
end
418420
end
419421

420422
local f2 = f1()
421423
local f3 = f2()
422-
assert(f3() == string.rep("0", 50))
423-
checkK(f3, f3())
424+
assert(f3() == k0)
425+
checkK(f3, k0)
424426
-- string is not needed by other functions
425427
assert(T.listk(f1)[1] == nil)
426428
assert(T.listk(f2)[1] == nil)

0 commit comments

Comments
 (0)