PPC: Fix HREFK code generation for huge tables.
[luajit-2.0.git] / src / buildvm.c
blob29cf7378553d52ba5f7ac2f3d5563c80b4094223
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.
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.
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"
31 #if defined(_WIN32)
32 #include <fcntl.h>
33 #include <io.h>
34 #endif
36 /* ------------------------------------------------------------------------ */
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
44 #include "../dynasm/dasm_proto.h"
46 /* Glue macros for DynASM. */
47 static int collect_reloc(BuildCtx *ctx, uint8_t *addr, int idx, int type);
49 #define DASM_EXTERN(ctx, addr, idx, type) \
50 collect_reloc(ctx, addr, idx, type)
52 /* ------------------------------------------------------------------------ */
54 /* Avoid trouble if cross-compiling for an x86 target. Speed doesn't matter. */
55 #define DASM_ALIGNED_WRITES 1
57 /* Embed architecture-specific DynASM encoder and backend. */
58 #if LJ_TARGET_X86
59 #include "../dynasm/dasm_x86.h"
60 #include "buildvm_x86.h"
61 #elif LJ_TARGET_X64
62 #include "../dynasm/dasm_x86.h"
63 #if LJ_ABI_WIN
64 #include "buildvm_x64win.h"
65 #else
66 #include "buildvm_x64.h"
67 #endif
68 #elif LJ_TARGET_ARM
69 #include "../dynasm/dasm_arm.h"
70 #include "buildvm_arm.h"
71 #elif LJ_TARGET_PPC
72 #include "../dynasm/dasm_ppc.h"
73 #include "buildvm_ppc.h"
74 #elif LJ_TARGET_PPCSPE
75 #include "../dynasm/dasm_ppc.h"
76 #include "buildvm_ppcspe.h"
77 #elif LJ_TARGET_MIPS
78 #include "../dynasm/dasm_mips.h"
79 #include "buildvm_mips.h"
80 #else
81 #error "No support for this architecture (yet)"
82 #endif
84 /* ------------------------------------------------------------------------ */
86 void owrite(BuildCtx *ctx, const void *ptr, size_t sz)
88 if (fwrite(ptr, 1, sz, ctx->fp) != sz) {
89 fprintf(stderr, "Error: cannot write to output file: %s\n",
90 strerror(errno));
91 exit(1);
95 /* ------------------------------------------------------------------------ */
97 /* Emit code as raw bytes. Only used for DynASM debugging. */
98 static void emit_raw(BuildCtx *ctx)
100 owrite(ctx, ctx->code, ctx->codesz);
103 /* -- Build machine code -------------------------------------------------- */
105 static const char *sym_decorate(BuildCtx *ctx,
106 const char *prefix, const char *suffix)
108 char name[256];
109 char *p;
110 #if LJ_64
111 const char *symprefix = ctx->mode == BUILD_machasm ? "_" : "";
112 #else
113 const char *symprefix = ctx->mode != BUILD_elfasm ? "_" : "";
114 #endif
115 sprintf(name, "%s%s%s", symprefix, prefix, suffix);
116 p = strchr(name, '@');
117 if (p) {
118 if (!LJ_64 && (ctx->mode == BUILD_coffasm || ctx->mode == BUILD_peobj))
119 name[0] = '@';
120 else
121 *p = '\0';
123 p = (char *)malloc(strlen(name)+1); /* MSVC doesn't like strdup. */
124 strcpy(p, name);
125 return p;
128 #define NRELOCSYM (sizeof(extnames)/sizeof(extnames[0])-1)
130 static int relocmap[NRELOCSYM];
132 /* Collect external relocations. */
133 static int collect_reloc(BuildCtx *ctx, uint8_t *addr, int idx, int type)
135 if (ctx->nreloc >= BUILD_MAX_RELOC) {
136 fprintf(stderr, "Error: too many relocations, increase BUILD_MAX_RELOC.\n");
137 exit(1);
139 if (relocmap[idx] < 0) {
140 relocmap[idx] = ctx->nrelocsym;
141 ctx->relocsym[ctx->nrelocsym] = sym_decorate(ctx, "", extnames[idx]);
142 ctx->nrelocsym++;
144 ctx->reloc[ctx->nreloc].ofs = (int32_t)(addr - ctx->code);
145 ctx->reloc[ctx->nreloc].sym = relocmap[idx];
146 ctx->reloc[ctx->nreloc].type = type;
147 ctx->nreloc++;
148 return 0; /* Encode symbol offset of 0. */
151 /* Naive insertion sort. Performance doesn't matter here. */
152 static void sym_insert(BuildCtx *ctx, int32_t ofs,
153 const char *prefix, const char *suffix)
155 ptrdiff_t i = ctx->nsym++;
156 while (i > 0) {
157 if (ctx->sym[i-1].ofs <= ofs)
158 break;
159 ctx->sym[i] = ctx->sym[i-1];
160 i--;
162 ctx->sym[i].ofs = ofs;
163 ctx->sym[i].name = sym_decorate(ctx, prefix, suffix);
166 /* Build the machine code. */
167 static int build_code(BuildCtx *ctx)
169 int status;
170 int i;
172 /* Initialize DynASM structures. */
173 ctx->nglob = GLOB__MAX;
174 ctx->glob = (void **)malloc(ctx->nglob*sizeof(void *));
175 memset(ctx->glob, 0, ctx->nglob*sizeof(void *));
176 ctx->nreloc = 0;
178 ctx->globnames = globnames;
179 ctx->relocsym = (const char **)malloc(NRELOCSYM*sizeof(const char *));
180 ctx->nrelocsym = 0;
181 for (i = 0; i < (int)NRELOCSYM; i++) relocmap[i] = -1;
183 ctx->dasm_ident = DASM_IDENT;
184 ctx->dasm_arch = DASM_ARCH;
186 dasm_init(Dst, DASM_MAXSECTION);
187 dasm_setupglobal(Dst, ctx->glob, ctx->nglob);
188 dasm_setup(Dst, build_actionlist);
190 /* Call arch-specific backend to emit the code. */
191 ctx->npc = build_backend(ctx);
193 /* Finalize the code. */
194 (void)dasm_checkstep(Dst, -1);
195 if ((status = dasm_link(Dst, &ctx->codesz))) return status;
196 ctx->code = (uint8_t *)malloc(ctx->codesz);
197 if ((status = dasm_encode(Dst, (void *)ctx->code))) return status;
199 /* Allocate symbol table and bytecode offsets. */
200 ctx->beginsym = sym_decorate(ctx, "", LABEL_PREFIX "vm_asm_begin");
201 ctx->sym = (BuildSym *)malloc((ctx->npc+ctx->nglob+1)*sizeof(BuildSym));
202 ctx->nsym = 0;
203 ctx->bc_ofs = (int32_t *)malloc(ctx->npc*sizeof(int32_t));
205 /* Collect the opcodes (PC labels). */
206 for (i = 0; i < ctx->npc; i++) {
207 int32_t ofs = dasm_getpclabel(Dst, i);
208 if (ofs < 0) return 0x22000000|i;
209 ctx->bc_ofs[i] = ofs;
210 if ((LJ_HASJIT ||
211 !(i == BC_JFORI || i == BC_JFORL || i == BC_JITERL || i == BC_JLOOP ||
212 i == BC_IFORL || i == BC_IITERL || i == BC_ILOOP)) &&
213 (LJ_HASFFI || i != BC_KCDATA))
214 sym_insert(ctx, ofs, LABEL_PREFIX_BC, bc_names[i]);
217 /* Collect the globals (named labels). */
218 for (i = 0; i < ctx->nglob; i++) {
219 const char *gl = globnames[i];
220 int len = (int)strlen(gl);
221 if (!ctx->glob[i]) {
222 fprintf(stderr, "Error: undefined global %s\n", gl);
223 exit(2);
225 /* Skip the _Z symbols. */
226 if (!(len >= 2 && gl[len-2] == '_' && gl[len-1] == 'Z'))
227 sym_insert(ctx, (int32_t)((uint8_t *)(ctx->glob[i]) - ctx->code),
228 LABEL_PREFIX, globnames[i]);
231 /* Close the address range. */
232 sym_insert(ctx, (int32_t)ctx->codesz, "", "");
233 ctx->nsym--;
235 dasm_free(Dst);
237 return 0;
240 /* -- Generate VM enums --------------------------------------------------- */
242 const char *const bc_names[] = {
243 #define BCNAME(name, ma, mb, mc, mt) #name,
244 BCDEF(BCNAME)
245 #undef BCNAME
246 NULL
249 const char *const ir_names[] = {
250 #define IRNAME(name, m, m1, m2) #name,
251 IRDEF(IRNAME)
252 #undef IRNAME
253 NULL
256 const char *const irt_names[] = {
257 #define IRTNAME(name) #name,
258 IRTDEF(IRTNAME)
259 #undef IRTNAME
260 NULL
263 const char *const irfpm_names[] = {
264 #define FPMNAME(name) #name,
265 IRFPMDEF(FPMNAME)
266 #undef FPMNAME
267 NULL
270 const char *const irfield_names[] = {
271 #define FLNAME(name, ofs) #name,
272 IRFLDEF(FLNAME)
273 #undef FLNAME
274 NULL
277 const char *const ircall_names[] = {
278 #define IRCALLNAME(cond, name, nargs, kind, type, flags) #name,
279 IRCALLDEF(IRCALLNAME)
280 #undef IRCALLNAME
281 NULL
284 static const char *const trace_errors[] = {
285 #define TREDEF(name, msg) msg,
286 #include "lj_traceerr.h"
287 NULL
290 static const char *lower(char *buf, const char *s)
292 char *p = buf;
293 while (*s) {
294 *p++ = (*s >= 'A' && *s <= 'Z') ? *s+0x20 : *s;
295 s++;
297 *p = '\0';
298 return buf;
301 /* Emit C source code for bytecode-related definitions. */
302 static void emit_bcdef(BuildCtx *ctx)
304 int i;
305 fprintf(ctx->fp, "/* This is a generated file. DO NOT EDIT! */\n\n");
306 fprintf(ctx->fp, "LJ_DATADEF const uint16_t lj_bc_ofs[] = {\n");
307 for (i = 0; i < ctx->npc; i++) {
308 if (i != 0)
309 fprintf(ctx->fp, ",\n");
310 fprintf(ctx->fp, "%d", ctx->bc_ofs[i]);
314 /* Emit VM definitions as Lua code for debug modules. */
315 static void emit_vmdef(BuildCtx *ctx)
317 char buf[80];
318 int i;
319 fprintf(ctx->fp, "-- This is a generated file. DO NOT EDIT!\n\n");
320 fprintf(ctx->fp, "module(...)\n\n");
322 fprintf(ctx->fp, "bcnames = \"");
323 for (i = 0; bc_names[i]; i++) fprintf(ctx->fp, "%-6s", bc_names[i]);
324 fprintf(ctx->fp, "\"\n\n");
326 fprintf(ctx->fp, "irnames = \"");
327 for (i = 0; ir_names[i]; i++) fprintf(ctx->fp, "%-6s", ir_names[i]);
328 fprintf(ctx->fp, "\"\n\n");
330 fprintf(ctx->fp, "irfpm = { [0]=");
331 for (i = 0; irfpm_names[i]; i++)
332 fprintf(ctx->fp, "\"%s\", ", lower(buf, irfpm_names[i]));
333 fprintf(ctx->fp, "}\n\n");
335 fprintf(ctx->fp, "irfield = { [0]=");
336 for (i = 0; irfield_names[i]; i++) {
337 char *p;
338 lower(buf, irfield_names[i]);
339 p = strchr(buf, '_');
340 if (p) *p = '.';
341 fprintf(ctx->fp, "\"%s\", ", buf);
343 fprintf(ctx->fp, "}\n\n");
345 fprintf(ctx->fp, "ircall = {\n[0]=");
346 for (i = 0; ircall_names[i]; i++)
347 fprintf(ctx->fp, "\"%s\",\n", ircall_names[i]);
348 fprintf(ctx->fp, "}\n\n");
350 fprintf(ctx->fp, "traceerr = {\n[0]=");
351 for (i = 0; trace_errors[i]; i++)
352 fprintf(ctx->fp, "\"%s\",\n", trace_errors[i]);
353 fprintf(ctx->fp, "}\n\n");
356 /* -- Argument parsing ---------------------------------------------------- */
358 /* Build mode names. */
359 static const char *const modenames[] = {
360 #define BUILDNAME(name) #name,
361 BUILDDEF(BUILDNAME)
362 #undef BUILDNAME
363 NULL
366 /* Print usage information and exit. */
367 static void usage(void)
369 int i;
370 fprintf(stderr, LUAJIT_VERSION " VM builder.\n");
371 fprintf(stderr, LUAJIT_COPYRIGHT ", " LUAJIT_URL "\n");
372 fprintf(stderr, "Target architecture: " LJ_ARCH_NAME "\n\n");
373 fprintf(stderr, "Usage: buildvm -m mode [-o outfile] [infiles...]\n\n");
374 fprintf(stderr, "Available modes:\n");
375 for (i = 0; i < BUILD__MAX; i++)
376 fprintf(stderr, " %s\n", modenames[i]);
377 exit(1);
380 /* Parse the output mode name. */
381 static BuildMode parsemode(const char *mode)
383 int i;
384 for (i = 0; modenames[i]; i++)
385 if (!strcmp(mode, modenames[i]))
386 return (BuildMode)i;
387 usage();
388 return (BuildMode)-1;
391 /* Parse arguments. */
392 static void parseargs(BuildCtx *ctx, char **argv)
394 const char *a;
395 int i;
396 ctx->mode = (BuildMode)-1;
397 ctx->outname = "-";
398 for (i = 1; (a = argv[i]) != NULL; i++) {
399 if (a[0] != '-')
400 break;
401 switch (a[1]) {
402 case '-':
403 if (a[2]) goto err;
404 i++;
405 goto ok;
406 case '\0':
407 goto ok;
408 case 'm':
409 i++;
410 if (a[2] || argv[i] == NULL) goto err;
411 ctx->mode = parsemode(argv[i]);
412 break;
413 case 'o':
414 i++;
415 if (a[2] || argv[i] == NULL) goto err;
416 ctx->outname = argv[i];
417 break;
418 default: err:
419 usage();
420 break;
424 ctx->args = argv+i;
425 if (ctx->mode == (BuildMode)-1) goto err;
428 int main(int argc, char **argv)
430 BuildCtx ctx_;
431 BuildCtx *ctx = &ctx_;
432 int status, binmode;
434 if (sizeof(void *) != 4*LJ_32+8*LJ_64) {
435 fprintf(stderr,"Error: pointer size mismatch in cross-build.\n");
436 fprintf(stderr,"Try: make HOST_CC=\"gcc -m32\" CROSS=... TARGET=...\n\n");
437 return 1;
440 UNUSED(argc);
441 parseargs(ctx, argv);
443 if ((status = build_code(ctx))) {
444 fprintf(stderr,"Error: DASM error %08x\n", status);
445 return 1;
448 switch (ctx->mode) {
449 case BUILD_peobj:
450 case BUILD_raw:
451 binmode = 1;
452 break;
453 default:
454 binmode = 0;
455 break;
458 if (ctx->outname[0] == '-' && ctx->outname[1] == '\0') {
459 ctx->fp = stdout;
460 #if defined(_WIN32)
461 if (binmode)
462 _setmode(_fileno(stdout), _O_BINARY); /* Yuck. */
463 #endif
464 } else if (!(ctx->fp = fopen(ctx->outname, binmode ? "wb" : "w"))) {
465 fprintf(stderr, "Error: cannot open output file '%s': %s\n",
466 ctx->outname, strerror(errno));
467 exit(1);
470 switch (ctx->mode) {
471 case BUILD_elfasm:
472 case BUILD_coffasm:
473 case BUILD_machasm:
474 emit_asm(ctx);
475 emit_asm_debug(ctx);
476 break;
477 case BUILD_peobj:
478 emit_peobj(ctx);
479 break;
480 case BUILD_raw:
481 emit_raw(ctx);
482 break;
483 case BUILD_bcdef:
484 emit_bcdef(ctx);
485 emit_lib(ctx);
486 break;
487 case BUILD_vmdef:
488 emit_vmdef(ctx);
489 emit_lib(ctx);
490 break;
491 case BUILD_ffdef:
492 case BUILD_libdef:
493 case BUILD_recdef:
494 emit_lib(ctx);
495 break;
496 case BUILD_folddef:
497 emit_fold(ctx);
498 break;
499 default:
500 break;
503 fflush(ctx->fp);
504 if (ferror(ctx->fp)) {
505 fprintf(stderr, "Error: cannot write to output file: %s\n",
506 strerror(errno));
507 exit(1);
509 fclose(ctx->fp);
511 return 0;