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

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

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