summary refs log tree commit diff stats
path: root/tests/template/t_otemplates.nim
blob: 8d2ac38a6ceedf8a1311e7a7de930182bf658d31 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
discard """
  output: "Success"
"""

# Ref:
# http://nim-lang.org/macros.html
# http://nim-lang.org/parseutils.html


# Imports
import tables, parseutils, macros, strutils
import annotate
export annotate


# Fields
const identChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}


# Procedure Declarations
proc parse_template(node: NimNode, value: string) {.compiletime.}


# Procedure Definitions
proc substring(value: string, index: int, length = -1): string {.compiletime.} =
    ## Returns a string at most `length` characters long, starting at `index`.
    return if length < 0:    value.substr(index)
           elif length == 0: ""
           else:             value.substr(index, index + length-1)


proc parse_thru_eol(value: string, index: int): int {.compiletime.} =
    ## Reads until and past the end of the current line, unless
    ## a non-whitespace character is encountered first
    var remainder: string
    var read = value.parseUntil(remainder, {0x0A.char}, index)
    if remainder.skipWhitespace() == read:
        return read + 1


proc trim_after_eol(value: var string) {.compiletime.} =
    ## Trims any whitespace at end after \n
    var toTrim = 0
    for i in countdown(value.len-1, 0):
        # If \n, return
        if value[i] in [' ', '\t']: inc(toTrim)
        else: break

    if toTrim > 0:
        value = value.substring(0, value.len - toTrim)


proc trim_eol(value: var string) {.compiletime.} =
    ## Removes everything after the last line if it contains nothing but whitespace
    for i in countdown(value.len - 1, 0):
        # If \n, trim and return
        if value[i] == 0x0A.char:
            value = value.substr(0, i)
            break

        # This is the first character
        if i == 0:
            value = ""
            break

        # Skip change
        if not (value[i] in [' ', '\t']): break


proc detect_indent(value: string, index: int): int {.compiletime.} =
    ## Detects how indented the line at `index` is.
    # Seek to the beginning of the line.
    var lastChar = index
    for i in countdown(index, 0):
        if value[i] == 0x0A.char:
            # if \n, return the indentation level
            return lastChar - i
        elif not (value[i] in [' ', '\t']):
            # if non-whitespace char, decrement lastChar
            dec(lastChar)


proc parse_thru_string(value: string, i: var int, strType = '"') {.compiletime.} =
    ## Parses until ending " or ' is reached.
    inc(i)
    if i < value.len-1:
        inc(i, value.skipUntil({'\\', strType}, i))


proc parse_to_close(value: string, index: int, open='(', close=')', opened=0): int {.compiletime.} =
    ## Reads until all opened braces are closed
    ## ignoring any strings "" or ''
    var remainder   = value.substring(index)
    var open_braces = opened
    result = 0

    while result < remainder.len:
        var c = remainder[result]

        if   c == open:  inc(open_braces)
        elif c == close: dec(open_braces)
        elif c == '"':   remainder.parse_thru_string(result)
        elif c == '\'':  remainder.parse_thru_string(result, '\'')

        if open_braces == 0: break
        else: inc(result)


iterator parse_stmt_list(value: string, index: var int): string =
    ## Parses unguided ${..} block
    var read        = value.parse_to_close(index, open='{', close='}')
    var expressions = value.substring(index + 1, read - 1).split({ ';', 0x0A.char })

    for expression in expressions:
        let value = expression.strip
        if value.len > 0:
            yield value

    #Increment index & parse thru EOL
    inc(index, read + 1)
    inc(index, value.parse_thru_eol(index))


iterator parse_compound_statements(value, identifier: string, index: int): string =
    ## Parses through several statements, i.e. if {} elif {} else {}
    ## and returns the initialization of each as an empty statement
    ## i.e. if x == 5 { ... } becomes if x == 5: nil.

    template get_next_ident(expected) =
        var nextIdent: string
        discard value.parseWhile(nextIdent, {'$'} + identChars, i)

        var next: string
        var read: int

        if nextIdent == "case":
            # We have to handle case a bit differently
            read = value.parseUntil(next, '$', i)
            inc(i, read)
            yield next.strip(leading=false) & "\n"

        else:
            read = value.parseUntil(next, '{', i)

            if nextIdent in expected:
                inc(i, read)
                # Parse until closing }, then skip whitespace afterwards
                read = value.parse_to_close(i, open='{', close='}')
                inc(i, read + 1)
                inc(i, value.skipWhitespace(i))
                yield next & ": nil\n"

            else: break


    var i = index
    while true:
        # Check if next statement would be valid, given the identifier
        if identifier in ["if", "when"]:
            get_next_ident([identifier, "$elif", "$else"])

        elif identifier == "case":
            get_next_ident(["case", "$of", "$elif", "$else"])

        elif identifier == "try":
            get_next_ident(["try", "$except", "$finally"])


proc parse_complex_stmt(value, identifier: string, index: var int): NimNode {.compiletime.} =
    ## Parses if/when/try /elif /else /except /finally statements

    # Build up complex statement string
    var stmtString = newString(0)
    var numStatements = 0
    for statement in value.parse_compound_statements(identifier, index):
        if statement[0] == '$': stmtString.add(statement.substr(1))
        else:                   stmtString.add(statement)
        inc(numStatements)

    # Parse stmt string
    result = parseExpr(stmtString)

    var resultIndex = 0

    # Fast forward a bit if this is a case statement
    if identifier == "case":
        inc(resultIndex)

    while resultIndex < numStatements:

        # Detect indentation
        let indent = detect_indent(value, index)

        # Parse until an open brace `{`
        var read = value.skipUntil('{', index)
        inc(index, read + 1)

        # Parse through EOL
        inc(index, value.parse_thru_eol(index))

        # Parse through { .. }
        read = value.parse_to_close(index, open='{', close='}', opened=1)

        # Add parsed sub-expression into body
        var body       = newStmtList()
        var stmtString = value.substring(index, read)
        trim_after_eol(stmtString)
        stmtString = reindent(stmtString, indent)
        parse_template(body, stmtString)
        inc(index, read + 1)

        # Insert body into result
        var stmtIndex = result[resultIndex].len-1
        result[resultIndex][stmtIndex] = body

        # Parse through EOL again & increment result index
        inc(index, value.parse_thru_eol(index))
        inc(resultIndex)


proc parse_simple_statement(value: string, index: var int): NimNode {.compiletime.} =
    ## Parses for/while

    # Detect indentation
    let indent = detect_indent(value, index)

    # Parse until an open brace `{`
    var splitValue: string
    var read = value.parseUntil(splitValue, '{', index)
    result   = parseExpr(splitValue & ":nil")
    inc(index, read + 1)

    # Parse through EOL
    inc(index, value.parse_thru_eol(index))

    # Parse through { .. }
    read = value.parse_to_close(index, open='{', close='}', opened=1)

    # Add parsed sub-expression into body
    var body       = newStmtList()
    var stmtString = value.substring(index, read)
    trim_after_eol(stmtString)
    stmtString = reindent(stmtString, indent)
    parse_template(body, stmtString)
    inc(index, read + 1)

    # Insert body into result
    var stmtIndex = result.len-1
    result[stmtIndex] = body

    # Parse through EOL again
    inc(index, value.parse_thru_eol(index))


proc parse_until_symbol(node: NimNode, value: string, index: var int): bool {.compiletime.} =
    ## Parses a string until a $ symbol is encountered, if
    ## two $$'s are encountered in a row, a split will happen
    ## removing one of the $'s from the resulting output
    var splitValue: string
    var read = value.parseUntil(splitValue, '$', index)
    var insertionPoint = node.len

    inc(index, read + 1)
    if index < value.len:

        case value[index]
        of '$':
            # Check for duplicate `$`, meaning this is an escaped $
            node.add newCall("add", ident("result"), newStrLitNode("$"))
            inc(index)

        of '(':
            # Check for open `(`, which means parse as simple single-line expression.
            trim_eol(splitValue)
            read = value.parse_to_close(index) + 1
            node.add newCall("add", ident("result"),
                newCall(bindSym"strip", parseExpr("$" & value.substring(index, read)))
            )
            inc(index, read)

        of '{':
            # Check for open `{`, which means open statement list
            trim_eol(splitValue)
            for s in value.parse_stmt_list(index):
                node.add parseExpr(s)

        else:
            # Otherwise parse while valid `identChars` and make expression w/ $
            var identifier: string
            read = value.parseWhile(identifier, identChars, index)

            if identifier in ["for", "while"]:
                ## for/while means open simple statement
                trim_eol(splitValue)
                node.add value.parse_simple_statement(index)

            elif identifier in ["if", "when", "case", "try"]:
                ## if/when/case/try means complex statement
                trim_eol(splitValue)
                node.add value.parse_complex_stmt(identifier, index)

            elif identifier.len > 0:
                ## Treat as simple variable
                node.add newCall("add", ident("result"), newCall("$", ident(identifier)))
                inc(index, read)

        result = true

    # Insert
    if splitValue.len > 0:
        node.insert insertionPoint, newCall("add", ident("result"), newStrLitNode(splitValue))


proc parse_template(node: NimNode, value: string) =
    ## Parses through entire template, outputing valid
    ## Nim code into the input `node` AST.
    var index = 0
    while index < value.len and
          parse_until_symbol(node, value, index): discard


macro tmpli*(body: untyped): untyped =
    result = newStmtList()

    result.add parseExpr("result = \"\"")

    var value = if body.kind in nnkStrLit..nnkTripleStrLit: body.strVal
                else: body[1].strVal

    parse_template(result, reindent(value))


macro tmpl*(body: untyped): untyped =
    result = newStmtList()

    var value = if body.kind in nnkStrLit..nnkTripleStrLit: body.strVal
                else: body[1].strVal

    parse_template(result, reindent(value))


# Run tests
when true:
    include otests
    echo "Success"
lass="k">else if (bt == VT_LDOUBLE) { o(0xc0d9); /* fld %st(0) */ o(0xdb); /* fstpt */ r = 7; } else { if (bt == VT_SHORT) o(0x66); if (bt == VT_BYTE || bt == VT_BOOL) o(0x88); else o(0x89); } if (fr == VT_CONST || fr == VT_LOCAL || (v->r & VT_LVAL)) { gen_modrm(r, v->r, v->sym, fc); } else if (fr != r) { o(0xc0 + fr + r * 8); /* mov r, fr */ } } static void gadd_sp(int val) { if (val == (char)val) { o(0xc483); g(val); } else { oad(0xc481, val); /* add $xxx, %esp */ } } /* 'is_jmp' is '1' if it is a jump */ static void gcall_or_jmp(int is_jmp) { int r; if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) { /* constant case */ if (vtop->r & VT_SYM) { /* relocation case */ greloc(cur_text_section, vtop->sym, ind + 1, R_386_PC32); } else { /* put an empty PC32 relocation */ put_elf_reloc(symtab_section, cur_text_section, ind + 1, R_386_PC32, 0); } oad(0xe8 + is_jmp, vtop->c.ul - 4); /* call/jmp im */ } else { /* otherwise, indirect call */ r = gv(RC_INT); o(0xff); /* call/jmp *r */ o(0xd0 + r + (is_jmp << 4)); } } static uint8_t fastcall_regs[3] = { TREG_EAX, TREG_EDX, TREG_ECX }; static uint8_t fastcallw_regs[2] = { TREG_ECX, TREG_EDX }; /* Generate function call. The function address is pushed first, then all the parameters in call order. This functions pops all the parameters and the function address. */ void gfunc_call(int nb_args) { int size, align, r, args_size, i, func_call; Sym *func_sym; args_size = 0; for(i = 0;i < nb_args; i++) { if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) { size = type_size(&vtop->type, &align); /* align to stack align size */ size = (size + 3) & ~3; /* allocate the necessary size on stack */ oad(0xec81, size); /* sub $xxx, %esp */ /* generate structure store */ r = get_reg(RC_INT); o(0x89); /* mov %esp, r */ o(0xe0 + r); vset(&vtop->type, r | VT_LVAL, 0); vswap(); vstore(); args_size += size; } else if (is_float(vtop->type.t)) { gv(RC_FLOAT); /* only one float register */ if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) size = 4; else if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) size = 8; else size = 12; oad(0xec81, size); /* sub $xxx, %esp */ if (size == 12) o(0x7cdb); else o(0x5cd9 + size - 4); /* fstp[s|l] 0(%esp) */ g(0x24); g(0x00); args_size += size; } else { /* simple type (currently always same size) */ /* XXX: implicit cast ? */ r = gv(RC_INT); if ((vtop->type.t & VT_BTYPE) == VT_LLONG) { size = 8; o(0x50 + vtop->r2); /* push r */ } else { size = 4; } o(0x50 + r); /* push r */ args_size += size; } vtop--; } save_regs(0); /* save used temporary registers */ func_sym = vtop->type.ref; func_call = FUNC_CALL(func_sym->r); /* fast call case */ if ((func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) || func_call == FUNC_FASTCALLW) { int fastcall_nb_regs; uint8_t *fastcall_regs_ptr; if (func_call == FUNC_FASTCALLW) { fastcall_regs_ptr = fastcallw_regs; fastcall_nb_regs = 2; } else { fastcall_regs_ptr = fastcall_regs; fastcall_nb_regs = func_call - FUNC_FASTCALL1 + 1; } for(i = 0;i < fastcall_nb_regs; i++) { if (args_size <= 0) break; o(0x58 + fastcall_regs_ptr[i]); /* pop r */ /* XXX: incorrect for struct/floats */ args_size -= 4; } } gcall_or_jmp(0); if (args_size && func_call != FUNC_STDCALL) gadd_sp(args_size); vtop--; } #ifdef TCC_TARGET_PE #define FUNC_PROLOG_SIZE 10 #else #define FUNC_PROLOG_SIZE 9 #endif /* generate function prolog of type 't' */ void gfunc_prolog(CType *func_type) { int addr, align, size, func_call, fastcall_nb_regs; int param_index, param_addr; uint8_t *fastcall_regs_ptr; Sym *sym; CType *type; sym = func_type->ref; func_call = FUNC_CALL(sym->r); addr = 8; loc = 0; if (func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) { fastcall_nb_regs = func_call - FUNC_FASTCALL1 + 1; fastcall_regs_ptr = fastcall_regs; } else if (func_call == FUNC_FASTCALLW) { fastcall_nb_regs = 2; fastcall_regs_ptr = fastcallw_regs; } else { fastcall_nb_regs = 0; fastcall_regs_ptr = NULL; } param_index = 0; ind += FUNC_PROLOG_SIZE; func_sub_sp_offset = ind; /* if the function returns a structure, then add an implicit pointer parameter */ func_vt = sym->type; if ((func_vt.t & VT_BTYPE) == VT_STRUCT) { /* XXX: fastcall case ? */ func_vc = addr; addr += 4; param_index++; } /* define parameters */ while ((sym = sym->next) != NULL) { type = &sym->type; size = type_size(type, &align); size = (size + 3) & ~3; #ifdef FUNC_STRUCT_PARAM_AS_PTR /* structs are passed as pointer */ if ((type->t & VT_BTYPE) == VT_STRUCT) { size = 4; } #endif if (param_index < fastcall_nb_regs) { /* save FASTCALL register */ loc -= 4; o(0x89); /* movl */ gen_modrm(fastcall_regs_ptr[param_index], VT_LOCAL, NULL, loc); param_addr = loc; } else { param_addr = addr; addr += size; } sym_push(sym->v & ~SYM_FIELD, type, VT_LOCAL | lvalue_type(type->t), param_addr); param_index++; } func_ret_sub = 0; /* pascal type call ? */ if (func_call == FUNC_STDCALL) func_ret_sub = addr - 8; /* leave some room for bound checking code */ if (tcc_state->do_bounds_check) { oad(0xb8, 0); /* lbound section pointer */ oad(0xb8, 0); /* call to function */ func_bound_offset = lbounds_section->data_offset; } } /* generate function epilog */ void gfunc_epilog(void) { int v, saved_ind; #ifdef CONFIG_TCC_BCHECK if (tcc_state->do_bounds_check && func_bound_offset != lbounds_section->data_offset) { int saved_ind; int *bounds_ptr; Sym *sym, *sym_data; /* add end of table info */ bounds_ptr = section_ptr_add(lbounds_section, sizeof(int)); *bounds_ptr = 0; /* generate bound local allocation */ saved_ind = ind; ind = func_sub_sp_offset; sym_data = get_sym_ref(&char_pointer_type, lbounds_section, func_bound_offset, lbounds_section->data_offset); greloc(cur_text_section, sym_data, ind + 1, R_386_32); oad(0xb8, 0); /* mov %eax, xxx */ sym = external_global_sym(TOK___bound_local_new, &func_old_type, 0); greloc(cur_text_section, sym, ind + 1, R_386_PC32); oad(0xe8, -4); ind = saved_ind; /* generate bound check local freeing */ o(0x5250); /* save returned value, if any */ greloc(cur_text_section, sym_data, ind + 1, R_386_32); oad(0xb8, 0); /* mov %eax, xxx */ sym = external_global_sym(TOK___bound_local_delete, &func_old_type, 0); greloc(cur_text_section, sym, ind + 1, R_386_PC32); oad(0xe8, -4); o(0x585a); /* restore returned value, if any */ } #endif o(0xc9); /* leave */ if (func_ret_sub == 0) { o(0xc3); /* ret */ } else { o(0xc2); /* ret n */ g(func_ret_sub); g(func_ret_sub >> 8); } /* align local size to word & save local variables */ v = (-loc + 3) & -4; saved_ind = ind; ind = func_sub_sp_offset - FUNC_PROLOG_SIZE; #ifdef TCC_TARGET_PE if (v >= 4096) { Sym *sym = external_global_sym(TOK___chkstk, &func_old_type, 0); oad(0xb8, v); /* mov stacksize, %eax */ oad(0xe8, -4); /* call __chkstk, (does the stackframe too) */ greloc(cur_text_section, sym, ind-4, R_386_PC32); } else #endif { o(0xe58955); /* push %ebp, mov %esp, %ebp */ o(0xec81); /* sub esp, stacksize */ gen_le32(v); #if FUNC_PROLOG_SIZE == 10 o(0x90); /* adjust to FUNC_PROLOG_SIZE */ #endif } ind = saved_ind; } /* generate a jump to a label */ int gjmp(int t) { return psym(0xe9, t); } /* generate a jump to a fixed address */ void gjmp_addr(int a) { int r; r = a - ind - 2; if (r == (char)r) { g(0xeb); g(r); } else { oad(0xe9, a - ind - 5); } } /* generate a test. set 'inv' to invert test. Stack entry is popped */ int gtst(int inv, int t) { int v, *p; v = vtop->r & VT_VALMASK; if (v == VT_CMP) { /* fast case : can jump directly since flags are set */ g(0x0f); t = psym((vtop->c.i - 16) ^ inv, t); } else if (v == VT_JMP || v == VT_JMPI) { /* && or || optimization */ if ((v & 1) == inv) { /* insert vtop->c jump list in t */ p = &vtop->c.i; while (*p != 0) p = (int *)(cur_text_section->data + *p); *p = t; t = vtop->c.i; } else { t = gjmp(t); gsym(vtop->c.i); } } else { if (is_float(vtop->type.t) || (vtop->type.t & VT_BTYPE) == VT_LLONG) { vpushi(0); gen_op(TOK_NE); } if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) { /* constant jmp optimization */ if ((vtop->c.i != 0) != inv) t = gjmp(t); } else { v = gv(RC_INT); o(0x85); o(0xc0 + v * 9); g(0x0f); t = psym(0x85 ^ inv, t); } } vtop--; return t; } /* generate an integer binary operation */ void gen_opi(int op) { int r, fr, opc, c; switch(op) { case '+': case TOK_ADDC1: /* add with carry generation */ opc = 0; gen_op8: if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) { /* constant case */ vswap(); r = gv(RC_INT); vswap(); c = vtop->c.i; if (c == (char)c) { /* XXX: generate inc and dec for smaller code ? */ o(0x83); o(0xc0 | (opc << 3) | r); g(c); } else { o(0x81); oad(0xc0 | (opc << 3) | r, c); } } else { gv2(RC_INT, RC_INT); r = vtop[-1].r; fr = vtop[0].r; o((opc << 3) | 0x01); o(0xc0 + r + fr * 8); } vtop--; if (op >= TOK_ULT && op <= TOK_GT) { vtop->r = VT_CMP; vtop->c.i = op; } break; case '-': case TOK_SUBC1: /* sub with carry generation */ opc = 5; goto gen_op8; case TOK_ADDC2: /* add with carry use */ opc = 2; goto gen_op8; case TOK_SUBC2: /* sub with carry use */ opc = 3; goto gen_op8; case '&': opc = 4; goto gen_op8; case '^': opc = 6; goto gen_op8; case '|': opc = 1; goto gen_op8; case '*': gv2(RC_INT, RC_INT); r = vtop[-1].r; fr = vtop[0].r; vtop--; o(0xaf0f); /* imul fr, r */ o(0xc0 + fr + r * 8); break; case TOK_SHL: opc = 4; goto gen_shift; case TOK_SHR: opc = 5; goto gen_shift; case TOK_SAR: opc = 7; gen_shift: opc = 0xc0 | (opc << 3); if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) { /* constant case */ vswap(); r = gv(RC_INT); vswap(); c = vtop->c.i & 0x1f; o(0xc1); /* shl/shr/sar $xxx, r */ o(opc | r); g(c); } else { /* we generate the shift in ecx */ gv2(RC_INT, RC_ECX); r = vtop[-1].r; o(0xd3); /* shl/shr/sar %cl, r */ o(opc | r); } vtop--; break; case '/': case TOK_UDIV: case TOK_PDIV: case '%': case TOK_UMOD: case TOK_UMULL: /* first operand must be in eax */ /* XXX: need better constraint for second operand */ gv2(RC_EAX, RC_ECX); r = vtop[-1].r; fr = vtop[0].r; vtop--; save_reg(TREG_EDX); if (op == TOK_UMULL) { o(0xf7); /* mul fr */ o(0xe0 + fr); vtop->r2 = TREG_EDX; r = TREG_EAX; } else { if (op == TOK_UDIV || op == TOK_UMOD) { o(0xf7d231); /* xor %edx, %edx, div fr, %eax */ o(0xf0 + fr); } else { o(0xf799); /* cltd, idiv fr, %eax */ o(0xf8 + fr); } if (op == '%' || op == TOK_UMOD) r = TREG_EDX; else r = TREG_EAX; } vtop->r = r; break; default: opc = 7; goto gen_op8; } } /* generate a floating point operation 'v = t1 op t2' instruction. The two operands are guaranted to have the same floating point type */ /* XXX: need to use ST1 too */ void gen_opf(int op) { int a, ft, fc, swapped, r; /* convert constants to memory references */ if ((vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_CONST) { vswap(); gv(RC_FLOAT); vswap(); } if ((vtop[0].r & (VT_VALMASK | VT_LVAL)) == VT_CONST) gv(RC_FLOAT); /* must put at least one value in the floating point register */ if ((vtop[-1].r & VT_LVAL) && (vtop[0].r & VT_LVAL)) { vswap(); gv(RC_FLOAT); vswap(); } swapped = 0; /* swap the stack if needed so that t1 is the register and t2 is the memory reference */ if (vtop[-1].r & VT_LVAL) { vswap(); swapped = 1; } if (op >= TOK_ULT && op <= TOK_GT) { /* load on stack second operand */ load(TREG_ST0, vtop); save_reg(TREG_EAX); /* eax is used by FP comparison code */ if (op == TOK_GE || op == TOK_GT) swapped = !swapped; else if (op == TOK_EQ || op == TOK_NE) swapped = 0; if (swapped) o(0xc9d9); /* fxch %st(1) */ o(0xe9da); /* fucompp */ o(0xe0df); /* fnstsw %ax */ if (op == TOK_EQ) { o(0x45e480); /* and $0x45, %ah */ o(0x40fC80); /* cmp $0x40, %ah */ } else if (op == TOK_NE) { o(0x45e480); /* and $0x45, %ah */ o(0x40f480); /* xor $0x40, %ah */ op = TOK_NE; } else if (op == TOK_GE || op == TOK_LE) { o(0x05c4f6); /* test $0x05, %ah */ op = TOK_EQ; } else { o(0x45c4f6); /* test $0x45, %ah */ op = TOK_EQ; } vtop--; vtop->r = VT_CMP; vtop->c.i = op; } else { /* no memory reference possible for long double operations */ if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) { load(TREG_ST0, vtop); swapped = !swapped; } switch(op) { default: case '+': a = 0; break; case '-': a = 4; if (swapped) a++; break; case '*': a = 1; break; case '/': a = 6; if (swapped) a++; break; } ft = vtop->type.t; fc = vtop->c.ul; if ((ft & VT_BTYPE) == VT_LDOUBLE) { o(0xde); /* fxxxp %st, %st(1) */ o(0xc1 + (a << 3)); } else { /* if saved lvalue, then we must reload it */ r = vtop->r; if ((r & VT_VALMASK) == VT_LLOCAL) { SValue v1; r = get_reg(RC_INT); v1.type.t = VT_INT; v1.r = VT_LOCAL | VT_LVAL; v1.c.ul = fc; load(r, &v1); fc = 0; } if ((ft & VT_BTYPE) == VT_DOUBLE) o(0xdc); else o(0xd8); gen_modrm(a, r, vtop->sym, fc); } vtop--; } } /* convert integers to fp 't' type. Must handle 'int', 'unsigned int' and 'long long' cases. */ void gen_cvt_itof(int t) { save_reg(TREG_ST0); gv(RC_INT); if ((vtop->type.t & VT_BTYPE) == VT_LLONG) { /* signed long long to float/double/long double (unsigned case is handled generically) */ o(0x50 + vtop->r2); /* push r2 */ o(0x50 + (vtop->r & VT_VALMASK)); /* push r */ o(0x242cdf); /* fildll (%esp) */ o(0x08c483); /* add $8, %esp */ } else if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED)) { /* unsigned int to float/double/long double */ o(0x6a); /* push $0 */ g(0x00); o(0x50 + (vtop->r & VT_VALMASK)); /* push r */ o(0x242cdf); /* fildll (%esp) */ o(0x08c483); /* add $8, %esp */ } else { /* int to float/double/long double */ o(0x50 + (vtop->r & VT_VALMASK)); /* push r */ o(0x2404db); /* fildl (%esp) */ o(0x04c483); /* add $4, %esp */ } vtop->r = TREG_ST0; } /* convert fp to int 't' type */ /* XXX: handle long long case */ void gen_cvt_ftoi(int t) { int r, r2, size; Sym *sym; CType ushort_type; ushort_type.t = VT_SHORT | VT_UNSIGNED; gv(RC_FLOAT); if (t != VT_INT) size = 8; else size = 4; o(0x2dd9); /* ldcw xxx */ sym = external_global_sym(TOK___tcc_int_fpu_control, &ushort_type, VT_LVAL); greloc(cur_text_section, sym, ind, R_386_32); gen_le32(0); oad(0xec81, size); /* sub $xxx, %esp */ if (size == 4) o(0x1cdb); /* fistpl */ else o(0x3cdf); /* fistpll */ o(0x24); o(0x2dd9); /* ldcw xxx */ sym = external_global_sym(TOK___tcc_fpu_control, &ushort_type, VT_LVAL); greloc(cur_text_section, sym, ind, R_386_32); gen_le32(0); r = get_reg(RC_INT); o(0x58 + r); /* pop r */ if (size == 8) { if (t == VT_LLONG) { vtop->r = r; /* mark reg as used */ r2 = get_reg(RC_INT); o(0x58 + r2); /* pop r2 */ vtop->r2 = r2; } else { o(0x04c483); /* add $4, %esp */ } } vtop->r = r; } /* convert from one floating point type to another */ void gen_cvt_ftof(int t) { /* all we have to do on i386 is to put the float in a register */ gv(RC_FLOAT); } /* computed goto support */ void ggoto(void) { gcall_or_jmp(1); vtop--; } /* bound check support functions */ #ifdef CONFIG_TCC_BCHECK /* generate a bounded pointer addition */ void gen_bounded_ptr_add(void) { Sym *sym; /* prepare fast i386 function call (args in eax and edx) */ gv2(RC_EAX, RC_EDX); /* save all temporary registers */ vtop -= 2; save_regs(0); /* do a fast function call */ sym = external_global_sym(TOK___bound_ptr_add, &func_old_type, 0); greloc(cur_text_section, sym, ind + 1, R_386_PC32); oad(0xe8, -4); /* returned pointer is in eax */ vtop++; vtop->r = TREG_EAX | VT_BOUNDED; /* address of bounding function call point */ vtop->c.ul = (cur_text_section->reloc->data_offset - sizeof(Elf32_Rel)); } /* patch pointer addition in vtop so that pointer dereferencing is also tested */ void gen_bounded_ptr_deref(void) { int func; int size, align; Elf32_Rel *rel; Sym *sym; size = 0; /* XXX: put that code in generic part of tcc */ if (!is_float(vtop->type.t)) { if (vtop->r & VT_LVAL_BYTE) size = 1; else if (vtop->r & VT_LVAL_SHORT) size = 2; } if (!size) size = type_size(&vtop->type, &align); switch(size) { case 1: func = TOK___bound_ptr_indir1; break; case 2: func = TOK___bound_ptr_indir2; break; case 4: func = TOK___bound_ptr_indir4; break; case 8: func = TOK___bound_ptr_indir8; break; case 12: func = TOK___bound_ptr_indir12; break; case 16: func = TOK___bound_ptr_indir16; break; default: error("unhandled size when derefencing bounded pointer"); func = 0; break; } /* patch relocation */ /* XXX: find a better solution ? */ rel = (Elf32_Rel *)(cur_text_section->reloc->data + vtop->c.ul); sym = external_global_sym(func, &func_old_type, 0); if (!sym->c) put_extern_sym(sym, NULL, 0, 0); rel->r_info = ELF32_R_INFO(sym->c, ELF32_R_TYPE(rel->r_info)); } #endif /* end of X86 code generator */ /*************************************************************/