File:  [gforth] / gforth / engine / main.c
Revision 1.199: download - view: text, annotated - select for diffs
Sat Feb 23 13:03:56 2008 UTC (16 years, 1 month ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Fixed build problem
Some changes for NXT

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

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