aboutsummaryrefslogtreecommitdiff
path: root/src/host/buildvm.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/buildvm.c')
-rw-r--r--src/host/buildvm.c504
1 files changed, 504 insertions, 0 deletions
diff --git a/src/host/buildvm.c b/src/host/buildvm.c
new file mode 100644
index 00000000..7dbf2cae
--- /dev/null
+++ b/src/host/buildvm.c
@@ -0,0 +1,504 @@
1/*
2** LuaJIT VM builder.
3** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4**
5** This is a tool to build the hand-tuned assembler code required for
6** LuaJIT's bytecode interpreter. It supports a variety of output formats
7** to feed different toolchains (see usage() below).
8**
9** This tool is not particularly optimized because it's only used while
10** _building_ LuaJIT. There's no point in distributing or installing it.
11** Only the object code generated by this tool is linked into LuaJIT.
12**
13** Caveat: some memory is not free'd, error handling is lazy.
14** It's a one-shot tool -- any effort fixing this would be wasted.
15*/
16
17#include "buildvm.h"
18#include "lj_obj.h"
19#include "lj_gc.h"
20#include "lj_bc.h"
21#include "lj_ir.h"
22#include "lj_ircall.h"
23#include "lj_frame.h"
24#include "lj_dispatch.h"
25#if LJ_HASFFI
26#include "lj_ctype.h"
27#include "lj_ccall.h"
28#endif
29#include "luajit.h"
30
31#if defined(_WIN32)
32#include <fcntl.h>
33#include <io.h>
34#endif
35
36/* ------------------------------------------------------------------------ */
37
38/* DynASM glue definitions. */
39#define Dst ctx
40#define Dst_DECL BuildCtx *ctx
41#define Dst_REF (ctx->D)
42#define DASM_CHECKS 1
43
44#include "../dynasm/dasm_proto.h"
45
46/* Glue macros for DynASM. */
47static int collect_reloc(BuildCtx *ctx, uint8_t *addr, int idx, int type);
48
49#define DASM_EXTERN(ctx, addr, idx, type) \
50 collect_reloc(ctx, addr, idx, type)
51
52/* ------------------------------------------------------------------------ */
53
54/* Avoid trouble if cross-compiling for an x86 target. Speed doesn't matter. */
55#define DASM_ALIGNED_WRITES 1
56
57/* Embed architecture-specific DynASM encoder. */
58#if LJ_TARGET_X86ORX64
59#include "../dynasm/dasm_x86.h"
60#elif LJ_TARGET_ARM
61#include "../dynasm/dasm_arm.h"
62#elif LJ_TARGET_PPC
63#include "../dynasm/dasm_ppc.h"
64#elif LJ_TARGET_PPCSPE
65#include "../dynasm/dasm_ppc.h"
66#elif LJ_TARGET_MIPS
67#include "../dynasm/dasm_mips.h"
68#else
69#error "No support for this architecture (yet)"
70#endif
71
72/* Embed generated architecture-specific backend. */
73#include "buildvm_arch.h"
74
75/* ------------------------------------------------------------------------ */
76
77void owrite(BuildCtx *ctx, const void *ptr, size_t sz)
78{
79 if (fwrite(ptr, 1, sz, ctx->fp) != sz) {
80 fprintf(stderr, "Error: cannot write to output file: %s\n",
81 strerror(errno));
82 exit(1);
83 }
84}
85
86/* ------------------------------------------------------------------------ */
87
88/* Emit code as raw bytes. Only used for DynASM debugging. */
89static void emit_raw(BuildCtx *ctx)
90{
91 owrite(ctx, ctx->code, ctx->codesz);
92}
93
94/* -- Build machine code -------------------------------------------------- */
95
96static const char *sym_decorate(BuildCtx *ctx,
97 const char *prefix, const char *suffix)
98{
99 char name[256];
100 char *p;
101#if LJ_64
102 const char *symprefix = ctx->mode == BUILD_machasm ? "_" : "";
103#else
104 const char *symprefix = ctx->mode != BUILD_elfasm ? "_" : "";
105#endif
106 sprintf(name, "%s%s%s", symprefix, prefix, suffix);
107 p = strchr(name, '@');
108 if (p) {
109 if (!LJ_64 && (ctx->mode == BUILD_coffasm || ctx->mode == BUILD_peobj))
110 name[0] = '@';
111 else
112 *p = '\0';
113 }
114 p = (char *)malloc(strlen(name)+1); /* MSVC doesn't like strdup. */
115 strcpy(p, name);
116 return p;
117}
118
119#define NRELOCSYM (sizeof(extnames)/sizeof(extnames[0])-1)
120
121static int relocmap[NRELOCSYM];
122
123/* Collect external relocations. */
124static int collect_reloc(BuildCtx *ctx, uint8_t *addr, int idx, int type)
125{
126 if (ctx->nreloc >= BUILD_MAX_RELOC) {
127 fprintf(stderr, "Error: too many relocations, increase BUILD_MAX_RELOC.\n");
128 exit(1);
129 }
130 if (relocmap[idx] < 0) {
131 relocmap[idx] = ctx->nrelocsym;
132 ctx->relocsym[ctx->nrelocsym] = sym_decorate(ctx, "", extnames[idx]);
133 ctx->nrelocsym++;
134 }
135 ctx->reloc[ctx->nreloc].ofs = (int32_t)(addr - ctx->code);
136 ctx->reloc[ctx->nreloc].sym = relocmap[idx];
137 ctx->reloc[ctx->nreloc].type = type;
138 ctx->nreloc++;
139 return 0; /* Encode symbol offset of 0. */
140}
141
142/* Naive insertion sort. Performance doesn't matter here. */
143static void sym_insert(BuildCtx *ctx, int32_t ofs,
144 const char *prefix, const char *suffix)
145{
146 ptrdiff_t i = ctx->nsym++;
147 while (i > 0) {
148 if (ctx->sym[i-1].ofs <= ofs)
149 break;
150 ctx->sym[i] = ctx->sym[i-1];
151 i--;
152 }
153 ctx->sym[i].ofs = ofs;
154 ctx->sym[i].name = sym_decorate(ctx, prefix, suffix);
155}
156
157/* Build the machine code. */
158static int build_code(BuildCtx *ctx)
159{
160 int status;
161 int i;
162
163 /* Initialize DynASM structures. */
164 ctx->nglob = GLOB__MAX;
165 ctx->glob = (void **)malloc(ctx->nglob*sizeof(void *));
166 memset(ctx->glob, 0, ctx->nglob*sizeof(void *));
167 ctx->nreloc = 0;
168
169 ctx->globnames = globnames;
170 ctx->relocsym = (const char **)malloc(NRELOCSYM*sizeof(const char *));
171 ctx->nrelocsym = 0;
172 for (i = 0; i < (int)NRELOCSYM; i++) relocmap[i] = -1;
173
174 ctx->dasm_ident = DASM_IDENT;
175 ctx->dasm_arch = DASM_ARCH;
176
177 dasm_init(Dst, DASM_MAXSECTION);
178 dasm_setupglobal(Dst, ctx->glob, ctx->nglob);
179 dasm_setup(Dst, build_actionlist);
180
181 /* Call arch-specific backend to emit the code. */
182 ctx->npc = build_backend(ctx);
183
184 /* Finalize the code. */
185 (void)dasm_checkstep(Dst, -1);
186 if ((status = dasm_link(Dst, &ctx->codesz))) return status;
187 ctx->code = (uint8_t *)malloc(ctx->codesz);
188 if ((status = dasm_encode(Dst, (void *)ctx->code))) return status;
189
190 /* Allocate symbol table and bytecode offsets. */
191 ctx->beginsym = sym_decorate(ctx, "", LABEL_PREFIX "vm_asm_begin");
192 ctx->sym = (BuildSym *)malloc((ctx->npc+ctx->nglob+1)*sizeof(BuildSym));
193 ctx->nsym = 0;
194 ctx->bc_ofs = (int32_t *)malloc(ctx->npc*sizeof(int32_t));
195
196 /* Collect the opcodes (PC labels). */
197 for (i = 0; i < ctx->npc; i++) {
198 int32_t ofs = dasm_getpclabel(Dst, i);
199 if (ofs < 0) return 0x22000000|i;
200 ctx->bc_ofs[i] = ofs;
201 if ((LJ_HASJIT ||
202 !(i == BC_JFORI || i == BC_JFORL || i == BC_JITERL || i == BC_JLOOP ||
203 i == BC_IFORL || i == BC_IITERL || i == BC_ILOOP)) &&
204 (LJ_HASFFI || i != BC_KCDATA))
205 sym_insert(ctx, ofs, LABEL_PREFIX_BC, bc_names[i]);
206 }
207
208 /* Collect the globals (named labels). */
209 for (i = 0; i < ctx->nglob; i++) {
210 const char *gl = globnames[i];
211 int len = (int)strlen(gl);
212 if (!ctx->glob[i]) {
213 fprintf(stderr, "Error: undefined global %s\n", gl);
214 exit(2);
215 }
216 /* Skip the _Z symbols. */
217 if (!(len >= 2 && gl[len-2] == '_' && gl[len-1] == 'Z'))
218 sym_insert(ctx, (int32_t)((uint8_t *)(ctx->glob[i]) - ctx->code),
219 LABEL_PREFIX, globnames[i]);
220 }
221
222 /* Close the address range. */
223 sym_insert(ctx, (int32_t)ctx->codesz, "", "");
224 ctx->nsym--;
225
226 dasm_free(Dst);
227
228 return 0;
229}
230
231/* -- Generate VM enums --------------------------------------------------- */
232
233const char *const bc_names[] = {
234#define BCNAME(name, ma, mb, mc, mt) #name,
235BCDEF(BCNAME)
236#undef BCNAME
237 NULL
238};
239
240const char *const ir_names[] = {
241#define IRNAME(name, m, m1, m2) #name,
242IRDEF(IRNAME)
243#undef IRNAME
244 NULL
245};
246
247const char *const irt_names[] = {
248#define IRTNAME(name) #name,
249IRTDEF(IRTNAME)
250#undef IRTNAME
251 NULL
252};
253
254const char *const irfpm_names[] = {
255#define FPMNAME(name) #name,
256IRFPMDEF(FPMNAME)
257#undef FPMNAME
258 NULL
259};
260
261const char *const irfield_names[] = {
262#define FLNAME(name, ofs) #name,
263IRFLDEF(FLNAME)
264#undef FLNAME
265 NULL
266};
267
268const char *const ircall_names[] = {
269#define IRCALLNAME(cond, name, nargs, kind, type, flags) #name,
270IRCALLDEF(IRCALLNAME)
271#undef IRCALLNAME
272 NULL
273};
274
275static const char *const trace_errors[] = {
276#define TREDEF(name, msg) msg,
277#include "lj_traceerr.h"
278 NULL
279};
280
281static const char *lower(char *buf, const char *s)
282{
283 char *p = buf;
284 while (*s) {
285 *p++ = (*s >= 'A' && *s <= 'Z') ? *s+0x20 : *s;
286 s++;
287 }
288 *p = '\0';
289 return buf;
290}
291
292/* Emit C source code for bytecode-related definitions. */
293static void emit_bcdef(BuildCtx *ctx)
294{
295 int i;
296 fprintf(ctx->fp, "/* This is a generated file. DO NOT EDIT! */\n\n");
297 fprintf(ctx->fp, "LJ_DATADEF const uint16_t lj_bc_ofs[] = {\n");
298 for (i = 0; i < ctx->npc; i++) {
299 if (i != 0)
300 fprintf(ctx->fp, ",\n");
301 fprintf(ctx->fp, "%d", ctx->bc_ofs[i]);
302 }
303}
304
305/* Emit VM definitions as Lua code for debug modules. */
306static void emit_vmdef(BuildCtx *ctx)
307{
308 char buf[80];
309 int i;
310 fprintf(ctx->fp, "-- This is a generated file. DO NOT EDIT!\n\n");
311 fprintf(ctx->fp, "module(...)\n\n");
312
313 fprintf(ctx->fp, "bcnames = \"");
314 for (i = 0; bc_names[i]; i++) fprintf(ctx->fp, "%-6s", bc_names[i]);
315 fprintf(ctx->fp, "\"\n\n");
316
317 fprintf(ctx->fp, "irnames = \"");
318 for (i = 0; ir_names[i]; i++) fprintf(ctx->fp, "%-6s", ir_names[i]);
319 fprintf(ctx->fp, "\"\n\n");
320
321 fprintf(ctx->fp, "irfpm = { [0]=");
322 for (i = 0; irfpm_names[i]; i++)
323 fprintf(ctx->fp, "\"%s\", ", lower(buf, irfpm_names[i]));
324 fprintf(ctx->fp, "}\n\n");
325
326 fprintf(ctx->fp, "irfield = { [0]=");
327 for (i = 0; irfield_names[i]; i++) {
328 char *p;
329 lower(buf, irfield_names[i]);
330 p = strchr(buf, '_');
331 if (p) *p = '.';
332 fprintf(ctx->fp, "\"%s\", ", buf);
333 }
334 fprintf(ctx->fp, "}\n\n");
335
336 fprintf(ctx->fp, "ircall = {\n[0]=");
337 for (i = 0; ircall_names[i]; i++)
338 fprintf(ctx->fp, "\"%s\",\n", ircall_names[i]);
339 fprintf(ctx->fp, "}\n\n");
340
341 fprintf(ctx->fp, "traceerr = {\n[0]=");
342 for (i = 0; trace_errors[i]; i++)
343 fprintf(ctx->fp, "\"%s\",\n", trace_errors[i]);
344 fprintf(ctx->fp, "}\n\n");
345}
346
347/* -- Argument parsing ---------------------------------------------------- */
348
349/* Build mode names. */
350static const char *const modenames[] = {
351#define BUILDNAME(name) #name,
352BUILDDEF(BUILDNAME)
353#undef BUILDNAME
354 NULL
355};
356
357/* Print usage information and exit. */
358static void usage(void)
359{
360 int i;
361 fprintf(stderr, LUAJIT_VERSION " VM builder.\n");
362 fprintf(stderr, LUAJIT_COPYRIGHT ", " LUAJIT_URL "\n");
363 fprintf(stderr, "Target architecture: " LJ_ARCH_NAME "\n\n");
364 fprintf(stderr, "Usage: buildvm -m mode [-o outfile] [infiles...]\n\n");
365 fprintf(stderr, "Available modes:\n");
366 for (i = 0; i < BUILD__MAX; i++)
367 fprintf(stderr, " %s\n", modenames[i]);
368 exit(1);
369}
370
371/* Parse the output mode name. */
372static BuildMode parsemode(const char *mode)
373{
374 int i;
375 for (i = 0; modenames[i]; i++)
376 if (!strcmp(mode, modenames[i]))
377 return (BuildMode)i;
378 usage();
379 return (BuildMode)-1;
380}
381
382/* Parse arguments. */
383static void parseargs(BuildCtx *ctx, char **argv)
384{
385 const char *a;
386 int i;
387 ctx->mode = (BuildMode)-1;
388 ctx->outname = "-";
389 for (i = 1; (a = argv[i]) != NULL; i++) {
390 if (a[0] != '-')
391 break;
392 switch (a[1]) {
393 case '-':
394 if (a[2]) goto err;
395 i++;
396 goto ok;
397 case '\0':
398 goto ok;
399 case 'm':
400 i++;
401 if (a[2] || argv[i] == NULL) goto err;
402 ctx->mode = parsemode(argv[i]);
403 break;
404 case 'o':
405 i++;
406 if (a[2] || argv[i] == NULL) goto err;
407 ctx->outname = argv[i];
408 break;
409 default: err:
410 usage();
411 break;
412 }
413 }
414ok:
415 ctx->args = argv+i;
416 if (ctx->mode == (BuildMode)-1) goto err;
417}
418
419int main(int argc, char **argv)
420{
421 BuildCtx ctx_;
422 BuildCtx *ctx = &ctx_;
423 int status, binmode;
424
425 if (sizeof(void *) != 4*LJ_32+8*LJ_64) {
426 fprintf(stderr,"Error: pointer size mismatch in cross-build.\n");
427 fprintf(stderr,"Try: make HOST_CC=\"gcc -m32\" CROSS=... TARGET=...\n\n");
428 return 1;
429 }
430
431 UNUSED(argc);
432 parseargs(ctx, argv);
433
434 if ((status = build_code(ctx))) {
435 fprintf(stderr,"Error: DASM error %08x\n", status);
436 return 1;
437 }
438
439 switch (ctx->mode) {
440 case BUILD_peobj:
441 case BUILD_raw:
442 binmode = 1;
443 break;
444 default:
445 binmode = 0;
446 break;
447 }
448
449 if (ctx->outname[0] == '-' && ctx->outname[1] == '\0') {
450 ctx->fp = stdout;
451#if defined(_WIN32)
452 if (binmode)
453 _setmode(_fileno(stdout), _O_BINARY); /* Yuck. */
454#endif
455 } else if (!(ctx->fp = fopen(ctx->outname, binmode ? "wb" : "w"))) {
456 fprintf(stderr, "Error: cannot open output file '%s': %s\n",
457 ctx->outname, strerror(errno));
458 exit(1);
459 }
460
461 switch (ctx->mode) {
462 case BUILD_elfasm:
463 case BUILD_coffasm:
464 case BUILD_machasm:
465 emit_asm(ctx);
466 emit_asm_debug(ctx);
467 break;
468 case BUILD_peobj:
469 emit_peobj(ctx);
470 break;
471 case BUILD_raw:
472 emit_raw(ctx);
473 break;
474 case BUILD_bcdef:
475 emit_bcdef(ctx);
476 emit_lib(ctx);
477 break;
478 case BUILD_vmdef:
479 emit_vmdef(ctx);
480 emit_lib(ctx);
481 break;
482 case BUILD_ffdef:
483 case BUILD_libdef:
484 case BUILD_recdef:
485 emit_lib(ctx);
486 break;
487 case BUILD_folddef:
488 emit_fold(ctx);
489 break;
490 default:
491 break;
492 }
493
494 fflush(ctx->fp);
495 if (ferror(ctx->fp)) {
496 fprintf(stderr, "Error: cannot write to output file: %s\n",
497 strerror(errno));
498 exit(1);
499 }
500 fclose(ctx->fp);
501
502 return 0;
503}
504