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

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

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