Annotation of gforth/engine/main.c, revision 1.218

1.1       anton       1: /* command line interpretation, image loading etc. for Gforth
                      2: 
                      3: 
1.208     anton       4:   Copyright (C) 1995,1996,1997,1998,2000,2003,2004,2005,2006,2007,2008 Free Software Foundation, Inc.
1.1       anton       5: 
                      6:   This file is part of Gforth.
                      7: 
                      8:   Gforth is free software; you can redistribute it and/or
                      9:   modify it under the terms of the GNU General Public License
1.193     anton      10:   as published by the Free Software Foundation, either version 3
1.1       anton      11:   of the License, or (at your option) any later version.
                     12: 
                     13:   This program is distributed in the hope that it will be useful,
                     14:   but WITHOUT ANY WARRANTY; without even the implied warranty of
                     15:   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     16:   GNU General Public License for more details.
                     17: 
                     18:   You should have received a copy of the GNU General Public License
1.193     anton      19:   along with this program; if not, see http://www.gnu.org/licenses/.
1.1       anton      20: */
                     21: 
                     22: #include "config.h"
1.82      anton      23: #include "forth.h"
1.1       anton      24: #include <errno.h>
                     25: #include <ctype.h>
                     26: #include <stdio.h>
1.2       pazsan     27: #include <unistd.h>
1.1       anton      28: #include <string.h>
                     29: #include <math.h>
                     30: #include <sys/types.h>
1.214     anton      31: #ifdef HAVE_ALLOCA_H
1.213     anton      32: #include <alloca.h>
1.214     anton      33: #endif
1.32      pazsan     34: #ifndef STANDALONE
1.1       anton      35: #include <sys/stat.h>
1.32      pazsan     36: #endif
1.1       anton      37: #include <fcntl.h>
                     38: #include <assert.h>
                     39: #include <stdlib.h>
1.102     anton      40: #include <signal.h>
1.11      pazsan     41: #ifndef STANDALONE
1.1       anton      42: #if HAVE_SYS_MMAN_H
                     43: #include <sys/mman.h>
                     44: #endif
1.11      pazsan     45: #endif
1.1       anton      46: #include "io.h"
                     47: #include "getopt.h"
1.11      pazsan     48: #ifdef STANDALONE
1.174     pazsan     49: /* #include <systypes.h> */
1.11      pazsan     50: #endif
1.1       anton      51: 
1.190     anton      52: /* output rules etc. for burg with --debug and --print-sequences */
                     53: /* #define BURG_FORMAT*/
                     54: 
1.121     anton      55: typedef enum prim_num {
1.119     anton      56: /* definitions of N_execute etc. */
1.126     anton      57: #include PRIM_NUM_I
1.119     anton      58:   N_START_SUPER
1.121     anton      59: } PrimNum;
1.119     anton      60: 
1.79      anton      61: /* global variables for engine.c 
                     62:    We put them here because engine.c is compiled several times in
                     63:    different ways for the same engine. */
1.161     pazsan     64: Cell *gforth_SP;
                     65: Float *gforth_FP;
                     66: Address gforth_UP=NULL;
1.207     pazsan     67: Cell *gforth_RP;
                     68: Address gforth_LP;
1.79      anton      69: 
1.216     pazsan     70: #ifndef HAS_LINKBACK
                     71: void * gforth_pointers[] = { 
                     72:   (void*)&gforth_SP,
                     73:   (void*)&gforth_FP,
                     74:   (void*)&gforth_LP,
                     75:   (void*)&gforth_RP,
                     76:   (void*)&gforth_UP,
1.217     pazsan     77:   (void*)gforth_engine,
                     78:   (void*)cstr,
                     79:   (void*)tilde_cstr };
1.216     pazsan     80: #endif
                     81: 
1.115     pazsan     82: #ifdef HAS_FFCALL
                     83: 
                     84: #include <callback.h>
                     85: 
1.161     pazsan     86: va_alist gforth_clist;
1.115     pazsan     87: 
1.161     pazsan     88: void gforth_callback(Xt* fcall, void * alist)
1.115     pazsan     89: {
1.140     pazsan     90:   /* save global valiables */
1.161     pazsan     91:   Cell *rp = gforth_RP;
                     92:   Cell *sp = gforth_SP;
                     93:   Float *fp = gforth_FP;
                     94:   Address lp = gforth_LP;
1.168     pazsan     95:   va_alist clist = gforth_clist;
1.140     pazsan     96: 
1.161     pazsan     97:   gforth_clist = (va_alist)alist;
1.140     pazsan     98: 
1.197     anton      99:   gforth_engine(fcall, sp, rp, fp, lp sr_call);
1.140     pazsan    100: 
                    101:   /* restore global variables */
1.161     pazsan    102:   gforth_RP = rp;
                    103:   gforth_SP = sp;
                    104:   gforth_FP = fp;
                    105:   gforth_LP = lp;
1.168     pazsan    106:   gforth_clist = clist;
1.115     pazsan    107: }
                    108: #endif
                    109: 
1.79      anton     110: #ifdef GFORTH_DEBUGGING
                    111: /* define some VM registers as global variables, so they survive exceptions;
                    112:    global register variables are not up to the task (according to the 
                    113:    GNU C manual) */
1.197     anton     114: #if defined(GLOBALS_NONRELOC)
                    115: saved_regs saved_regs_v;
                    116: saved_regs *saved_regs_p = &saved_regs_v;
                    117: #else /* !defined(GLOBALS_NONRELOC) */
1.79      anton     118: Xt *saved_ip;
                    119: Cell *rp;
1.197     anton     120: #endif /* !defined(GLOBALS_NONRELOC) */
                    121: #endif /* !defined(GFORTH_DEBUGGING) */
1.79      anton     122: 
                    123: #ifdef NO_IP
                    124: Label next_code;
                    125: #endif
                    126: 
                    127: #ifdef HAS_FILE
                    128: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
                    129: char* pfileattr[6]={"r","r","r+","r+","w","w"};
                    130: 
                    131: #ifndef O_BINARY
                    132: #define O_BINARY 0
                    133: #endif
                    134: #ifndef O_TEXT
                    135: #define O_TEXT 0
                    136: #endif
                    137: 
                    138: int ufileattr[6]= {
                    139:   O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
                    140:   O_RDWR  |O_BINARY, O_RDWR  |O_BINARY,
                    141:   O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
                    142: #endif
                    143: /* end global vars for engine.c */
                    144: 
1.1       anton     145: #define PRIM_VERSION 1
                    146: /* increment this whenever the primitives change in an incompatible way */
                    147: 
1.14      pazsan    148: #ifndef DEFAULTPATH
1.39      anton     149: #  define DEFAULTPATH "."
1.14      pazsan    150: #endif
                    151: 
1.1       anton     152: #ifdef MSDOS
                    153: jmp_buf throw_jmp_buf;
                    154: #endif
                    155: 
1.56      anton     156: #if defined(DOUBLY_INDIRECT)
                    157: #  define CFA(n)       ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
1.1       anton     158: #else
1.56      anton     159: #  define CFA(n)       ((Cell)(symbols+((n)&~0x4000UL)))
1.1       anton     160: #endif
                    161: 
                    162: #define maxaligned(n)  (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
                    163: 
                    164: static UCell dictsize=0;
                    165: static UCell dsize=0;
                    166: static UCell rsize=0;
                    167: static UCell fsize=0;
                    168: static UCell lsize=0;
                    169: int offset_image=0;
1.4       anton     170: int die_on_signal=0;
1.169     anton     171: int ignore_async_signals=0;
1.13      pazsan    172: #ifndef INCLUDE_IMAGE
1.1       anton     173: static int clear_dictionary=0;
1.24      anton     174: UCell pagesize=1;
1.22      pazsan    175: char *progname;
                    176: #else
                    177: char *progname = "gforth";
                    178: int optind = 1;
1.13      pazsan    179: #endif
1.181     anton     180: #ifndef MAP_NORESERVE
                    181: #define MAP_NORESERVE 0
                    182: #endif
1.183     pazsan    183: /* IF you have an old Cygwin, this may help:
1.182     pazsan    184: #ifdef __CYGWIN__
                    185: #define MAP_NORESERVE 0
                    186: #endif
1.183     pazsan    187: */
1.181     anton     188: static int map_noreserve=MAP_NORESERVE;
1.31      pazsan    189: 
1.167     anton     190: #define CODE_BLOCK_SIZE (512*1024) /* !! overflow handling for -native */
1.48      anton     191: Address code_area=0;
1.73      anton     192: Cell code_area_size = CODE_BLOCK_SIZE;
1.211     anton     193: Address code_here; /* does for code-area what HERE does for the dictionary */
1.100     anton     194: Address start_flush=NULL; /* start of unflushed code */
1.74      anton     195: Cell last_jump=0; /* if the last prim was compiled without jump, this
                    196:                      is it's number, otherwise this contains 0 */
1.48      anton     197: 
1.60      anton     198: static int no_super=0;   /* true if compile_prim should not fuse prims */
1.81      anton     199: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
                    200:                                             dynamically */
1.110     anton     201: static int print_metrics=0; /* if true, print metrics on exit */
1.194     anton     202: static int static_super_number = 10000; /* number of ss used if available */
1.152     anton     203: #define MAX_STATE 9 /* maximum number of states */
1.125     anton     204: static int maxstates = MAX_STATE; /* number of states for stack caching */
1.110     anton     205: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
1.144     pazsan    206: static int diag = 0; /* if true: print diagnostic informations */
1.158     anton     207: static int tpa_noequiv = 0;     /* if true: no state equivalence checking */
                    208: static int tpa_noautomaton = 0; /* if true: no tree parsing automaton */
                    209: static int tpa_trace = 0; /* if true: data for line graph of new states etc. */
1.189     anton     210: static int print_sequences = 0; /* print primitive sequences for optimization */
1.144     pazsan    211: static int relocs = 0;
                    212: static int nonrelocs = 0;
1.60      anton     213: 
1.30      pazsan    214: #ifdef HAS_DEBUG
1.68      anton     215: int debug=0;
1.190     anton     216: # define debugp(x...) do { if (debug) fprintf(x); } while (0)
1.31      pazsan    217: #else
                    218: # define perror(x...)
                    219: # define fprintf(x...)
1.144     pazsan    220: # define debugp(x...)
1.30      pazsan    221: #endif
1.31      pazsan    222: 
1.24      anton     223: ImageHeader *gforth_header;
1.43      anton     224: Label *vm_prims;
1.53      anton     225: #ifdef DOUBLY_INDIRECT
                    226: Label *xts; /* same content as vm_prims, but should only be used for xts */
                    227: #endif
1.1       anton     228: 
1.125     anton     229: #ifndef NO_DYNAMIC
1.186     anton     230: #ifndef CODE_ALIGNMENT
1.185     anton     231: #define CODE_ALIGNMENT 0
                    232: #endif
                    233: 
1.125     anton     234: #define MAX_IMMARGS 2
                    235: 
                    236: typedef struct {
                    237:   Label start; /* NULL if not relocatable */
                    238:   Cell length; /* only includes the jump iff superend is true*/
                    239:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
                    240:   char superend; /* true if primitive ends superinstruction, i.e.,
                    241:                      unconditional branch, execute, etc. */
                    242:   Cell nimmargs;
                    243:   struct immarg {
                    244:     Cell offset; /* offset of immarg within prim */
                    245:     char rel;    /* true if immarg is relative */
                    246:   } immargs[MAX_IMMARGS];
                    247: } PrimInfo;
                    248: 
                    249: PrimInfo *priminfos;
                    250: PrimInfo **decomp_prims;
                    251: 
1.139     anton     252: const char const* const prim_names[]={
                    253: #include PRIM_NAMES_I
                    254: };
                    255: 
1.148     anton     256: void init_ss_cost(void);
                    257: 
1.125     anton     258: static int is_relocatable(int p)
                    259: {
                    260:   return !no_dynamic && priminfos[p].start != NULL;
                    261: }
                    262: #else /* defined(NO_DYNAMIC) */
                    263: static int is_relocatable(int p)
                    264: {
                    265:   return 0;
                    266: }
                    267: #endif /* defined(NO_DYNAMIC) */
                    268: 
1.30      pazsan    269: #ifdef MEMCMP_AS_SUBROUTINE
                    270: int gforth_memcmp(const char * s1, const char * s2, size_t n)
                    271: {
                    272:   return memcmp(s1, s2, n);
                    273: }
                    274: #endif
                    275: 
1.125     anton     276: static Cell max(Cell a, Cell b)
                    277: {
                    278:   return a>b?a:b;
                    279: }
                    280: 
                    281: static Cell min(Cell a, Cell b)
                    282: {
                    283:   return a<b?a:b;
                    284: }
                    285: 
1.175     pazsan    286: #ifndef STANDALONE
1.1       anton     287: /* image file format:
1.15      pazsan    288:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
1.1       anton     289:  *   padding to a multiple of 8
1.84      anton     290:  *   magic: "Gforth3x" means format 0.6,
1.15      pazsan    291:  *              where x is a byte with
                    292:  *              bit 7:   reserved = 0
                    293:  *              bit 6:5: address unit size 2^n octets
                    294:  *              bit 4:3: character size 2^n octets
                    295:  *              bit 2:1: cell size 2^n octets
                    296:  *              bit 0:   endian, big=0, little=1.
                    297:  *  The magic are always 8 octets, no matter what the native AU/character size is
1.1       anton     298:  *  padding to max alignment (no padding necessary on current machines)
1.24      anton     299:  *  ImageHeader structure (see forth.h)
1.1       anton     300:  *  data (size in ImageHeader.image_size)
                    301:  *  tags ((if relocatable, 1 bit/data cell)
                    302:  *
                    303:  * tag==1 means that the corresponding word is an address;
                    304:  * If the word is >=0, the address is within the image;
                    305:  * addresses within the image are given relative to the start of the image.
                    306:  * If the word =-1 (CF_NIL), the address is NIL,
                    307:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                    308:  * If the word =CF(DODOES), it's a DOES> CFA
                    309:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                    310:  *                                     possibly containing a jump to dodoes)
1.51      anton     311:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
                    312:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
                    313:  *                                        it's the threaded code of a primitive
1.85      pazsan    314:  * bits 13..9 of a primitive token state which group the primitive belongs to,
                    315:  * bits 8..0 of a primitive token index into the group
1.1       anton     316:  */
                    317: 
1.115     pazsan    318: Cell groups[32] = {
1.85      pazsan    319:   0,
1.121     anton     320:   0
1.90      anton     321: #undef GROUP
1.115     pazsan    322: #undef GROUPADD
                    323: #define GROUPADD(n) +n
                    324: #define GROUP(x, n) , 0
1.126     anton     325: #include PRIM_GRP_I
1.90      anton     326: #undef GROUP
1.115     pazsan    327: #undef GROUPADD
1.85      pazsan    328: #define GROUP(x, n)
1.115     pazsan    329: #define GROUPADD(n)
1.85      pazsan    330: };
                    331: 
1.161     pazsan    332: static unsigned char *branch_targets(Cell *image, const unsigned char *bitstring,
1.125     anton     333:                              int size, Cell base)
                    334:      /* produce a bitmask marking all the branch targets */
                    335: {
1.130     anton     336:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
1.125     anton     337:   Cell token;
                    338:   unsigned char bits;
1.130     anton     339:   unsigned char *result=malloc(steps);
                    340: 
                    341:   memset(result, 0, steps);
                    342:   for(k=0; k<steps; k++) {
1.125     anton     343:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.130     anton     344:       if(bits & (1U << (RELINFOBITS-1))) {
                    345:        assert(i*sizeof(Cell) < size);
1.125     anton     346:         token=image[i];
                    347:        if (token>=base) { /* relocatable address */
                    348:          UCell bitnum=(token-base)/sizeof(Cell);
1.154     anton     349:          if (bitnum/RELINFOBITS < (UCell)steps)
                    350:            result[bitnum/RELINFOBITS] |= 1U << ((~bitnum)&(RELINFOBITS-1));
1.125     anton     351:        }
                    352:       }
                    353:     }
                    354:   }
                    355:   return result;
                    356: }
                    357: 
1.162     pazsan    358: void gforth_relocate(Cell *image, const Char *bitstring, 
                    359:                     UCell size, Cell base, Label symbols[])
1.1       anton     360: {
1.130     anton     361:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
1.11      pazsan    362:   Cell token;
1.1       anton     363:   char bits;
1.37      anton     364:   Cell max_symbols;
1.46      jwilke    365:   /* 
1.85      pazsan    366:    * A virtual start address that's the real start address minus 
1.46      jwilke    367:    * the one in the image 
                    368:    */
1.45      jwilke    369:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
1.125     anton     370:   unsigned char *targets = branch_targets(image, bitstring, size, base);
1.1       anton     371: 
1.85      pazsan    372:   /* group index into table */
1.115     pazsan    373:   if(groups[31]==0) {
                    374:     int groupsum=0;
                    375:     for(i=0; i<32; i++) {
                    376:       groupsum += groups[i];
                    377:       groups[i] = groupsum;
                    378:       /* printf("group[%d]=%d\n",i,groupsum); */
                    379:     }
                    380:     i=0;
                    381:   }
1.46      jwilke    382:   
                    383: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
1.37      anton     384:   
1.121     anton     385:   for (max_symbols=0; symbols[max_symbols]!=0; max_symbols++)
1.37      anton     386:     ;
1.47      anton     387:   max_symbols--;
1.35      pazsan    388: 
1.130     anton     389:   for(k=0; k<steps; k++) {
1.13      pazsan    390:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.1       anton     391:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
1.130     anton     392:       if(bits & (1U << (RELINFOBITS-1))) {
                    393:        assert(i*sizeof(Cell) < size);
1.35      pazsan    394:        /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
1.45      jwilke    395:         token=image[i];
1.85      pazsan    396:        if(token<0) {
                    397:          int group = (-token & 0x3E00) >> 9;
                    398:          if(group == 0) {
                    399:            switch(token|0x4000) {
1.1       anton     400:            case CF_NIL      : image[i]=0; break;
                    401: #if !defined(DOUBLY_INDIRECT)
                    402:            case CF(DOCOL)   :
                    403:            case CF(DOVAR)   :
                    404:            case CF(DOCON)   :
1.188     pazsan    405:            case CF(DOVAL)   :
1.1       anton     406:            case CF(DOUSER)  : 
                    407:            case CF(DODEFER) : 
1.11      pazsan    408:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
1.92      anton     409:            case CF(DOESJUMP): image[i]=0; break;
1.1       anton     410: #endif /* !defined(DOUBLY_INDIRECT) */
                    411:            case CF(DODOES)  :
1.45      jwilke    412:              MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
1.1       anton     413:              break;
1.85      pazsan    414:            default          : /* backward compatibility */
1.56      anton     415: /*           printf("Code field generation image[%x]:=CFA(%x)\n",
1.1       anton     416:                     i, CF(image[i])); */
1.55      anton     417:              if (CF((token | 0x4000))<max_symbols) {
1.56      anton     418:                image[i]=(Cell)CFA(CF(token));
                    419: #ifdef DIRECT_THREADED
1.125     anton     420:                if ((token & 0x4000) == 0) { /* threade code, no CFA */
                    421:                  if (targets[k] & (1U<<(RELINFOBITS-1-j)))
                    422:                    compile_prim1(0);
1.70      anton     423:                  compile_prim1(&image[i]);
1.125     anton     424:                }
1.56      anton     425: #endif
1.55      anton     426:              } else
1.115     pazsan    427:                fprintf(stderr,"Primitive %ld used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n",(long)CF(token),(long)&image[i], i, PACKAGE_VERSION);
1.1       anton     428:            }
1.85      pazsan    429:          } else {
                    430:            int tok = -token & 0x1FF;
                    431:            if (tok < (groups[group+1]-groups[group])) {
                    432: #if defined(DOUBLY_INDIRECT)
                    433:              image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
                    434: #else
                    435:              image[i]=(Cell)CFA((groups[group]+tok));
                    436: #endif
                    437: #ifdef DIRECT_THREADED
1.125     anton     438:              if ((token & 0x4000) == 0) { /* threade code, no CFA */
                    439:                if (targets[k] & (1U<<(RELINFOBITS-1-j)))
                    440:                  compile_prim1(0);
1.85      pazsan    441:                compile_prim1(&image[i]);
1.125     anton     442:              }
1.85      pazsan    443: #endif
                    444:            } else
1.115     pazsan    445:              fprintf(stderr,"Primitive %lx, %d of group %d used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n", (long)-token, tok, group, (long)&image[i],i,PACKAGE_VERSION);
1.85      pazsan    446:          }
                    447:        } else {
1.101     anton     448:           /* if base is > 0: 0 is a null reference so don't adjust*/
1.45      jwilke    449:           if (token>=base) {
                    450:             image[i]+=(Cell)start;
                    451:           }
1.46      jwilke    452:         }
1.1       anton     453:       }
                    454:     }
1.31      pazsan    455:   }
1.125     anton     456:   free(targets);
1.70      anton     457:   finish_code();
1.26      jwilke    458:   ((ImageHeader*)(image))->base = (Address) image;
1.1       anton     459: }
                    460: 
1.162     pazsan    461: #ifndef DOUBLY_INDIRECT
1.161     pazsan    462: static UCell checksum(Label symbols[])
1.1       anton     463: {
                    464:   UCell r=PRIM_VERSION;
                    465:   Cell i;
                    466: 
                    467:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    468:     r ^= (UCell)(symbols[i]);
                    469:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    470:   }
                    471: #ifdef DIRECT_THREADED
                    472:   /* we have to consider all the primitives */
                    473:   for (; symbols[i]!=(Label)0; i++) {
                    474:     r ^= (UCell)(symbols[i]);
                    475:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    476:   }
                    477: #else
                    478:   /* in indirect threaded code all primitives are accessed through the
                    479:      symbols table, so we just have to put the base address of symbols
                    480:      in the checksum */
                    481:   r ^= (UCell)symbols;
                    482: #endif
                    483:   return r;
                    484: }
1.162     pazsan    485: #endif
1.1       anton     486: 
1.161     pazsan    487: static Address verbose_malloc(Cell size)
1.3       anton     488: {
                    489:   Address r;
                    490:   /* leave a little room (64B) for stack underflows */
                    491:   if ((r = malloc(size+64))==NULL) {
                    492:     perror(progname);
                    493:     exit(1);
                    494:   }
                    495:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
1.144     pazsan    496:   debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
1.3       anton     497:   return r;
                    498: }
                    499: 
1.213     anton     500: static void *next_address=0;
1.161     pazsan    501: static void after_alloc(Address r, Cell size)
1.33      anton     502: {
                    503:   if (r != (Address)-1) {
1.144     pazsan    504:     debugp(stderr, "success, address=$%lx\n", (long) r);
1.173     anton     505: #if 0
                    506:     /* not needed now that we protect the stacks with mprotect */
1.33      anton     507:     if (pagesize != 1)
                    508:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
1.173     anton     509: #endif
1.33      anton     510:   } else {
1.144     pazsan    511:     debugp(stderr, "failed: %s\n", strerror(errno));
1.33      anton     512:   }
                    513: }
                    514: 
1.34      anton     515: #ifndef MAP_FAILED
                    516: #define MAP_FAILED ((Address) -1)
                    517: #endif
                    518: #ifndef MAP_FILE
                    519: # define MAP_FILE 0
                    520: #endif
                    521: #ifndef MAP_PRIVATE
                    522: # define MAP_PRIVATE 0
                    523: #endif
1.218   ! anton     524: #ifndef PROT_NONE
        !           525: # define PROT_NONE 0
        !           526: #endif
1.91      anton     527: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
                    528: # define MAP_ANON MAP_ANONYMOUS
                    529: #endif
1.34      anton     530: 
                    531: #if defined(HAVE_MMAP)
                    532: static Address alloc_mmap(Cell size)
1.1       anton     533: {
1.213     anton     534:   void *r;
1.1       anton     535: 
                    536: #if defined(MAP_ANON)
1.144     pazsan    537:   debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
1.181     anton     538:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|map_noreserve, -1, 0);
1.1       anton     539: #else /* !defined(MAP_ANON) */
1.17      anton     540:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
                    541:      apparently defaults) */
1.1       anton     542:   static int dev_zero=-1;
                    543: 
                    544:   if (dev_zero == -1)
                    545:     dev_zero = open("/dev/zero", O_RDONLY);
                    546:   if (dev_zero == -1) {
1.34      anton     547:     r = MAP_FAILED;
1.144     pazsan    548:     debugp(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
1.1       anton     549:              strerror(errno));
                    550:   } else {
1.144     pazsan    551:     debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
1.181     anton     552:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE|map_noreserve, dev_zero, 0);
1.1       anton     553:   }
                    554: #endif /* !defined(MAP_ANON) */
1.34      anton     555:   after_alloc(r, size);
                    556:   return r;  
                    557: }
1.172     anton     558: 
1.213     anton     559: static void page_noaccess(void *a)
1.172     anton     560: {
                    561:   /* try mprotect first; with munmap the page might be allocated later */
                    562:   debugp(stderr, "try mprotect(%p,%ld,PROT_NONE); ", a, (long)pagesize);
                    563:   if (mprotect(a, pagesize, PROT_NONE)==0) {
                    564:     debugp(stderr, "ok\n");
                    565:     return;
                    566:   }
                    567:   debugp(stderr, "failed: %s\n", strerror(errno));
                    568:   debugp(stderr, "try munmap(%p,%ld); ", a, (long)pagesize);
                    569:   if (munmap(a,pagesize)==0) {
                    570:     debugp(stderr, "ok\n");
                    571:     return;
                    572:   }
                    573:   debugp(stderr, "failed: %s\n", strerror(errno));
                    574: }  
                    575: 
1.173     anton     576: static size_t wholepage(size_t n)
1.172     anton     577: {
                    578:   return (n+pagesize-1)&~(pagesize-1);
                    579: }
1.34      anton     580: #endif
                    581: 
1.161     pazsan    582: Address gforth_alloc(Cell size)
1.34      anton     583: {
                    584: #if HAVE_MMAP
                    585:   Address r;
                    586: 
                    587:   r=alloc_mmap(size);
1.117     anton     588:   if (r!=(Address)MAP_FAILED)
1.1       anton     589:     return r;
                    590: #endif /* HAVE_MMAP */
1.3       anton     591:   /* use malloc as fallback */
                    592:   return verbose_malloc(size);
1.1       anton     593: }
                    594: 
1.213     anton     595: static void *dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
1.33      anton     596: {
1.213     anton     597:   void *image = MAP_FAILED;
1.33      anton     598: 
1.56      anton     599: #if defined(HAVE_MMAP)
1.33      anton     600:   if (offset==0) {
1.34      anton     601:     image=alloc_mmap(dictsize);
1.213     anton     602:     if (image != (void *)MAP_FAILED) {
                    603:       void *image1;
1.150     anton     604:       debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
1.181     anton     605:       image1 = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE|map_noreserve, fileno(file), 0);
1.150     anton     606:       after_alloc(image1,dictsize);
1.213     anton     607:       if (image1 == (void *)MAP_FAILED)
1.150     anton     608:        goto read_image;
                    609:     }
1.33      anton     610:   }
1.56      anton     611: #endif /* defined(HAVE_MMAP) */
1.213     anton     612:   if (image == (void *)MAP_FAILED) {
1.161     pazsan    613:     image = gforth_alloc(dictsize+offset)+offset;
1.149     anton     614:   read_image:
1.33      anton     615:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
1.34      anton     616:     fread(image, 1, imagesize, file);
1.33      anton     617:   }
                    618:   return image;
                    619: }
1.175     pazsan    620: #endif
1.33      anton     621: 
1.10      pazsan    622: void set_stack_sizes(ImageHeader * header)
                    623: {
                    624:   if (dictsize==0)
                    625:     dictsize = header->dict_size;
                    626:   if (dsize==0)
                    627:     dsize = header->data_stack_size;
                    628:   if (rsize==0)
                    629:     rsize = header->return_stack_size;
                    630:   if (fsize==0)
                    631:     fsize = header->fp_stack_size;
                    632:   if (lsize==0)
                    633:     lsize = header->locals_stack_size;
                    634:   dictsize=maxaligned(dictsize);
                    635:   dsize=maxaligned(dsize);
                    636:   rsize=maxaligned(rsize);
                    637:   lsize=maxaligned(lsize);
                    638:   fsize=maxaligned(fsize);
                    639: }
                    640: 
1.178     pazsan    641: #ifdef STANDALONE
                    642: void alloc_stacks(ImageHeader * h)
                    643: {
                    644: #define SSTACKSIZE 0x200
                    645:   static Cell dstack[SSTACKSIZE+1];
                    646:   static Cell rstack[SSTACKSIZE+1];
                    647: 
                    648:   h->dict_size=dictsize;
                    649:   h->data_stack_size=dsize;
                    650:   h->fp_stack_size=fsize;
                    651:   h->return_stack_size=rsize;
                    652:   h->locals_stack_size=lsize;
                    653: 
                    654:   h->data_stack_base=dstack+SSTACKSIZE;
                    655:   //  h->fp_stack_base=gforth_alloc(fsize);
                    656:   h->return_stack_base=rstack+SSTACKSIZE;
                    657:   //  h->locals_stack_base=gforth_alloc(lsize);
                    658: }
                    659: #else
1.173     anton     660: void alloc_stacks(ImageHeader * h)
1.10      pazsan    661: {
1.173     anton     662:   h->dict_size=dictsize;
                    663:   h->data_stack_size=dsize;
                    664:   h->fp_stack_size=fsize;
                    665:   h->return_stack_size=rsize;
                    666:   h->locals_stack_size=lsize;
1.10      pazsan    667: 
1.176     pazsan    668: #if defined(HAVE_MMAP) && !defined(STANDALONE)
1.172     anton     669:   if (pagesize > 1) {
1.173     anton     670:     size_t p = pagesize;
                    671:     size_t totalsize =
                    672:       wholepage(dsize)+wholepage(fsize)+wholepage(rsize)+wholepage(lsize)+5*p;
1.213     anton     673:     void *a = alloc_mmap(totalsize);
                    674:     if (a != (void *)MAP_FAILED) {
1.173     anton     675:       page_noaccess(a); a+=p; h->  data_stack_base=a; a+=wholepage(dsize);
                    676:       page_noaccess(a); a+=p; h->    fp_stack_base=a; a+=wholepage(fsize);
                    677:       page_noaccess(a); a+=p; h->return_stack_base=a; a+=wholepage(rsize);
                    678:       page_noaccess(a); a+=p; h->locals_stack_base=a; a+=wholepage(lsize);
1.172     anton     679:       page_noaccess(a);
                    680:       debugp(stderr,"stack addresses: d=%p f=%p r=%p l=%p\n",
1.173     anton     681:             h->data_stack_base,
                    682:             h->fp_stack_base,
                    683:             h->return_stack_base,
                    684:             h->locals_stack_base);
1.172     anton     685:       return;
                    686:     }
                    687:   }
                    688: #endif
1.173     anton     689:   h->data_stack_base=gforth_alloc(dsize);
                    690:   h->fp_stack_base=gforth_alloc(fsize);
                    691:   h->return_stack_base=gforth_alloc(rsize);
                    692:   h->locals_stack_base=gforth_alloc(lsize);
1.10      pazsan    693: }
1.178     pazsan    694: #endif
1.10      pazsan    695: 
1.161     pazsan    696: #warning You can ignore the warnings about clobbered variables in gforth_go
1.213     anton     697: int gforth_go(void *image, int stack, Cell *entries)
1.11      pazsan    698: {
1.38      anton     699:   volatile ImageHeader *image_header = (ImageHeader *)image;
1.18      anton     700:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
1.44      pazsan    701:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
1.18      anton     702:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
1.44      pazsan    703: #ifdef GFORTH_DEBUGGING
1.38      anton     704:   volatile Cell *orig_rp0=rp0;
1.44      pazsan    705: #endif
1.18      anton     706:   Address lp0=image_header->locals_stack_base + lsize;
                    707:   Xt *ip0=(Xt *)(image_header->boot_entry);
1.13      pazsan    708: #ifdef SYSSIGNALS
1.11      pazsan    709:   int throw_code;
1.13      pazsan    710: #endif
1.11      pazsan    711: 
                    712:   /* ensure that the cached elements (if any) are accessible */
1.151     anton     713: #if !(defined(GFORTH_DEBUGGING) || defined(INDIRECT_THREADED) || defined(DOUBLY_INDIRECT) || defined(VM_PROFILING))
                    714:   sp0 -= 8; /* make stuff below bottom accessible for stack caching */
1.187     anton     715:   fp0--;
1.151     anton     716: #endif
1.11      pazsan    717:   
                    718:   for(;stack>0;stack--)
1.18      anton     719:     *--sp0=entries[stack-1];
1.11      pazsan    720: 
1.177     pazsan    721: #if defined(SYSSIGNALS) && !defined(STANDALONE)
1.11      pazsan    722:   get_winsize();
                    723:    
                    724:   install_signal_handlers(); /* right place? */
                    725:   
                    726:   if ((throw_code=setjmp(throw_jmp_buf))) {
1.152     anton     727:     static Cell signal_data_stack[24];
                    728:     static Cell signal_return_stack[16];
1.11      pazsan    729:     static Float signal_fp_stack[1];
1.13      pazsan    730: 
1.152     anton     731:     signal_data_stack[15]=throw_code;
1.18      anton     732: 
                    733: #ifdef GFORTH_DEBUGGING
1.144     pazsan    734:     debugp(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
1.97      anton     735:              throw_code, saved_ip, rp);
1.38      anton     736:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
1.18      anton     737:       /* no rstack overflow or underflow */
                    738:       rp0 = rp;
1.63      anton     739:       *--rp0 = (Cell)saved_ip;
1.18      anton     740:     }
                    741:     else /* I love non-syntactic ifdefs :-) */
1.152     anton     742:       rp0 = signal_return_stack+16;
1.97      anton     743: #else  /* !defined(GFORTH_DEBUGGING) */
1.144     pazsan    744:     debugp(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
1.152     anton     745:       rp0 = signal_return_stack+16;
1.97      anton     746: #endif /* !defined(GFORTH_DEBUGGING) */
1.25      anton     747:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
1.11      pazsan    748:     
1.164     pazsan    749:     return((int)(Cell)gforth_engine(image_header->throw_entry, signal_data_stack+15,
1.197     anton     750:                       rp0, signal_fp_stack, 0 sr_call));
1.11      pazsan    751:   }
1.13      pazsan    752: #endif
1.11      pazsan    753: 
1.197     anton     754:   return((int)(Cell)gforth_engine(ip0,sp0,rp0,fp0,lp0 sr_call));
1.11      pazsan    755: }
                    756: 
1.177     pazsan    757: #if !defined(INCLUDE_IMAGE) && !defined(STANDALONE)
1.161     pazsan    758: static void print_sizes(Cell sizebyte)
1.21      anton     759:      /* print size information */
                    760: {
                    761:   static char* endianstring[]= { "   big","little" };
                    762:   
                    763:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
                    764:          endianstring[sizebyte & 1],
                    765:          1 << ((sizebyte >> 1) & 3),
                    766:          1 << ((sizebyte >> 3) & 3),
                    767:          1 << ((sizebyte >> 5) & 3));
                    768: }
                    769: 
1.106     anton     770: /* static superinstruction stuff */
                    771: 
1.141     anton     772: struct cost { /* super_info might be a more accurate name */
1.106     anton     773:   char loads;       /* number of stack loads */
                    774:   char stores;      /* number of stack stores */
                    775:   char updates;     /* number of stack pointer updates */
1.123     anton     776:   char branch;     /* is it a branch (SET_IP) */
1.125     anton     777:   unsigned char state_in;    /* state on entry */
                    778:   unsigned char state_out;   /* state on exit */
1.142     anton     779:   unsigned char imm_ops;     /* number of immediate operands */
1.123     anton     780:   short offset;     /* offset into super2 table */
1.125     anton     781:   unsigned char length;      /* number of components */
1.106     anton     782: };
                    783: 
1.121     anton     784: PrimNum super2[] = {
1.126     anton     785: #include SUPER2_I
1.106     anton     786: };
                    787: 
                    788: struct cost super_costs[] = {
1.126     anton     789: #include COSTS_I
1.106     anton     790: };
                    791: 
1.125     anton     792: struct super_state {
                    793:   struct super_state *next;
                    794:   PrimNum super;
                    795: };
                    796: 
1.106     anton     797: #define HASH_SIZE 256
                    798: 
                    799: struct super_table_entry {
                    800:   struct super_table_entry *next;
1.121     anton     801:   PrimNum *start;
1.106     anton     802:   short length;
1.125     anton     803:   struct super_state *ss_list; /* list of supers */
1.106     anton     804: } *super_table[HASH_SIZE];
                    805: int max_super=2;
                    806: 
1.125     anton     807: struct super_state *state_transitions=NULL;
                    808: 
1.161     pazsan    809: static int hash_super(PrimNum *start, int length)
1.106     anton     810: {
                    811:   int i, r;
                    812:   
                    813:   for (i=0, r=0; i<length; i++) {
                    814:     r <<= 1;
                    815:     r += start[i];
                    816:   }
                    817:   return r & (HASH_SIZE-1);
                    818: }
                    819: 
1.161     pazsan    820: static struct super_state **lookup_super(PrimNum *start, int length)
1.106     anton     821: {
                    822:   int hash=hash_super(start,length);
                    823:   struct super_table_entry *p = super_table[hash];
                    824: 
1.125     anton     825:   /* assert(length >= 2); */
1.106     anton     826:   for (; p!=NULL; p = p->next) {
                    827:     if (length == p->length &&
1.121     anton     828:        memcmp((char *)p->start, (char *)start, length*sizeof(PrimNum))==0)
1.125     anton     829:       return &(p->ss_list);
1.106     anton     830:   }
1.125     anton     831:   return NULL;
1.106     anton     832: }
                    833: 
1.161     pazsan    834: static void prepare_super_table()
1.106     anton     835: {
                    836:   int i;
1.109     anton     837:   int nsupers = 0;
1.106     anton     838: 
                    839:   for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
                    840:     struct cost *c = &super_costs[i];
1.125     anton     841:     if ((c->length < 2 || nsupers < static_super_number) &&
                    842:        c->state_in < maxstates && c->state_out < maxstates) {
                    843:       struct super_state **ss_listp= lookup_super(super2+c->offset, c->length);
                    844:       struct super_state *ss = malloc(sizeof(struct super_state));
                    845:       ss->super= i;
                    846:       if (c->offset==N_noop && i != N_noop) {
                    847:        if (is_relocatable(i)) {
                    848:          ss->next = state_transitions;
                    849:          state_transitions = ss;
                    850:        }
                    851:       } else if (ss_listp != NULL) {
                    852:        ss->next = *ss_listp;
                    853:        *ss_listp = ss;
                    854:       } else {
                    855:        int hash = hash_super(super2+c->offset, c->length);
                    856:        struct super_table_entry **p = &super_table[hash];
                    857:        struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
                    858:        ss->next = NULL;
                    859:        e->next = *p;
                    860:        e->start = super2 + c->offset;
                    861:        e->length = c->length;
                    862:        e->ss_list = ss;
                    863:        *p = e;
                    864:       }
1.106     anton     865:       if (c->length > max_super)
                    866:        max_super = c->length;
1.125     anton     867:       if (c->length >= 2)
                    868:        nsupers++;
1.106     anton     869:     }
                    870:   }
1.144     pazsan    871:   debugp(stderr, "Using %d static superinsts\n", nsupers);
1.195     anton     872:   if (nsupers>0 && !tpa_noautomaton && !tpa_noequiv) {
                    873:     /* Currently these two things don't work together; see Section 3.2
                    874:        of <http://www.complang.tuwien.ac.at/papers/ertl+06pldi.ps.gz>,
                    875:        in particular Footnote 6 for the reason; hmm, we should be able
                    876:        to use an automaton without state equivalence, but that costs
                    877:        significant space so we only do it if the user explicitly
                    878:        disables state equivalence. */
                    879:     debugp(stderr, "Disabling tpa-automaton, because nsupers>0 and state equivalence is enabled.\n");
1.218   ! anton     880:     tpa_noautomaton = 1;
1.194     anton     881:   }
1.106     anton     882: }
                    883: 
                    884: /* dynamic replication/superinstruction stuff */
                    885: 
1.69      anton     886: #ifndef NO_DYNAMIC
1.161     pazsan    887: static int compare_priminfo_length(const void *_a, const void *_b)
1.76      anton     888: {
1.90      anton     889:   PrimInfo **a = (PrimInfo **)_a;
                    890:   PrimInfo **b = (PrimInfo **)_b;
1.77      anton     891:   Cell diff = (*a)->length - (*b)->length;
                    892:   if (diff)
                    893:     return diff;
                    894:   else /* break ties by start address; thus the decompiler produces
                    895:           the earliest primitive with the same code (e.g. noop instead
                    896:           of (char) and @ instead of >code-address */
                    897:     return (*b)->start - (*a)->start;
1.76      anton     898: }
1.112     anton     899: #endif /* !defined(NO_DYNAMIC) */
1.76      anton     900: 
1.125     anton     901: static char MAYBE_UNUSED superend[]={
1.126     anton     902: #include PRIM_SUPEREND_I
1.106     anton     903: };
1.107     anton     904: 
                    905: Cell npriminfos=0;
1.76      anton     906: 
1.146     anton     907: Label goto_start;
                    908: Cell goto_len;
                    909: 
1.162     pazsan    910: #ifndef NO_DYNAMIC
1.161     pazsan    911: static int compare_labels(const void *pa, const void *pb)
1.113     anton     912: {
1.114     anton     913:   Label a = *(Label *)pa;
                    914:   Label b = *(Label *)pb;
                    915:   return a-b;
                    916: }
1.162     pazsan    917: #endif
1.113     anton     918: 
1.161     pazsan    919: static Label bsearch_next(Label key, Label *a, UCell n)
1.114     anton     920:      /* a is sorted; return the label >=key that is the closest in a;
                    921:         return NULL if there is no label in a >=key */
                    922: {
                    923:   int mid = (n-1)/2;
                    924:   if (n<1)
                    925:     return NULL;
                    926:   if (n == 1) {
                    927:     if (a[0] < key)
                    928:       return NULL;
                    929:     else
                    930:       return a[0];
                    931:   }
                    932:   if (a[mid] < key)
                    933:     return bsearch_next(key, a+mid+1, n-mid-1);
                    934:   else
                    935:     return bsearch_next(key, a, mid+1);
1.113     anton     936: }
                    937: 
1.161     pazsan    938: static void check_prims(Label symbols1[])
1.47      anton     939: {
                    940:   int i;
1.90      anton     941: #ifndef NO_DYNAMIC
1.146     anton     942:   Label *symbols2, *symbols3, *ends1, *ends1j, *ends1jsorted, *goto_p;
1.119     anton     943:   int nends1j;
1.90      anton     944: #endif
1.47      anton     945: 
1.66      anton     946:   if (debug)
                    947: #ifdef __VERSION__
                    948:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
                    949: #else
                    950: #define xstr(s) str(s)
                    951: #define str(s) #s
                    952:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
                    953: #endif
1.121     anton     954:   for (i=0; symbols1[i]!=0; i++)
1.47      anton     955:     ;
1.55      anton     956:   npriminfos = i;
1.70      anton     957:   
                    958: #ifndef NO_DYNAMIC
1.66      anton     959:   if (no_dynamic)
                    960:     return;
1.197     anton     961:   symbols2=gforth_engine2(0,0,0,0,0 sr_call);
1.70      anton     962: #if NO_IP
1.197     anton     963:   symbols3=gforth_engine3(0,0,0,0,0 sr_call);
1.70      anton     964: #else
                    965:   symbols3=symbols1;
                    966: #endif
1.121     anton     967:   ends1 = symbols1+i+1;
1.119     anton     968:   ends1j =   ends1+i;
1.146     anton     969:   goto_p = ends1j+i+1; /* goto_p[0]==before; ...[1]==after;*/
1.121     anton     970:   nends1j = i+1;
1.119     anton     971:   ends1jsorted = (Label *)alloca(nends1j*sizeof(Label));
                    972:   memcpy(ends1jsorted,ends1j,nends1j*sizeof(Label));
                    973:   qsort(ends1jsorted, nends1j, sizeof(Label), compare_labels);
1.146     anton     974: 
                    975:   /* check whether the "goto *" is relocatable */
                    976:   goto_len = goto_p[1]-goto_p[0];
                    977:   debugp(stderr, "goto * %p %p len=%ld\n",
1.190     anton     978:         goto_p[0],symbols2[goto_p-symbols1],(long)goto_len);
1.146     anton     979:   if (memcmp(goto_p[0],symbols2[goto_p-symbols1],goto_len)!=0) { /* unequal */
                    980:     no_dynamic=1;
                    981:     debugp(stderr,"  not relocatable, disabling dynamic code generation\n");
1.148     anton     982:     init_ss_cost();
1.146     anton     983:     return;
                    984:   }
                    985:   goto_start = goto_p[0];
1.113     anton     986:   
1.47      anton     987:   priminfos = calloc(i,sizeof(PrimInfo));
1.121     anton     988:   for (i=0; symbols1[i]!=0; i++) {
1.70      anton     989:     int prim_len = ends1[i]-symbols1[i];
1.47      anton     990:     PrimInfo *pi=&priminfos[i];
1.154     anton     991:     struct cost *sc=&super_costs[i];
1.70      anton     992:     int j=0;
                    993:     char *s1 = (char *)symbols1[i];
                    994:     char *s2 = (char *)symbols2[i];
                    995:     char *s3 = (char *)symbols3[i];
1.119     anton     996:     Label endlabel = bsearch_next(symbols1[i]+1,ends1jsorted,nends1j);
1.70      anton     997: 
                    998:     pi->start = s1;
1.121     anton     999:     pi->superend = superend[i]|no_super;
1.147     anton    1000:     pi->length = prim_len;
1.113     anton    1001:     pi->restlength = endlabel - symbols1[i] - pi->length;
1.70      anton    1002:     pi->nimmargs = 0;
1.144     pazsan   1003:     relocs++;
1.190     anton    1004: #if defined(BURG_FORMAT)
                   1005:     { /* output as burg-style rules */
                   1006:       int p=super_costs[i].offset;
                   1007:       if (p==N_noop)
                   1008:        debugp(stderr, "S%d: S%d = %d (%d);", sc->state_in, sc->state_out, i+1, pi->length);
                   1009:       else
                   1010:        debugp(stderr, "S%d: op%d(S%d) = %d (%d);", sc->state_in, p, sc->state_out, i+1, pi->length);
                   1011:     }
                   1012: #else
1.154     anton    1013:     debugp(stderr, "%-15s %d-%d %4d %p %p %p len=%3ld rest=%2ld send=%1d",
                   1014:           prim_names[i], sc->state_in, sc->state_out,
                   1015:           i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength),
                   1016:           pi->superend);
1.190     anton    1017: #endif
1.114     anton    1018:     if (endlabel == NULL) {
                   1019:       pi->start = NULL; /* not relocatable */
1.122     anton    1020:       if (pi->length<0) pi->length=100;
1.190     anton    1021: #ifndef BURG_FORMAT
1.144     pazsan   1022:       debugp(stderr,"\n   non_reloc: no J label > start found\n");
1.190     anton    1023: #endif
1.144     pazsan   1024:       relocs--;
                   1025:       nonrelocs++;
1.114     anton    1026:       continue;
                   1027:     }
                   1028:     if (ends1[i] > endlabel && !pi->superend) {
1.113     anton    1029:       pi->start = NULL; /* not relocatable */
1.122     anton    1030:       pi->length = endlabel-symbols1[i];
1.190     anton    1031: #ifndef BURG_FORMAT
1.144     pazsan   1032:       debugp(stderr,"\n   non_reloc: there is a J label before the K label (restlength<0)\n");
1.190     anton    1033: #endif
1.144     pazsan   1034:       relocs--;
                   1035:       nonrelocs++;
1.113     anton    1036:       continue;
                   1037:     }
1.114     anton    1038:     if (ends1[i] < pi->start && !pi->superend) {
1.113     anton    1039:       pi->start = NULL; /* not relocatable */
1.122     anton    1040:       pi->length = endlabel-symbols1[i];
1.190     anton    1041: #ifndef BURG_FORMAT
1.144     pazsan   1042:       debugp(stderr,"\n   non_reloc: K label before I label (length<0)\n");
1.190     anton    1043: #endif
1.144     pazsan   1044:       relocs--;
                   1045:       nonrelocs++;
1.113     anton    1046:       continue;
                   1047:     }
1.138     anton    1048:     assert(pi->length>=0);
1.113     anton    1049:     assert(pi->restlength >=0);
1.74      anton    1050:     while (j<(pi->length+pi->restlength)) {
1.70      anton    1051:       if (s1[j]==s3[j]) {
                   1052:        if (s1[j] != s2[j]) {
                   1053:          pi->start = NULL; /* not relocatable */
1.190     anton    1054: #ifndef BURG_FORMAT
1.144     pazsan   1055:          debugp(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
1.190     anton    1056: #endif
1.74      anton    1057:          /* assert(j<prim_len); */
1.144     pazsan   1058:          relocs--;
                   1059:          nonrelocs++;
1.70      anton    1060:          break;
                   1061:        }
                   1062:        j++;
                   1063:       } else {
                   1064:        struct immarg *ia=&pi->immargs[pi->nimmargs];
                   1065: 
                   1066:        pi->nimmargs++;
                   1067:        ia->offset=j;
                   1068:        if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
                   1069:          ia->rel=0;
1.144     pazsan   1070:          debugp(stderr,"\n   absolute immarg: offset %3d",j);
1.70      anton    1071:        } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
                   1072:                   symbols1[DOESJUMP+1]) {
                   1073:          ia->rel=1;
1.144     pazsan   1074:          debugp(stderr,"\n   relative immarg: offset %3d",j);
1.70      anton    1075:        } else {
                   1076:          pi->start = NULL; /* not relocatable */
1.190     anton    1077: #ifndef BURG_FORMAT
1.144     pazsan   1078:          debugp(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
1.190     anton    1079: #endif
1.74      anton    1080:          /* assert(j<prim_len);*/
1.144     pazsan   1081:          relocs--;
                   1082:          nonrelocs++;
1.70      anton    1083:          break;
                   1084:        }
                   1085:        j+=4;
1.47      anton    1086:       }
                   1087:     }
1.144     pazsan   1088:     debugp(stderr,"\n");
1.70      anton    1089:   }
1.76      anton    1090:   decomp_prims = calloc(i,sizeof(PrimInfo *));
                   1091:   for (i=DOESJUMP+1; i<npriminfos; i++)
                   1092:     decomp_prims[i] = &(priminfos[i]);
                   1093:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
                   1094:        compare_priminfo_length);
1.70      anton    1095: #endif
                   1096: }
                   1097: 
1.161     pazsan   1098: static void flush_to_here(void)
1.74      anton    1099: {
1.93      anton    1100: #ifndef NO_DYNAMIC
1.100     anton    1101:   if (start_flush)
1.210     anton    1102:     FLUSH_ICACHE((caddr_t)start_flush, code_here-start_flush);
1.74      anton    1103:   start_flush=code_here;
1.93      anton    1104: #endif
1.74      anton    1105: }
                   1106: 
1.209     anton    1107: static void MAYBE_UNUSED align_code(void)
1.185     anton    1108:      /* align code_here on some platforms */
                   1109: {
                   1110: #ifndef NO_DYNAMIC
1.186     anton    1111: #if defined(CODE_PADDING)
1.185     anton    1112:   Cell alignment = CODE_ALIGNMENT;
1.186     anton    1113:   static char nops[] = CODE_PADDING;
                   1114:   UCell maxpadding=MAX_PADDING;
1.185     anton    1115:   UCell offset = ((UCell)code_here)&(alignment-1);
                   1116:   UCell length = alignment-offset;
1.186     anton    1117:   if (length <= maxpadding) {
                   1118:     memcpy(code_here,nops+offset,length);
1.185     anton    1119:     code_here += length;
                   1120:   }
1.186     anton    1121: #endif /* defined(CODE_PADDING) */
1.185     anton    1122: #endif /* defined(NO_DYNAMIC */
                   1123: }  
                   1124: 
1.93      anton    1125: #ifndef NO_DYNAMIC
1.161     pazsan   1126: static void append_jump(void)
1.74      anton    1127: {
                   1128:   if (last_jump) {
                   1129:     PrimInfo *pi = &priminfos[last_jump];
                   1130:     
                   1131:     memcpy(code_here, pi->start+pi->length, pi->restlength);
                   1132:     code_here += pi->restlength;
1.147     anton    1133:     memcpy(code_here, goto_start, goto_len);
                   1134:     code_here += goto_len;
1.185     anton    1135:     align_code();
1.74      anton    1136:     last_jump=0;
                   1137:   }
                   1138: }
                   1139: 
1.75      anton    1140: /* Gforth remembers all code blocks in this list.  On forgetting (by
                   1141: executing a marker) the code blocks are not freed (because Gforth does
                   1142: not remember how they were allocated; hmm, remembering that might be
                   1143: easier and cleaner).  Instead, code_here etc. are reset to the old
                   1144: value, and the "forgotten" code blocks are reused when they are
                   1145: needed. */
                   1146: 
                   1147: struct code_block_list {
                   1148:   struct code_block_list *next;
                   1149:   Address block;
                   1150:   Cell size;
                   1151: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
                   1152: 
1.161     pazsan   1153: static Address append_prim(Cell p)
1.74      anton    1154: {
                   1155:   PrimInfo *pi = &priminfos[p];
                   1156:   Address old_code_here = code_here;
                   1157: 
1.185     anton    1158:   if (code_area+code_area_size < code_here+pi->length+pi->restlength+goto_len+CODE_ALIGNMENT) {
1.75      anton    1159:     struct code_block_list *p;
1.74      anton    1160:     append_jump();
1.93      anton    1161:     flush_to_here();
1.75      anton    1162:     if (*next_code_blockp == NULL) {
1.161     pazsan   1163:       code_here = start_flush = code_area = gforth_alloc(code_area_size);
1.75      anton    1164:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
                   1165:       *next_code_blockp = p;
                   1166:       p->next = NULL;
                   1167:       p->block = code_here;
                   1168:       p->size = code_area_size;
                   1169:     } else {
                   1170:       p = *next_code_blockp;
                   1171:       code_here = start_flush = code_area = p->block;
                   1172:     }
1.74      anton    1173:     old_code_here = code_here;
1.75      anton    1174:     next_code_blockp = &(p->next);
1.74      anton    1175:   }
                   1176:   memcpy(code_here, pi->start, pi->length);
                   1177:   code_here += pi->length;
                   1178:   return old_code_here;
                   1179: }
                   1180: #endif
1.75      anton    1181: 
                   1182: int forget_dyncode(Address code)
                   1183: {
                   1184: #ifdef NO_DYNAMIC
                   1185:   return -1;
                   1186: #else
                   1187:   struct code_block_list *p, **pp;
                   1188: 
                   1189:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
                   1190:     if (code >= p->block && code < p->block+p->size) {
                   1191:       next_code_blockp = &(p->next);
                   1192:       code_here = start_flush = code;
                   1193:       code_area = p->block;
                   1194:       last_jump = 0;
                   1195:       return -1;
                   1196:     }
                   1197:   }
1.78      anton    1198:   return -no_dynamic;
1.75      anton    1199: #endif /* !defined(NO_DYNAMIC) */
                   1200: }
                   1201: 
1.161     pazsan   1202: static long dyncodesize(void)
1.104     anton    1203: {
                   1204: #ifndef NO_DYNAMIC
1.106     anton    1205:   struct code_block_list *p;
1.104     anton    1206:   long size=0;
                   1207:   for (p=code_block_list; p!=NULL; p=p->next) {
                   1208:     if (code_here >= p->block && code_here < p->block+p->size)
                   1209:       return size + (code_here - p->block);
                   1210:     else
                   1211:       size += p->size;
                   1212:   }
                   1213: #endif /* !defined(NO_DYNAMIC) */
                   1214:   return 0;
                   1215: }
                   1216: 
1.90      anton    1217: Label decompile_code(Label _code)
1.75      anton    1218: {
1.76      anton    1219: #ifdef NO_DYNAMIC
1.90      anton    1220:   return _code;
1.76      anton    1221: #else /* !defined(NO_DYNAMIC) */
                   1222:   Cell i;
1.77      anton    1223:   struct code_block_list *p;
1.90      anton    1224:   Address code=_code;
1.76      anton    1225: 
1.77      anton    1226:   /* first, check if we are in code at all */
                   1227:   for (p = code_block_list;; p = p->next) {
                   1228:     if (p == NULL)
                   1229:       return code;
                   1230:     if (code >= p->block && code < p->block+p->size)
                   1231:       break;
                   1232:   }
1.76      anton    1233:   /* reverse order because NOOP might match other prims */
                   1234:   for (i=npriminfos-1; i>DOESJUMP; i--) {
                   1235:     PrimInfo *pi=decomp_prims[i];
                   1236:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
1.121     anton    1237:       return vm_prims[super2[super_costs[pi-priminfos].offset]];
1.118     anton    1238:     /* return pi->start;*/
1.76      anton    1239:   }
                   1240:   return code;
                   1241: #endif /* !defined(NO_DYNAMIC) */
1.75      anton    1242: }
1.74      anton    1243: 
1.70      anton    1244: #ifdef NO_IP
                   1245: int nbranchinfos=0;
                   1246: 
                   1247: struct branchinfo {
1.136     anton    1248:   Label **targetpp; /* **(bi->targetpp) is the target */
1.70      anton    1249:   Cell *addressptr; /* store the target here */
                   1250: } branchinfos[100000];
                   1251: 
                   1252: int ndoesexecinfos=0;
                   1253: struct doesexecinfo {
                   1254:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
1.136     anton    1255:   Label *targetp; /*target for branch (because this is not in threaded code)*/
1.70      anton    1256:   Cell *xt; /* cfa of word whose does-code needs calling */
                   1257: } doesexecinfos[10000];
                   1258: 
1.161     pazsan   1259: static void set_rel_target(Cell *source, Label target)
1.70      anton    1260: {
                   1261:   *source = ((Cell)target)-(((Cell)source)+4);
                   1262: }
                   1263: 
1.161     pazsan   1264: static void register_branchinfo(Label source, Cell *targetpp)
1.70      anton    1265: {
                   1266:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
1.136     anton    1267:   bi->targetpp = (Label **)targetpp;
1.70      anton    1268:   bi->addressptr = (Cell *)source;
                   1269:   nbranchinfos++;
                   1270: }
                   1271: 
1.161     pazsan   1272: static Address compile_prim1arg(PrimNum p, Cell **argp)
1.70      anton    1273: {
1.133     anton    1274:   Address old_code_here=append_prim(p);
1.70      anton    1275: 
1.74      anton    1276:   assert(vm_prims[p]==priminfos[p].start);
1.133     anton    1277:   *argp = (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
                   1278:   return old_code_here;
1.70      anton    1279: }
                   1280: 
1.161     pazsan   1281: static Address compile_call2(Cell *targetpp, Cell **next_code_targetp)
1.70      anton    1282: {
1.73      anton    1283:   PrimInfo *pi = &priminfos[N_call2];
1.74      anton    1284:   Address old_code_here = append_prim(N_call2);
1.70      anton    1285: 
1.134     anton    1286:   *next_code_targetp = (Cell *)(old_code_here + pi->immargs[0].offset);
1.136     anton    1287:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetpp);
1.134     anton    1288:   return old_code_here;
1.70      anton    1289: }
                   1290: #endif
                   1291: 
                   1292: void finish_code(void)
                   1293: {
                   1294: #ifdef NO_IP
                   1295:   Cell i;
                   1296: 
                   1297:   compile_prim1(NULL);
                   1298:   for (i=0; i<ndoesexecinfos; i++) {
                   1299:     struct doesexecinfo *dei = &doesexecinfos[i];
1.136     anton    1300:     dei->targetp = (Label *)DOES_CODE1((dei->xt));
                   1301:     branchinfos[dei->branchinfo].targetpp = &(dei->targetp);
1.70      anton    1302:   }
                   1303:   ndoesexecinfos = 0;
                   1304:   for (i=0; i<nbranchinfos; i++) {
                   1305:     struct branchinfo *bi=&branchinfos[i];
1.136     anton    1306:     set_rel_target(bi->addressptr, **(bi->targetpp));
1.70      anton    1307:   }
                   1308:   nbranchinfos = 0;
1.128     anton    1309: #else
                   1310:   compile_prim1(NULL);
1.48      anton    1311: #endif
1.93      anton    1312:   flush_to_here();
1.48      anton    1313: }
                   1314: 
1.162     pazsan   1315: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1.128     anton    1316: #ifdef NO_IP
1.161     pazsan   1317: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1.128     anton    1318:      /* compile prim #p dynamically (mod flags etc.) and return start
                   1319:        address of generated code for putting it into the threaded
                   1320:        code. This function is only called if all the associated
                   1321:        inline arguments of p are already in place (at tcp[1] etc.) */
                   1322: {
                   1323:   PrimInfo *pi=&priminfos[p];
                   1324:   Cell *next_code_target=NULL;
1.135     anton    1325:   Address codeaddr;
                   1326:   Address primstart;
1.128     anton    1327:   
                   1328:   assert(p<npriminfos);
                   1329:   if (p==N_execute || p==N_perform || p==N_lit_perform) {
1.134     anton    1330:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
1.135     anton    1331:     primstart = append_prim(p);
                   1332:     goto other_prim;
                   1333:   } else if (p==N_call) {
1.136     anton    1334:     codeaddr = compile_call2(tcp+1, &next_code_target);
1.128     anton    1335:   } else if (p==N_does_exec) {
                   1336:     struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1.133     anton    1337:     Cell *arg;
                   1338:     codeaddr = compile_prim1arg(N_lit,&arg);
                   1339:     *arg = (Cell)PFA(tcp[1]);
1.128     anton    1340:     /* we cannot determine the callee now (last_start[1] may be a
                   1341:        forward reference), so just register an arbitrary target, and
                   1342:        register in dei that we need to fix this before resolving
                   1343:        branches */
                   1344:     dei->branchinfo = nbranchinfos;
                   1345:     dei->xt = (Cell *)(tcp[1]);
1.134     anton    1346:     compile_call2(0, &next_code_target);
1.128     anton    1347:   } else if (!is_relocatable(p)) {
1.133     anton    1348:     Cell *branch_target;
                   1349:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
                   1350:     compile_prim1arg(N_branch,&branch_target);
                   1351:     set_rel_target(branch_target,vm_prims[p]);
1.128     anton    1352:   } else {
                   1353:     unsigned j;
1.135     anton    1354: 
                   1355:     codeaddr = primstart = append_prim(p);
                   1356:   other_prim:
1.128     anton    1357:     for (j=0; j<pi->nimmargs; j++) {
                   1358:       struct immarg *ia = &(pi->immargs[j]);
1.136     anton    1359:       Cell *argp = tcp + pi->nimmargs - j;
                   1360:       Cell argval = *argp; /* !! specific to prims */
1.128     anton    1361:       if (ia->rel) { /* !! assumption: relative refs are branches */
1.136     anton    1362:        register_branchinfo(primstart + ia->offset, argp);
1.128     anton    1363:       } else /* plain argument */
1.135     anton    1364:        *(Cell *)(primstart + ia->offset) = argval;
1.128     anton    1365:     }
                   1366:   }
                   1367:   if (next_code_target!=NULL)
                   1368:     *next_code_target = (Cell)code_here;
1.135     anton    1369:   return (Cell)codeaddr;
1.128     anton    1370: }
                   1371: #else /* !defined(NO_IP) */
1.161     pazsan   1372: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1.128     anton    1373:      /* compile prim #p dynamically (mod flags etc.) and return start
                   1374:         address of generated code for putting it into the threaded code */
1.108     anton    1375: {
1.121     anton    1376:   Cell static_prim = (Cell)vm_prims[p];
1.108     anton    1377: #if defined(NO_DYNAMIC)
                   1378:   return static_prim;
                   1379: #else /* !defined(NO_DYNAMIC) */
                   1380:   Address old_code_here;
                   1381: 
                   1382:   if (no_dynamic)
                   1383:     return static_prim;
1.125     anton    1384:   if (p>=npriminfos || !is_relocatable(p)) {
1.108     anton    1385:     append_jump();
                   1386:     return static_prim;
                   1387:   }
                   1388:   old_code_here = append_prim(p);
1.147     anton    1389:   last_jump = p;
                   1390:   if (priminfos[p].superend)
                   1391:     append_jump();
1.108     anton    1392:   return (Cell)old_code_here;
                   1393: #endif  /* !defined(NO_DYNAMIC) */
                   1394: }
1.128     anton    1395: #endif /* !defined(NO_IP) */
1.162     pazsan   1396: #endif
1.70      anton    1397: 
1.109     anton    1398: #ifndef NO_DYNAMIC
1.161     pazsan   1399: static int cost_codesize(int prim)
1.109     anton    1400: {
1.121     anton    1401:   return priminfos[prim].length;
1.109     anton    1402: }
                   1403: #endif
                   1404: 
1.161     pazsan   1405: static int cost_ls(int prim)
1.109     anton    1406: {
                   1407:   struct cost *c = super_costs+prim;
                   1408: 
                   1409:   return c->loads + c->stores;
                   1410: }
                   1411: 
1.161     pazsan   1412: static int cost_lsu(int prim)
1.109     anton    1413: {
                   1414:   struct cost *c = super_costs+prim;
                   1415: 
                   1416:   return c->loads + c->stores + c->updates;
                   1417: }
                   1418: 
1.161     pazsan   1419: static int cost_nexts(int prim)
1.109     anton    1420: {
                   1421:   return 1;
                   1422: }
                   1423: 
                   1424: typedef int Costfunc(int);
                   1425: Costfunc *ss_cost =  /* cost function for optimize_bb */
                   1426: #ifdef NO_DYNAMIC
                   1427: cost_lsu;
                   1428: #else
                   1429: cost_codesize;
                   1430: #endif
                   1431: 
1.110     anton    1432: struct {
                   1433:   Costfunc *costfunc;
                   1434:   char *metricname;
                   1435:   long sum;
                   1436: } cost_sums[] = {
                   1437: #ifndef NO_DYNAMIC
                   1438:   { cost_codesize, "codesize", 0 },
                   1439: #endif
                   1440:   { cost_ls,       "ls",       0 },
                   1441:   { cost_lsu,      "lsu",      0 },
                   1442:   { cost_nexts,    "nexts",    0 }
                   1443: };
                   1444: 
1.148     anton    1445: #ifndef NO_DYNAMIC
                   1446: void init_ss_cost(void) {
                   1447:   if (no_dynamic && ss_cost == cost_codesize) {
                   1448:     ss_cost = cost_nexts;
                   1449:     cost_sums[0] = cost_sums[1]; /* don't use cost_codesize for print-metrics */
                   1450:     debugp(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-nexts\n");
                   1451:   }
                   1452: }
                   1453: #endif
                   1454: 
1.106     anton    1455: #define MAX_BB 128 /* maximum number of instructions in BB */
1.125     anton    1456: #define INF_COST 1000000 /* infinite cost */
                   1457: #define CANONICAL_STATE 0
                   1458: 
                   1459: struct waypoint {
                   1460:   int cost;     /* the cost from here to the end */
                   1461:   PrimNum inst; /* the inst used from here to the next waypoint */
                   1462:   char relocatable; /* the last non-transition was relocatable */
                   1463:   char no_transition; /* don't use the next transition (relocatability)
                   1464:                       * or this transition (does not change state) */
                   1465: };
                   1466: 
1.156     anton    1467: struct tpa_state { /* tree parsing automaton (like) state */
1.155     anton    1468:   /* labeling is back-to-front */
                   1469:   struct waypoint *inst;  /* in front of instruction */
                   1470:   struct waypoint *trans; /* in front of instruction and transition */
                   1471: }; 
                   1472: 
1.156     anton    1473: struct tpa_state *termstate = NULL; /* initialized in loader() */
1.155     anton    1474: 
1.158     anton    1475: /* statistics about tree parsing (lazyburg) stuff */
                   1476: long lb_basic_blocks = 0;
                   1477: long lb_labeler_steps = 0;
                   1478: long lb_labeler_automaton = 0;
                   1479: long lb_labeler_dynprog = 0;
                   1480: long lb_newstate_equiv = 0;
                   1481: long lb_newstate_new = 0;
                   1482: long lb_applicable_base_rules = 0;
                   1483: long lb_applicable_chain_rules = 0;
                   1484: 
1.162     pazsan   1485: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1.161     pazsan   1486: static void init_waypoints(struct waypoint ws[])
1.125     anton    1487: {
                   1488:   int k;
                   1489: 
                   1490:   for (k=0; k<maxstates; k++)
                   1491:     ws[k].cost=INF_COST;
                   1492: }
1.106     anton    1493: 
1.161     pazsan   1494: static struct tpa_state *empty_tpa_state()
1.155     anton    1495: {
1.156     anton    1496:   struct tpa_state *s = malloc(sizeof(struct tpa_state));
1.155     anton    1497: 
1.157     anton    1498:   s->inst  = calloc(maxstates,sizeof(struct waypoint));
1.155     anton    1499:   init_waypoints(s->inst);
1.157     anton    1500:   s->trans = calloc(maxstates,sizeof(struct waypoint));
1.155     anton    1501:   /* init_waypoints(s->trans);*/
                   1502:   return s;
                   1503: }
                   1504: 
1.161     pazsan   1505: static void transitions(struct tpa_state *t)
1.107     anton    1506: {
1.125     anton    1507:   int k;
                   1508:   struct super_state *l;
                   1509:   
                   1510:   for (k=0; k<maxstates; k++) {
1.155     anton    1511:     t->trans[k] = t->inst[k];
                   1512:     t->trans[k].no_transition = 1;
1.125     anton    1513:   }
                   1514:   for (l = state_transitions; l != NULL; l = l->next) {
                   1515:     PrimNum s = l->super;
                   1516:     int jcost;
                   1517:     struct cost *c=super_costs+s;
1.155     anton    1518:     struct waypoint *wi=&(t->trans[c->state_in]);
                   1519:     struct waypoint *wo=&(t->inst[c->state_out]);
1.158     anton    1520:     lb_applicable_chain_rules++;
1.125     anton    1521:     if (wo->cost == INF_COST)
                   1522:       continue;
                   1523:     jcost = wo->cost + ss_cost(s);
                   1524:     if (jcost <= wi->cost) {
                   1525:       wi->cost = jcost;
                   1526:       wi->inst = s;
                   1527:       wi->relocatable = wo->relocatable;
                   1528:       wi->no_transition = 0;
                   1529:       /* if (ss_greedy) wi->cost = wo->cost ? */
                   1530:     }
                   1531:   }
                   1532: }
1.107     anton    1533: 
1.161     pazsan   1534: static struct tpa_state *make_termstate()
1.155     anton    1535: {
1.157     anton    1536:   struct tpa_state *s = empty_tpa_state();
1.155     anton    1537: 
                   1538:   s->inst[CANONICAL_STATE].cost = 0;
                   1539:   transitions(s);
                   1540:   return s;
                   1541: }
1.162     pazsan   1542: #endif
1.155     anton    1543: 
1.156     anton    1544: #define TPA_SIZE 16384
                   1545: 
                   1546: struct tpa_entry {
                   1547:   struct tpa_entry *next;
                   1548:   PrimNum inst;
                   1549:   struct tpa_state *state_behind;  /* note: brack-to-front labeling */
                   1550:   struct tpa_state *state_infront; /* note: brack-to-front labeling */
                   1551: } *tpa_table[TPA_SIZE];
                   1552: 
1.162     pazsan   1553: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1.161     pazsan   1554: static Cell hash_tpa(PrimNum p, struct tpa_state *t)
1.156     anton    1555: {
                   1556:   UCell it = (UCell )t;
                   1557:   return (p+it+(it>>14))&(TPA_SIZE-1);
                   1558: }
                   1559: 
1.161     pazsan   1560: static struct tpa_state **lookup_tpa(PrimNum p, struct tpa_state *t2)
1.156     anton    1561: {
                   1562:   int hash=hash_tpa(p, t2);
                   1563:   struct tpa_entry *te = tpa_table[hash];
                   1564: 
1.158     anton    1565:   if (tpa_noautomaton) {
                   1566:     static struct tpa_state *t;
                   1567:     t = NULL;
                   1568:     return &t;
                   1569:   }
1.156     anton    1570:   for (; te!=NULL; te = te->next) {
                   1571:     if (p == te->inst && t2 == te->state_behind)
                   1572:       return &(te->state_infront);
                   1573:   }
                   1574:   te = (struct tpa_entry *)malloc(sizeof(struct tpa_entry));
                   1575:   te->next = tpa_table[hash];
                   1576:   te->inst = p;
                   1577:   te->state_behind = t2;
                   1578:   te->state_infront = NULL;
                   1579:   tpa_table[hash] = te;
                   1580:   return &(te->state_infront);
                   1581: }
                   1582: 
1.161     pazsan   1583: static void tpa_state_normalize(struct tpa_state *t)
1.157     anton    1584: {
                   1585:   /* normalize so cost of canonical state=0; this may result in
                   1586:      negative states for some states */
                   1587:   int d = t->inst[CANONICAL_STATE].cost;
                   1588:   int i;
                   1589: 
                   1590:   for (i=0; i<maxstates; i++) {
                   1591:     if (t->inst[i].cost != INF_COST)
                   1592:       t->inst[i].cost -= d;
                   1593:     if (t->trans[i].cost != INF_COST)
                   1594:       t->trans[i].cost -= d;
                   1595:   }
                   1596: }
                   1597: 
1.161     pazsan   1598: static int tpa_state_equivalent(struct tpa_state *t1, struct tpa_state *t2)
1.157     anton    1599: {
                   1600:   return (memcmp(t1->inst, t2->inst, maxstates*sizeof(struct waypoint)) == 0 &&
                   1601:          memcmp(t1->trans,t2->trans,maxstates*sizeof(struct waypoint)) == 0);
                   1602: }
1.162     pazsan   1603: #endif
1.157     anton    1604: 
                   1605: struct tpa_state_entry {
                   1606:   struct tpa_state_entry *next;
                   1607:   struct tpa_state *state;
                   1608: } *tpa_state_table[TPA_SIZE];
                   1609: 
1.163     pazsan   1610: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1.161     pazsan   1611: static Cell hash_tpa_state(struct tpa_state *t)
1.157     anton    1612: {
                   1613:   int *ti = (int *)(t->inst);
                   1614:   int *tt = (int *)(t->trans);
                   1615:   int r=0;
                   1616:   int i;
                   1617: 
                   1618:   for (i=0; ti+i < (int *)(t->inst+maxstates); i++)
                   1619:     r += ti[i]+tt[i];
                   1620:   return (r+(r>>14)+(r>>22)) & (TPA_SIZE-1);
                   1621: }
                   1622: 
1.161     pazsan   1623: static struct tpa_state *lookup_tpa_state(struct tpa_state *t)
1.157     anton    1624: {
                   1625:   Cell hash = hash_tpa_state(t);
                   1626:   struct tpa_state_entry *te = tpa_state_table[hash];
                   1627:   struct tpa_state_entry *tn;
                   1628: 
1.158     anton    1629:   if (!tpa_noequiv) {
                   1630:     for (; te!=NULL; te = te->next) {
                   1631:       if (tpa_state_equivalent(t, te->state)) {
                   1632:        lb_newstate_equiv++;
                   1633:        free(t->inst);
                   1634:        free(t->trans);
                   1635:        free(t);
                   1636:        return te->state;
                   1637:       }
1.157     anton    1638:     }
1.158     anton    1639:     tn = (struct tpa_state_entry *)malloc(sizeof(struct tpa_state_entry));
                   1640:     tn->next = te;
                   1641:     tn->state = t;
                   1642:     tpa_state_table[hash] = tn;
                   1643:   }
                   1644:   lb_newstate_new++;
                   1645:   if (tpa_trace)
                   1646:     fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
1.157     anton    1647:   return t;
                   1648: }
                   1649: 
1.125     anton    1650: /* use dynamic programming to find the shortest paths within the basic
                   1651:    block origs[0..ninsts-1] and rewrite the instructions pointed to by
                   1652:    instps to use it */
1.161     pazsan   1653: static void optimize_rewrite(Cell *instps[], PrimNum origs[], int ninsts)
1.125     anton    1654: {
                   1655:   int i,j;
1.156     anton    1656:   struct tpa_state *ts[ninsts+1];
1.125     anton    1657:   int nextdyn, nextstate, no_transition;
                   1658:   
1.158     anton    1659:   lb_basic_blocks++;
1.155     anton    1660:   ts[ninsts] = termstate;
1.189     anton    1661: #ifndef NO_DYNAMIC
                   1662:   if (print_sequences) {
                   1663:     for (i=0; i<ninsts; i++)
1.190     anton    1664: #if defined(BURG_FORMAT)
                   1665:       fprintf(stderr, "op%d ", super_costs[origs[i]].offset);
                   1666: #else
1.189     anton    1667:       fprintf(stderr, "%s ", prim_names[origs[i]]);
1.190     anton    1668: #endif
1.189     anton    1669:     fprintf(stderr, "\n");
                   1670:   }
                   1671: #endif
1.107     anton    1672:   for (i=ninsts-1; i>=0; i--) {
1.156     anton    1673:     struct tpa_state **tp = lookup_tpa(origs[i],ts[i+1]);
                   1674:     struct tpa_state *t = *tp;
1.158     anton    1675:     lb_labeler_steps++;
                   1676:     if (t) {
1.156     anton    1677:       ts[i] = t;
1.158     anton    1678:       lb_labeler_automaton++;
                   1679:     }
1.156     anton    1680:     else {
1.158     anton    1681:       lb_labeler_dynprog++;
1.156     anton    1682:       ts[i] = empty_tpa_state();
                   1683:       for (j=1; j<=max_super && i+j<=ninsts; j++) {
                   1684:        struct super_state **superp = lookup_super(origs+i, j);
                   1685:        if (superp!=NULL) {
                   1686:          struct super_state *supers = *superp;
                   1687:          for (; supers!=NULL; supers = supers->next) {
                   1688:            PrimNum s = supers->super;
                   1689:            int jcost;
                   1690:            struct cost *c=super_costs+s;
                   1691:            struct waypoint *wi=&(ts[i]->inst[c->state_in]);
                   1692:            struct waypoint *wo=&(ts[i+j]->trans[c->state_out]);
                   1693:            int no_transition = wo->no_transition;
1.158     anton    1694:            lb_applicable_base_rules++;
1.156     anton    1695:            if (!(is_relocatable(s)) && !wo->relocatable) {
                   1696:              wo=&(ts[i+j]->inst[c->state_out]);
                   1697:              no_transition=1;
                   1698:            }
                   1699:            if (wo->cost == INF_COST) 
                   1700:              continue;
                   1701:            jcost = wo->cost + ss_cost(s);
                   1702:            if (jcost <= wi->cost) {
                   1703:              wi->cost = jcost;
                   1704:              wi->inst = s;
                   1705:              wi->relocatable = is_relocatable(s);
                   1706:              wi->no_transition = no_transition;
                   1707:              /* if (ss_greedy) wi->cost = wo->cost ? */
                   1708:            }
1.125     anton    1709:          }
1.107     anton    1710:        }
                   1711:       }
1.156     anton    1712:       transitions(ts[i]);
1.157     anton    1713:       tpa_state_normalize(ts[i]);
                   1714:       *tp = ts[i] = lookup_tpa_state(ts[i]);
1.158     anton    1715:       if (tpa_trace)
                   1716:        fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
1.107     anton    1717:     }
1.125     anton    1718:   }
                   1719:   /* now rewrite the instructions */
                   1720:   nextdyn=0;
                   1721:   nextstate=CANONICAL_STATE;
1.155     anton    1722:   no_transition = ((!ts[0]->trans[nextstate].relocatable) 
                   1723:                   ||ts[0]->trans[nextstate].no_transition);
1.125     anton    1724:   for (i=0; i<ninsts; i++) {
                   1725:     Cell tc=0, tc2;
                   1726:     if (i==nextdyn) {
                   1727:       if (!no_transition) {
                   1728:        /* process trans */
1.155     anton    1729:        PrimNum p = ts[i]->trans[nextstate].inst;
1.125     anton    1730:        struct cost *c = super_costs+p;
1.155     anton    1731:        assert(ts[i]->trans[nextstate].cost != INF_COST);
1.125     anton    1732:        assert(c->state_in==nextstate);
1.128     anton    1733:        tc = compile_prim_dyn(p,NULL);
1.125     anton    1734:        nextstate = c->state_out;
                   1735:       }
                   1736:       {
                   1737:        /* process inst */
1.155     anton    1738:        PrimNum p = ts[i]->inst[nextstate].inst;
1.125     anton    1739:        struct cost *c=super_costs+p;
                   1740:        assert(c->state_in==nextstate);
1.155     anton    1741:        assert(ts[i]->inst[nextstate].cost != INF_COST);
1.125     anton    1742: #if defined(GFORTH_DEBUGGING)
                   1743:        assert(p == origs[i]);
                   1744: #endif
1.128     anton    1745:        tc2 = compile_prim_dyn(p,instps[i]);
1.125     anton    1746:        if (no_transition || !is_relocatable(p))
                   1747:          /* !! actually what we care about is if and where
                   1748:           * compile_prim_dyn() puts NEXTs */
                   1749:          tc=tc2;
1.155     anton    1750:        no_transition = ts[i]->inst[nextstate].no_transition;
1.125     anton    1751:        nextstate = c->state_out;
                   1752:        nextdyn += c->length;
                   1753:       }
                   1754:     } else {
                   1755: #if defined(GFORTH_DEBUGGING)
                   1756:       assert(0);
                   1757: #endif
                   1758:       tc=0;
1.155     anton    1759:       /* tc= (Cell)vm_prims[ts[i]->inst[CANONICAL_STATE].inst]; */
1.125     anton    1760:     }
                   1761:     *(instps[i]) = tc;
                   1762:   }      
                   1763:   if (!no_transition) {
1.155     anton    1764:     PrimNum p = ts[i]->trans[nextstate].inst;
1.125     anton    1765:     struct cost *c = super_costs+p;
                   1766:     assert(c->state_in==nextstate);
1.155     anton    1767:     assert(ts[i]->trans[nextstate].cost != INF_COST);
1.125     anton    1768:     assert(i==nextdyn);
1.128     anton    1769:     (void)compile_prim_dyn(p,NULL);
1.125     anton    1770:     nextstate = c->state_out;
1.107     anton    1771:   }
1.125     anton    1772:   assert(nextstate==CANONICAL_STATE);
1.107     anton    1773: }
1.162     pazsan   1774: #endif
1.107     anton    1775: 
1.105     anton    1776: /* compile *start, possibly rewriting it into a static and/or dynamic
                   1777:    superinstruction */
                   1778: void compile_prim1(Cell *start)
1.70      anton    1779: {
1.108     anton    1780: #if defined(DOUBLY_INDIRECT)
1.125     anton    1781:   Label prim;
                   1782: 
                   1783:   if (start==NULL)
                   1784:     return;
                   1785:   prim = (Label)*start;
1.108     anton    1786:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
                   1787:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
                   1788:     *start=(Cell)prim;
                   1789:     return;
                   1790:   } else {
                   1791:     *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
                   1792:     return;
                   1793:   }
                   1794: #elif defined(INDIRECT_THREADED)
                   1795:   return;
1.112     anton    1796: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1.128     anton    1797:   /* !! does not work, for unknown reasons; but something like this is
                   1798:      probably needed to ensure that we don't call compile_prim_dyn
                   1799:      before the inline arguments are there */
                   1800:   static Cell *instps[MAX_BB];
                   1801:   static PrimNum origs[MAX_BB];
                   1802:   static int ninsts=0;
                   1803:   PrimNum prim_num;
                   1804: 
                   1805:   if (start==NULL || ninsts >= MAX_BB ||
                   1806:       (ninsts>0 && superend[origs[ninsts-1]])) {
                   1807:     /* after bb, or at the start of the next bb */
                   1808:     optimize_rewrite(instps,origs,ninsts);
                   1809:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts); */
                   1810:     ninsts=0;
1.185     anton    1811:     if (start==NULL) {
                   1812:       align_code();
1.128     anton    1813:       return;
1.185     anton    1814:     }
1.128     anton    1815:   }
                   1816:   prim_num = ((Xt)*start)-vm_prims;
                   1817:   if(prim_num >= npriminfos) {
                   1818:     optimize_rewrite(instps,origs,ninsts);
1.129     anton    1819:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts);*/
1.128     anton    1820:     ninsts=0;
                   1821:     return;
                   1822:   }    
                   1823:   assert(ninsts<MAX_BB);
                   1824:   instps[ninsts] = start;
                   1825:   origs[ninsts] = prim_num;
                   1826:   ninsts++;
1.112     anton    1827: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1.47      anton    1828: }
                   1829: 
1.176     pazsan   1830: #ifndef STANDALONE
1.161     pazsan   1831: Address gforth_loader(FILE *imagefile, char* filename)
1.1       anton    1832: /* returns the address of the image proper (after the preamble) */
                   1833: {
                   1834:   ImageHeader header;
                   1835:   Address image;
                   1836:   Address imp; /* image+preamble */
1.17      anton    1837:   Char magic[8];
                   1838:   char magic7; /* size byte of magic number */
1.1       anton    1839:   Cell preamblesize=0;
1.6       pazsan   1840:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1.1       anton    1841:   UCell check_sum;
1.15      pazsan   1842:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
                   1843:                 (RELINFOBITS == 16) ? 1 :
                   1844:                 (RELINFOBITS == 32) ? 2 : 3);
                   1845:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
                   1846:                   (sizeof(Char) == 2) ? 1 :
                   1847:                   (sizeof(Char) == 4) ? 2 : 3) + ausize;
                   1848:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
                   1849:                   (sizeof(Cell) == 2) ? 1 :
                   1850:                   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1.21      anton    1851:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
                   1852: #ifdef WORDS_BIGENDIAN
                   1853:        0
                   1854: #else
                   1855:        1
                   1856: #endif
                   1857:     ;
1.1       anton    1858: 
1.197     anton    1859:   vm_prims = gforth_engine(0,0,0,0,0 sr_call);
1.47      anton    1860:   check_prims(vm_prims);
1.106     anton    1861:   prepare_super_table();
1.1       anton    1862: #ifndef DOUBLY_INDIRECT
1.59      anton    1863: #ifdef PRINT_SUPER_LENGTHS
                   1864:   print_super_lengths();
                   1865: #endif
1.43      anton    1866:   check_sum = checksum(vm_prims);
1.1       anton    1867: #else /* defined(DOUBLY_INDIRECT) */
1.43      anton    1868:   check_sum = (UCell)vm_prims;
1.1       anton    1869: #endif /* defined(DOUBLY_INDIRECT) */
1.155     anton    1870: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
                   1871:   termstate = make_termstate();
                   1872: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1.10      pazsan   1873:   
                   1874:   do {
                   1875:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.84      anton    1876:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
1.10      pazsan   1877:              progname, filename);
                   1878:       exit(1);
1.1       anton    1879:     }
1.10      pazsan   1880:     preamblesize+=8;
1.84      anton    1881:   } while(memcmp(magic,"Gforth3",7));
1.17      anton    1882:   magic7 = magic[7];
1.1       anton    1883:   if (debug) {
1.17      anton    1884:     magic[7]='\0';
1.21      anton    1885:     fprintf(stderr,"Magic found: %s ", magic);
                   1886:     print_sizes(magic7);
1.1       anton    1887:   }
                   1888: 
1.21      anton    1889:   if (magic7 != sizebyte)
                   1890:     {
                   1891:       fprintf(stderr,"This image is:         ");
                   1892:       print_sizes(magic7);
                   1893:       fprintf(stderr,"whereas the machine is ");
                   1894:       print_sizes(sizebyte);
1.1       anton    1895:       exit(-2);
                   1896:     };
                   1897: 
                   1898:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.10      pazsan   1899: 
                   1900:   set_stack_sizes(&header);
1.1       anton    1901:   
                   1902: #if HAVE_GETPAGESIZE
                   1903:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
                   1904: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
                   1905:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
                   1906: #elif PAGESIZE
                   1907:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
                   1908: #endif
1.144     pazsan   1909:   debugp(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1.1       anton    1910: 
1.34      anton    1911:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
                   1912:                          preamblesize+dictsize, data_offset);
1.33      anton    1913:   imp=image+preamblesize;
1.178     pazsan   1914: 
1.57      anton    1915:   alloc_stacks((ImageHeader *)imp);
1.1       anton    1916:   if (clear_dictionary)
1.33      anton    1917:     memset(imp+header.image_size, 0, dictsize-header.image_size);
1.90      anton    1918:   if(header.base==0 || header.base  == (Address)0x100) {
1.1       anton    1919:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
1.162     pazsan   1920:     Char reloc_bits[reloc_size];
1.33      anton    1921:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1.10      pazsan   1922:     fread(reloc_bits, 1, reloc_size, imagefile);
1.161     pazsan   1923:     gforth_relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
1.1       anton    1924: #if 0
                   1925:     { /* let's see what the relocator did */
                   1926:       FILE *snapshot=fopen("snapshot.fi","wb");
                   1927:       fwrite(image,1,imagesize,snapshot);
                   1928:       fclose(snapshot);
                   1929:     }
                   1930: #endif
1.46      jwilke   1931:   }
                   1932:   else if(header.base!=imp) {
                   1933:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
                   1934:            progname, (unsigned long)header.base, (unsigned long)imp);
                   1935:     exit(1);
1.1       anton    1936:   }
                   1937:   if (header.checksum==0)
                   1938:     ((ImageHeader *)imp)->checksum=check_sum;
                   1939:   else if (header.checksum != check_sum) {
                   1940:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
                   1941:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
                   1942:     exit(1);
                   1943:   }
1.53      anton    1944: #ifdef DOUBLY_INDIRECT
                   1945:   ((ImageHeader *)imp)->xt_base = xts;
                   1946: #endif
1.1       anton    1947:   fclose(imagefile);
                   1948: 
1.56      anton    1949:   /* unnecessary, except maybe for CODE words */
                   1950:   /* FLUSH_ICACHE(imp, header.image_size);*/
1.1       anton    1951: 
                   1952:   return imp;
                   1953: }
1.176     pazsan   1954: #endif
1.1       anton    1955: 
1.72      anton    1956: /* pointer to last '/' or '\' in file, 0 if there is none. */
1.161     pazsan   1957: static char *onlypath(char *filename)
1.10      pazsan   1958: {
1.72      anton    1959:   return strrchr(filename, DIRSEP);
1.1       anton    1960: }
                   1961: 
1.161     pazsan   1962: static FILE *openimage(char *fullfilename)
1.10      pazsan   1963: {
                   1964:   FILE *image_file;
1.162     pazsan   1965:   char * expfilename = tilde_cstr((Char *)fullfilename, strlen(fullfilename), 1);
1.10      pazsan   1966: 
1.28      anton    1967:   image_file=fopen(expfilename,"rb");
1.1       anton    1968:   if (image_file!=NULL && debug)
1.28      anton    1969:     fprintf(stderr, "Opened image file: %s\n", expfilename);
1.10      pazsan   1970:   return image_file;
1.1       anton    1971: }
                   1972: 
1.28      anton    1973: /* try to open image file concat(path[0:len],imagename) */
1.161     pazsan   1974: static FILE *checkimage(char *path, int len, char *imagename)
1.10      pazsan   1975: {
                   1976:   int dirlen=len;
1.162     pazsan   1977:   char fullfilename[dirlen+strlen((char *)imagename)+2];
1.10      pazsan   1978: 
1.1       anton    1979:   memcpy(fullfilename, path, dirlen);
1.71      pazsan   1980:   if (fullfilename[dirlen-1]!=DIRSEP)
                   1981:     fullfilename[dirlen++]=DIRSEP;
1.1       anton    1982:   strcpy(fullfilename+dirlen,imagename);
1.10      pazsan   1983:   return openimage(fullfilename);
1.1       anton    1984: }
                   1985: 
1.161     pazsan   1986: static FILE * open_image_file(char * imagename, char * path)
1.1       anton    1987: {
1.10      pazsan   1988:   FILE * image_file=NULL;
1.28      anton    1989:   char *origpath=path;
1.10      pazsan   1990:   
1.71      pazsan   1991:   if(strchr(imagename, DIRSEP)==NULL) {
1.10      pazsan   1992:     /* first check the directory where the exe file is in !! 01may97jaw */
                   1993:     if (onlypath(progname))
1.72      anton    1994:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1.10      pazsan   1995:     if (!image_file)
                   1996:       do {
                   1997:        char *pend=strchr(path, PATHSEP);
                   1998:        if (pend==NULL)
                   1999:          pend=path+strlen(path);
                   2000:        if (strlen(path)==0) break;
                   2001:        image_file=checkimage(path, pend-path, imagename);
                   2002:        path=pend+(*pend==PATHSEP);
                   2003:       } while (image_file==NULL);
                   2004:   } else {
                   2005:     image_file=openimage(imagename);
                   2006:   }
1.1       anton    2007: 
1.10      pazsan   2008:   if (!image_file) {
                   2009:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.28      anton    2010:            progname, imagename, origpath);
1.10      pazsan   2011:     exit(1);
1.7       anton    2012:   }
                   2013: 
1.10      pazsan   2014:   return image_file;
                   2015: }
1.11      pazsan   2016: #endif
                   2017: 
1.178     pazsan   2018: #ifdef STANDALONE_ALLOC
1.177     pazsan   2019: Address gforth_alloc(Cell size)
                   2020: {
                   2021:   Address r;
                   2022:   /* leave a little room (64B) for stack underflows */
                   2023:   if ((r = malloc(size+64))==NULL) {
                   2024:     perror(progname);
                   2025:     exit(1);
                   2026:   }
                   2027:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
                   2028:   debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
                   2029:   return r;
                   2030: }
                   2031: #endif
                   2032: 
1.11      pazsan   2033: #ifdef HAS_OS
1.161     pazsan   2034: static UCell convsize(char *s, UCell elemsize)
1.11      pazsan   2035: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
                   2036:    of bytes.  the letter at the end indicates the unit, where e stands
                   2037:    for the element size. default is e */
                   2038: {
                   2039:   char *endp;
                   2040:   UCell n,m;
                   2041: 
                   2042:   m = elemsize;
                   2043:   n = strtoul(s,&endp,0);
                   2044:   if (endp!=NULL) {
                   2045:     if (strcmp(endp,"b")==0)
                   2046:       m=1;
                   2047:     else if (strcmp(endp,"k")==0)
                   2048:       m=1024;
                   2049:     else if (strcmp(endp,"M")==0)
                   2050:       m=1024*1024;
                   2051:     else if (strcmp(endp,"G")==0)
                   2052:       m=1024*1024*1024;
                   2053:     else if (strcmp(endp,"T")==0) {
                   2054: #if (SIZEOF_CHAR_P > 4)
1.24      anton    2055:       m=1024L*1024*1024*1024;
1.11      pazsan   2056: #else
                   2057:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
                   2058:       exit(1);
                   2059: #endif
                   2060:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                   2061:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
                   2062:       exit(1);
                   2063:     }
                   2064:   }
                   2065:   return n*m;
                   2066: }
1.10      pazsan   2067: 
1.109     anton    2068: enum {
                   2069:   ss_number = 256,
1.125     anton    2070:   ss_states,
1.109     anton    2071:   ss_min_codesize,
                   2072:   ss_min_ls,
                   2073:   ss_min_lsu,
                   2074:   ss_min_nexts,
                   2075: };
                   2076: 
1.179     pazsan   2077: #ifndef STANDALONE
1.10      pazsan   2078: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
                   2079: {
                   2080:   int c;
                   2081: 
1.1       anton    2082:   opterr=0;
                   2083:   while (1) {
                   2084:     int option_index=0;
                   2085:     static struct option opts[] = {
1.29      anton    2086:       {"appl-image", required_argument, NULL, 'a'},
1.1       anton    2087:       {"image-file", required_argument, NULL, 'i'},
                   2088:       {"dictionary-size", required_argument, NULL, 'm'},
                   2089:       {"data-stack-size", required_argument, NULL, 'd'},
                   2090:       {"return-stack-size", required_argument, NULL, 'r'},
                   2091:       {"fp-stack-size", required_argument, NULL, 'f'},
                   2092:       {"locals-stack-size", required_argument, NULL, 'l'},
1.181     anton    2093:       {"vm-commit", no_argument, &map_noreserve, 0},
1.1       anton    2094:       {"path", required_argument, NULL, 'p'},
                   2095:       {"version", no_argument, NULL, 'v'},
                   2096:       {"help", no_argument, NULL, 'h'},
                   2097:       /* put something != 0 into offset_image */
                   2098:       {"offset-image", no_argument, &offset_image, 1},
                   2099:       {"no-offset-im", no_argument, &offset_image, 0},
                   2100:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
1.201     anton    2101:       {"debug", no_argument, &debug, 1},
                   2102:       {"diag", no_argument, &diag, 1},
1.4       anton    2103:       {"die-on-signal", no_argument, &die_on_signal, 1},
1.169     anton    2104:       {"ignore-async-signals", no_argument, &ignore_async_signals, 1},
1.60      anton    2105:       {"no-super", no_argument, &no_super, 1},
                   2106:       {"no-dynamic", no_argument, &no_dynamic, 1},
1.66      anton    2107:       {"dynamic", no_argument, &no_dynamic, 0},
1.110     anton    2108:       {"print-metrics", no_argument, &print_metrics, 1},
1.189     anton    2109:       {"print-sequences", no_argument, &print_sequences, 1},
1.109     anton    2110:       {"ss-number", required_argument, NULL, ss_number},
1.125     anton    2111:       {"ss-states", required_argument, NULL, ss_states},
1.109     anton    2112: #ifndef NO_DYNAMIC
                   2113:       {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
                   2114: #endif
                   2115:       {"ss-min-ls",       no_argument, NULL, ss_min_ls},
                   2116:       {"ss-min-lsu",      no_argument, NULL, ss_min_lsu},
                   2117:       {"ss-min-nexts",    no_argument, NULL, ss_min_nexts},
1.110     anton    2118:       {"ss-greedy",       no_argument, &ss_greedy, 1},
1.158     anton    2119:       {"tpa-noequiv",     no_argument, &tpa_noequiv, 1},
                   2120:       {"tpa-noautomaton", no_argument, &tpa_noautomaton, 1},
                   2121:       {"tpa-trace",      no_argument, &tpa_trace, 1},
1.1       anton    2122:       {0,0,0,0}
                   2123:       /* no-init-file, no-rc? */
                   2124:     };
                   2125:     
1.36      pazsan   2126:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1.1       anton    2127:     
                   2128:     switch (c) {
1.29      anton    2129:     case EOF: return;
                   2130:     case '?': optind--; return;
                   2131:     case 'a': *imagename = optarg; return;
1.10      pazsan   2132:     case 'i': *imagename = optarg; break;
1.1       anton    2133:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                   2134:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                   2135:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                   2136:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                   2137:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.10      pazsan   2138:     case 'p': *path = optarg; break;
1.36      pazsan   2139:     case 'o': offset_image = 1; break;
                   2140:     case 'n': offset_image = 0; break;
                   2141:     case 'c': clear_dictionary = 1; break;
                   2142:     case 's': die_on_signal = 1; break;
                   2143:     case 'x': debug = 1; break;
1.83      anton    2144:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
1.109     anton    2145:     case ss_number: static_super_number = atoi(optarg); break;
1.125     anton    2146:     case ss_states: maxstates = max(min(atoi(optarg),MAX_STATE),1); break;
1.109     anton    2147: #ifndef NO_DYNAMIC
                   2148:     case ss_min_codesize: ss_cost = cost_codesize; break;
                   2149: #endif
                   2150:     case ss_min_ls:       ss_cost = cost_ls;       break;
                   2151:     case ss_min_lsu:      ss_cost = cost_lsu;      break;
                   2152:     case ss_min_nexts:    ss_cost = cost_nexts;    break;
1.1       anton    2153:     case 'h': 
1.29      anton    2154:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1.1       anton    2155: Engine Options:\n\
1.181     anton    2156:   --appl-image FILE                Equivalent to '--image-file=FILE --'\n\
1.10      pazsan   2157:   --clear-dictionary               Initialize the dictionary with 0 bytes\n\
                   2158:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
                   2159:   --debug                          Print debugging information during startup\n\
1.144     pazsan   2160:   --diag                           Print diagnostic information during startup\n\
1.181     anton    2161:   --die-on-signal                  Exit instead of THROWing some signals\n\
                   2162:   --dynamic                        Use dynamic native code\n\
1.10      pazsan   2163:   -f SIZE, --fp-stack-size=SIZE            Specify floating point stack size\n\
                   2164:   -h, --help                       Print this message and exit\n\
1.181     anton    2165:   --ignore-async-signals           Ignore instead of THROWing async. signals\n\
1.10      pazsan   2166:   -i FILE, --image-file=FILE       Use image FILE instead of `gforth.fi'\n\
                   2167:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
                   2168:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
1.60      anton    2169:   --no-dynamic                     Use only statically compiled primitives\n\
1.10      pazsan   2170:   --no-offset-im                   Load image at normal position\n\
1.181     anton    2171:   --no-super                       No dynamically formed superinstructions\n\
1.10      pazsan   2172:   --offset-image                   Load image at a different position\n\
                   2173:   -p PATH, --path=PATH             Search path for finding image and sources\n\
1.110     anton    2174:   --print-metrics                  Print some code generation metrics on exit\n\
1.201     anton    2175:   --print-sequences                Print primitive sequences for optimization\n\
1.10      pazsan   2176:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1.181     anton    2177:   --ss-greedy                      Greedy, not optimal superinst selection\n\
                   2178:   --ss-min-codesize                Select superinsts for smallest native code\n\
                   2179:   --ss-min-ls                      Minimize loads and stores\n\
                   2180:   --ss-min-lsu                     Minimize loads, stores, and pointer updates\n\
                   2181:   --ss-min-nexts                   Minimize the number of static superinsts\n\
                   2182:   --ss-number=N                            Use N static superinsts (default max)\n\
                   2183:   --ss-states=N                            N states for stack caching (default max)\n\
                   2184:   --tpa-noequiv                            Automaton without state equivalence\n\
                   2185:   --tpa-noautomaton                Dynamic programming only\n\
                   2186:   --tpa-trace                      Report new states etc.\n\
1.66      anton    2187:   -v, --version                            Print engine version and exit\n\
1.181     anton    2188:   --vm-commit                      Use OS default for memory overcommit\n\
1.1       anton    2189: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1.10      pazsan   2190:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
                   2191:              argv[0]);
                   2192:       optind--;
                   2193:       return;
1.1       anton    2194:     }
                   2195:   }
1.10      pazsan   2196: }
1.11      pazsan   2197: #endif
1.179     pazsan   2198: #endif
1.10      pazsan   2199: 
1.161     pazsan   2200: static void print_diag()
1.144     pazsan   2201: {
                   2202: 
1.207     pazsan   2203: #if !defined(HAVE_GETRUSAGE)
1.145     pazsan   2204:   fprintf(stderr, "*** missing functionality ***\n"
1.144     pazsan   2205: #ifndef HAVE_GETRUSAGE
                   2206:          "    no getrusage -> CPUTIME broken\n"
                   2207: #endif
                   2208:          );
                   2209: #endif
                   2210:   if((relocs < nonrelocs) ||
                   2211: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
                   2212:      1
                   2213: #else
                   2214:      0
                   2215: #endif
                   2216:      )
                   2217:     debugp(stderr, "relocs: %d:%d\n", relocs, nonrelocs);
1.209     anton    2218:     fprintf(stderr, "*** %sperformance problems ***\n%s%s",
1.204     anton    2219: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D) || !(defined(FORCE_REG) || defined(FORCE_REG_UNNECESSARY)) || defined(BUGGY_LONG_LONG)
1.165     pazsan   2220:            "",
                   2221: #else
                   2222:            "no ",
                   2223: #endif
1.144     pazsan   2224: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
                   2225:            "    double-cell integer type buggy ->\n        "
                   2226: #ifdef BUGGY_LL_CMP
                   2227:            "CMP, "
                   2228: #endif
                   2229: #ifdef BUGGY_LL_MUL
                   2230:            "MUL, "
                   2231: #endif
                   2232: #ifdef BUGGY_LL_DIV
                   2233:            "DIV, "
                   2234: #endif
                   2235: #ifdef BUGGY_LL_ADD
                   2236:            "ADD, "
                   2237: #endif
                   2238: #ifdef BUGGY_LL_SHIFT
                   2239:            "SHIFT, "
                   2240: #endif
                   2241: #ifdef BUGGY_LL_D2F
                   2242:            "D2F, "
                   2243: #endif
                   2244: #ifdef BUGGY_LL_F2D
                   2245:            "F2D, "
                   2246: #endif
                   2247:            "\b\b slow\n"
1.145     pazsan   2248: #endif
1.200     anton    2249: #if !(defined(FORCE_REG) || defined(FORCE_REG_UNNECESSARY))
1.145     pazsan   2250:            "    automatic register allocation: performance degradation possible\n"
                   2251: #endif
1.198     anton    2252:            "",
1.209     anton    2253:            (relocs < nonrelocs) ? "no dynamic code generation (--debug for details) -> factor 2 slowdown\n" : "");
1.144     pazsan   2254: }
                   2255: 
1.179     pazsan   2256: #ifdef STANDALONE
                   2257: Cell data_abort_pc;
                   2258: 
                   2259: void data_abort_C(void)
                   2260: {
                   2261:   while(1) {
                   2262:   }
                   2263: }
1.10      pazsan   2264: #endif
1.67      pazsan   2265: 
1.10      pazsan   2266: int main(int argc, char **argv, char **env)
                   2267: {
1.30      pazsan   2268: #ifdef HAS_OS
1.10      pazsan   2269:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1.30      pazsan   2270: #else
                   2271:   char *path = DEFAULTPATH;
                   2272: #endif
1.13      pazsan   2273: #ifndef INCLUDE_IMAGE
1.10      pazsan   2274:   char *imagename="gforth.fi";
                   2275:   FILE *image_file;
                   2276:   Address image;
                   2277: #endif
                   2278:   int retvalue;
                   2279:          
1.213     anton    2280:   code_here = ((void *)0)+CODE_BLOCK_SIZE; /* llvm-gcc does not like this as
                   2281:                                               initializer, so we do it here */
1.215     anton    2282: #ifdef MACOSX_DEPLOYMENT_TARGET
                   2283:   setenv("MACOSX_DEPLOYMENT_TARGET", MACOSX_DEPLOYMENT_TARGET, 0);
                   2284: #endif
                   2285: #ifdef LTDL_LIBRARY_PATH
                   2286:   setenv("LTDL_LIBRARY_PATH", LTDL_LIBRARY_PATH, 0);
                   2287: #endif
1.179     pazsan   2288: #ifndef STANDALONE
1.10      pazsan   2289:   /* buffering of the user output device */
1.11      pazsan   2290: #ifdef _IONBF
1.10      pazsan   2291:   if (isatty(fileno(stdout))) {
                   2292:     fflush(stdout);
                   2293:     setvbuf(stdout,NULL,_IONBF,0);
1.1       anton    2294:   }
1.11      pazsan   2295: #endif
1.180     pazsan   2296: #else
                   2297:   prep_terminal();
1.179     pazsan   2298: #endif
1.1       anton    2299: 
1.10      pazsan   2300:   progname = argv[0];
                   2301: 
1.199     pazsan   2302: #ifndef STANDALONE
1.212     anton    2303: #ifdef HAVE_LIBLTDL
1.191     anton    2304:   if (lt_dlinit()!=0) {
                   2305:     fprintf(stderr,"%s: lt_dlinit failed", progname);
                   2306:     exit(1);
                   2307:   }
1.212     anton    2308: #endif
1.203     anton    2309:     
1.11      pazsan   2310: #ifdef HAS_OS
1.10      pazsan   2311:   gforth_args(argc, argv, &path, &imagename);
1.109     anton    2312: #ifndef NO_DYNAMIC
1.148     anton    2313:   init_ss_cost();
1.109     anton    2314: #endif /* !defined(NO_DYNAMIC) */
                   2315: #endif /* defined(HAS_OS) */
1.179     pazsan   2316: #endif
1.10      pazsan   2317: 
1.175     pazsan   2318: #ifdef STANDALONE
1.197     anton    2319:   image = gforth_engine(0, 0, 0, 0, 0 sr_call);
1.10      pazsan   2320:   alloc_stacks((ImageHeader *)image);
                   2321: #else
                   2322:   image_file = open_image_file(imagename, path);
1.161     pazsan   2323:   image = gforth_loader(image_file, imagename);
1.10      pazsan   2324: #endif
1.24      anton    2325:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1.1       anton    2326: 
1.144     pazsan   2327:   if (diag)
                   2328:     print_diag();
1.1       anton    2329:   {
1.10      pazsan   2330:     char path2[strlen(path)+1];
1.1       anton    2331:     char *p1, *p2;
                   2332:     Cell environ[]= {
                   2333:       (Cell)argc-(optind-1),
                   2334:       (Cell)(argv+(optind-1)),
1.10      pazsan   2335:       (Cell)strlen(path),
1.1       anton    2336:       (Cell)path2};
                   2337:     argv[optind-1] = progname;
                   2338:     /*
                   2339:        for (i=0; i<environ[0]; i++)
                   2340:        printf("%s\n", ((char **)(environ[1]))[i]);
                   2341:        */
                   2342:     /* make path OS-independent by replacing path separators with NUL */
1.10      pazsan   2343:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1.1       anton    2344:       if (*p1==PATHSEP)
                   2345:        *p2 = '\0';
                   2346:       else
                   2347:        *p2 = *p1;
                   2348:     *p2='\0';
1.161     pazsan   2349:     retvalue = gforth_go(image, 4, environ);
1.178     pazsan   2350: #if defined(SIGPIPE) && !defined(STANDALONE)
1.102     anton    2351:     bsd_signal(SIGPIPE, SIG_IGN);
                   2352: #endif
1.42      anton    2353: #ifdef VM_PROFILING
                   2354:     vm_print_profile(stderr);
                   2355: #endif
1.1       anton    2356:     deprep_terminal();
1.199     pazsan   2357: #ifndef STANDALONE
1.212     anton    2358: #ifdef HAVE_LIBLTDL
1.191     anton    2359:     if (lt_dlexit()!=0)
                   2360:       fprintf(stderr,"%s: lt_dlexit failed", progname);
1.199     pazsan   2361: #endif
1.212     anton    2362: #endif
1.104     anton    2363:   }
1.110     anton    2364:   if (print_metrics) {
                   2365:     int i;
                   2366:     fprintf(stderr, "code size = %8ld\n", dyncodesize());
1.177     pazsan   2367: #ifndef STANDALONE
1.110     anton    2368:     for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
                   2369:       fprintf(stderr, "metric %8s: %8ld\n",
                   2370:              cost_sums[i].metricname, cost_sums[i].sum);
1.177     pazsan   2371: #endif
1.158     anton    2372:     fprintf(stderr,"lb_basic_blocks = %ld\n", lb_basic_blocks);
                   2373:     fprintf(stderr,"lb_labeler_steps = %ld\n", lb_labeler_steps);
                   2374:     fprintf(stderr,"lb_labeler_automaton = %ld\n", lb_labeler_automaton);
                   2375:     fprintf(stderr,"lb_labeler_dynprog = %ld\n", lb_labeler_dynprog);
                   2376:     fprintf(stderr,"lb_newstate_equiv = %ld\n", lb_newstate_equiv);
                   2377:     fprintf(stderr,"lb_newstate_new = %ld\n", lb_newstate_new);
                   2378:     fprintf(stderr,"lb_applicable_base_rules = %ld\n", lb_applicable_base_rules);
                   2379:     fprintf(stderr,"lb_applicable_chain_rules = %ld\n", lb_applicable_chain_rules);
                   2380:   }
                   2381:   if (tpa_trace) {
                   2382:     fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
                   2383:     fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
1.1       anton    2384:   }
1.13      pazsan   2385:   return retvalue;
1.1       anton    2386: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>