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

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

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