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

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

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