File:  [gforth] / gforth / engine / main.c
Revision 1.176: download - view: text, annotated - select for diffs
Sun Mar 25 21:30:59 2007 UTC (17 years ago) by pazsan
Branches: MAIN
CVS tags: HEAD
C-based Gforth EC starts to work

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

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