File:  [gforth] / gforth / Attic / prims2y.fs
Revision 1.4: download - view: text, annotated - select for diffs
Wed Oct 1 09:15:45 2003 UTC (17 years, 10 months ago) by anton
Branches: MAIN
CVS tags: HEAD
adapted store optimization to stack caching

    1: \ converts primitives to, e.g., C code 
    2: 
    3: \ Copyright (C) 1995,1996,1997,1998,2000,2003 Free Software Foundation, Inc.
    4: 
    5: \ This file is part of Gforth.
    6: 
    7: \ Gforth is free software; you can redistribute it and/or
    8: \ modify it under the terms of the GNU General Public License
    9: \ as published by the Free Software Foundation; either version 2
   10: \ of the License, or (at your option) any later version.
   11: 
   12: \ This program is distributed in the hope that it will be useful,
   13: \ but WITHOUT ANY WARRANTY; without even the implied warranty of
   14: \ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   15: \ GNU General Public License for more details.
   16: 
   17: \ You should have received a copy of the GNU General Public License
   18: \ along with this program; if not, write to the Free Software
   19: \ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
   20: 
   21: 
   22: \ This is not very nice (hard limits, no checking, assumes 1 chars = 1).
   23: \ And it grew even worse when it aged.
   24: 
   25: \ Optimizations:
   26: \ superfluous stores are removed. GCC removes the superfluous loads by itself
   27: \ TOS and FTOS can be kept in register( variable)s.
   28: \ 
   29: \ Problems:
   30: \ The TOS optimization is somewhat hairy. The problems by example:
   31: \ 1) dup ( w -- w w ): w=TOS; sp-=1; sp[1]=w; TOS=w;
   32: \    The store is not superfluous although the earlier opt. would think so
   33: \    Alternatively:    sp[0]=TOS; w=TOS; sp-=1; TOS=w;
   34: \ 2) ( -- .. ): sp[0] = TOS; ... /* This additional store is necessary */
   35: \ 3) ( .. -- ): ... TOS = sp[0]; /* as well as this load */
   36: \ 4) ( -- ): /* but here they are unnecessary */
   37: \ 5) Words that call NEXT themselves have to be done very carefully.
   38: \
   39: \ To do:
   40: \ add the store optimization for doubles
   41: \ regarding problem 1 above: It would be better (for over) to implement
   42: \ 	the alternative
   43: \ store optimization for combined instructions.
   44: 
   45: \ Design Uglyness:
   46: 
   47: \ - global state (values, variables) in connection with combined instructions.
   48: 
   49: \ - index computation is different for instruction-stream and the
   50: \ stacks; there are two mechanisms for dealing with that
   51: \ (stack-in-index-xt and a test for stack==instruction-stream); there
   52: \ should be only one.
   53: 
   54: \ for backwards compatibility, jaw
   55: require compat/strcomp.fs
   56: 
   57: warnings off
   58: 
   59: \ redefinitions of kernel words not present in gforth-0.6.1
   60: : latestxt lastcfa @ ;
   61: : latest last @ ;
   62: 
   63: [IFUNDEF] try
   64: include startup.fs
   65: [THEN]
   66: 
   67: : struct% struct ; \ struct is redefined in gray
   68: 
   69: warnings off
   70: \ warnings on
   71: 
   72: include ./gray.fs
   73: 128 constant max-effect \ number of things on one side of a stack effect
   74: 4 constant max-stacks  \ the max. number of stacks (including inst-stream).
   75: 255 constant maxchar
   76: maxchar 1+ constant eof-char
   77: #tab constant tab-char
   78: #lf constant nl-char
   79: 
   80: variable rawinput \ pointer to next character to be scanned
   81: variable endrawinput \ pointer to the end of the input (the char after the last)
   82: variable cookedinput \ pointer to the next char to be parsed
   83: variable line \ line number of char pointed to by input
   84: variable line-start \ pointer to start of current line (for error messages)
   85: 0 line !
   86: 2variable filename \ filename of original input file
   87: 0 0 filename 2!
   88: 2variable out-filename \ filename of the output file (for sync lines)
   89: 0 0 out-filename 2!
   90: 2variable f-comment
   91: 0 0 f-comment 2!
   92: variable skipsynclines \ are sync lines ("#line ...") invisible to the parser?
   93: skipsynclines on
   94: variable out-nls \ newlines in output (for output sync lines)
   95: 0 out-nls !
   96: variable store-optimization \ use store optimization?
   97: store-optimization off
   98: 
   99: variable include-skipped-insts
  100: \ does the threaded code for a combined instruction include the cells
  101: \ for the component instructions (true) or only the cells for the
  102: \ inline arguments (false)
  103: include-skipped-insts off
  104: 
  105: variable immarg \ values for immediate arguments (to be used in IMM_ARG macros)
  106: $12340000 immarg !
  107: 
  108: : th ( addr1 n -- addr2 )
  109:     cells + ;
  110: 
  111: : holds ( addr u -- )
  112:     \ like HOLD, but for a string
  113:     tuck + swap 0 +do
  114: 	1- dup c@ hold
  115:     loop
  116:     drop ;
  117: 
  118: : insert-wordlist { c-addr u wordlist xt -- }
  119:     \ adds name "addr u" to wordlist using defining word xt
  120:     \ xt may cause additional stack effects
  121:     get-current >r wordlist set-current
  122:     c-addr u nextname xt execute
  123:     r> set-current ;
  124: 
  125: : start ( -- addr )
  126:  cookedinput @ ;
  127: 
  128: : end ( addr -- addr u )
  129:  cookedinput @ over - ;
  130: 
  131: : print-error-line ( -- )
  132:     \ print the current line and position
  133:     line-start @ endrawinput @ over - 2dup nl-char scan drop nip ( start end )
  134:     over - type cr
  135:     line-start @ rawinput @ over - typewhite ." ^" cr ;
  136: 
  137: : ?print-error { f addr u -- }
  138:     f ?not? if
  139: 	outfile-id >r try
  140: 	    stderr to outfile-id
  141: 	    filename 2@ type ." :" line @ 0 .r ." : " addr u type cr
  142: 	    print-error-line
  143: 	    0
  144: 	recover endtry
  145: 	r> to outfile-id throw
  146: 	1 (bye) \ abort
  147:     endif ;
  148: 
  149: : quote ( -- )
  150:     [char] " emit ;
  151: 
  152: \ count output lines to generate sync lines for output
  153: 
  154: : count-nls ( addr u -- )
  155:     bounds u+do
  156: 	i c@ nl-char = negate out-nls +!
  157:     loop ;
  158: 
  159: :noname ( addr u -- )
  160:     2dup count-nls
  161:     defers type ;
  162: is type
  163: 
  164: variable output          \ xt ( -- ) of output word for simple primitives
  165: variable output-combined \ xt ( -- ) of output word for combined primitives
  166: 
  167: struct%
  168:     cell%    field stack-number \ the number of this stack
  169:     cell% 2* field stack-pointer \ stackpointer name
  170:     cell%    field stack-type \ name for default type of stack items
  171:     cell%    field stack-in-index-xt \ ( in-size item -- in-index )
  172:     cell%    field stack-access-transform \ ( nitem -- index )
  173: end-struct stack%
  174: 
  175: struct%
  176:  cell% 2* field item-name   \ name, excluding stack prefixes
  177:  cell%    field item-stack  \ descriptor for the stack used, 0 is default
  178:  cell%    field item-type   \ descriptor for the item type
  179:  cell%    field item-offset \ offset in stack items, 0 for the deepest element
  180:  cell%	  field item-first  \ true if this is the first occurence of the item
  181: end-struct item%
  182: 
  183: struct%
  184:     cell% 2* field type-c-name
  185:     cell%    field type-stack \ default stack
  186:     cell%    field type-size  \ size of type in stack items
  187:     cell%    field type-fetch \ xt of fetch code generator ( item -- )
  188:     cell%    field type-store \ xt of store code generator ( item -- )
  189: end-struct type%
  190: 
  191: struct%
  192:     cell%    field register-number
  193:     cell%    field register-type \ pointer to type
  194:     cell% 2* field register-name \ c name
  195: end-struct register%
  196: 
  197: struct%
  198:     cell% 2* field ss-registers  \ addr u; ss-registers[0] is TOS
  199:                                  \ 0 means: use memory
  200:     cell%    field ss-offset     \ stack pointer offset: sp[-offset] is TOS
  201: end-struct ss% \ stack-state
  202: 
  203: struct%
  204:     cell% max-stacks * field state-sss
  205: end-struct state%
  206: 
  207: variable next-stack-number 0 next-stack-number !
  208: create stacks max-stacks cells allot \ array of stacks
  209: 256 constant max-registers
  210: create registers max-registers cells allot \ array of registers
  211: variable nregisters 0 nregisters ! \ number of registers
  212: 
  213: : stack-in-index ( in-size item -- in-index )
  214:     item-offset @ - 1- ;
  215: 
  216: : inst-in-index ( in-size item -- in-index )
  217:     nip dup item-offset @ swap item-type @ type-size @ + 1- ;
  218: 
  219: : make-stack ( addr-ptr u1 type "stack-name" -- )
  220:     next-stack-number @ max-stacks < s" too many stacks" ?print-error
  221:     create stack% %allot >r
  222:     r@ stacks next-stack-number @ th !
  223:     next-stack-number @ r@ stack-number !
  224:     1 next-stack-number +!
  225:     r@ stack-type !
  226:     save-mem r@ stack-pointer 2! 
  227:     ['] stack-in-index r@ stack-in-index-xt !
  228:     ['] noop r@ stack-access-transform !
  229:     rdrop ;
  230: 
  231: : map-stacks { xt -- }
  232:     \ perform xt for all stacks
  233:     next-stack-number @ 0 +do
  234: 	stacks i th @ xt execute
  235:     loop ;
  236: 
  237: : map-stacks1 { xt -- }
  238:     \ perform xt for all stacks except inst-stream
  239:     next-stack-number @ 1 +do
  240: 	stacks i th @ xt execute
  241:     loop ;
  242: 
  243: \ stack items
  244: 
  245: : init-item ( addr u addr1 -- )
  246:     \ initialize item at addr1 with name addr u
  247:     \ !! remove stack prefix
  248:     dup item% %size erase
  249:     item-name 2! ;
  250: 
  251: : map-items { addr end xt -- }
  252:     \ perform xt for all items in array addr...end
  253:     end addr ?do
  254: 	i xt execute
  255:     item% %size +loop ;
  256: 
  257: \ types
  258: 
  259: : print-type-prefix ( type -- )
  260:     body> >head name>string type ;
  261: 
  262: \ various variables for storing stuff of one primitive
  263: 
  264: struct%
  265:     cell% 2* field prim-name
  266:     cell% 2* field prim-wordset
  267:     cell% 2* field prim-c-name
  268:     cell% 2* field prim-doc
  269:     cell% 2* field prim-c-code
  270:     cell% 2* field prim-forth-code
  271:     cell% 2* field prim-stack-string
  272:     cell%    field prim-num            \ ordinal number
  273:     cell%    field prim-items-wordlist \ unique items
  274:     item% max-effect * field prim-effect-in
  275:     item% max-effect * field prim-effect-out
  276:     cell%    field prim-effect-in-end
  277:     cell%    field prim-effect-out-end
  278:     cell% max-stacks * field prim-stacks-in  \ number of in items per stack
  279:     cell% max-stacks * field prim-stacks-out \ number of out items per stack
  280: end-struct prim%
  281: 
  282: : make-prim ( -- prim )
  283:     prim% %alloc { p }
  284:     s" " p prim-doc 2! s" " p prim-forth-code 2! s" " p prim-wordset 2!
  285:     p ;
  286: 
  287: 0 value prim     \ in combined prims either combined or a part
  288: 0 value combined \ in combined prims the combined prim
  289: variable in-part \ true if processing a part
  290:  in-part off
  291: 0 value state-in  \ state on entering prim
  292: 0 value state-out \ state on exiting prim
  293: 
  294: : prim-context ( ... p xt -- ... )
  295:     \ execute xt with prim set to p
  296:     prim >r
  297:     swap to prim
  298:     catch
  299:     r> to prim
  300:     throw ;
  301: 
  302: 1000 constant max-combined
  303: create combined-prims max-combined cells allot
  304: variable num-combined
  305: variable part-num \ current part number during process-combined
  306: 
  307: : map-combined { xt -- }
  308:     \ perform xt for all components of the current combined instruction
  309:     num-combined @ 0 +do
  310: 	combined-prims i th @ xt execute
  311:     loop ;
  312: 
  313: table constant combinations
  314:   \ the keys are the sequences of pointers to primitives
  315: 
  316: create current-depth max-stacks cells allot
  317: create max-depth     max-stacks cells allot
  318: create min-depth     max-stacks cells allot
  319: 
  320: create sp-update-in max-stacks cells allot
  321: \ where max-depth occured the first time
  322: create max-depths max-stacks max-combined 1+ * cells allot
  323: \ maximum depth at start of each part: array[parts] of array[stack]
  324: create max-back-depths max-stacks max-combined 1+ * cells allot
  325: \ maximun depth from end of the combination to the start of the each part
  326: 
  327: : s-c-max-depth ( nstack ncomponent -- addr )
  328:     max-stacks * + cells max-depths + ;
  329: 
  330: : s-c-max-back-depth ( nstack ncomponent -- addr )
  331:     max-stacks * + cells max-back-depths + ;
  332: 
  333: wordlist constant primitives
  334: 
  335: : create-prim ( prim -- )
  336:     dup prim-name 2@ primitives ['] constant insert-wordlist ;
  337: 
  338: : stack-in ( stack -- addr )
  339:     \ address of number of stack items in effect in
  340:     stack-number @ cells prim prim-stacks-in + ;
  341: 
  342: : stack-out ( stack -- addr )
  343:     \ address of number of stack items in effect out
  344:     stack-number @ cells prim prim-stacks-out + ;
  345: 
  346: \ global vars
  347: variable c-line
  348: 2variable c-filename
  349: variable name-line
  350: 2variable name-filename
  351: 2variable last-name-filename
  352: Variable function-number 0 function-number !
  353: Variable function-old 0 function-old !
  354: : function-diff ( n -- )
  355:     ." GROUPADD(" function-number @ function-old @ - 0 .r ." )" cr
  356:     function-number @ function-old ! ;
  357: : forth-fdiff ( -- )
  358:     function-number @ function-old @ - 0 .r ."  groupadd" cr
  359:     function-number @ function-old ! ;
  360: 
  361: \ a few more set ops
  362: 
  363: : bit-equivalent ( w1 w2 -- w3 )
  364:  xor invert ;
  365: 
  366: : complement ( set1 -- set2 )
  367:  empty ['] bit-equivalent binary-set-operation ;
  368: 
  369: \ forward declaration for inst-stream (breaks cycle in definitions)
  370: defer inst-stream-f ( -- stack )
  371: 
  372: \ stack access stuff
  373: 
  374: : normal-stack-access0 { n stack -- }
  375:     \ n has the ss-offset already applied (see ...-access1)
  376:     n stack stack-access-transform @ execute ." [" 0 .r ." ]" ;
  377: 
  378: : state-ss { stack state -- ss }
  379:     state state-sss stack stack-number @ th @ ;
  380: 
  381: : stack-reg { n stack state -- reg }
  382:     \ n is the index (TOS=0); reg is 0 if the access is to memory
  383:     stack state state-ss ss-registers 2@ n u> if ( addr ) \ in ss-registers?
  384: 	n th @
  385:     else
  386: 	drop 0
  387:     endif ;
  388: 
  389: : normal-stack-access1 { n stack state -- }
  390:     n stack state stack-reg ?dup-if
  391: 	register-name 2@ type exit
  392:     endif
  393:     stack stack-pointer 2@ type
  394:     n stack state state-ss ss-offset @ - stack normal-stack-access0 ;
  395: 
  396: : normal-stack-access ( n stack state -- )
  397:     over inst-stream-f = if
  398: 	." IMM_ARG(" normal-stack-access1 ." ," immarg ? ." )"
  399: 	1 immarg +!
  400:     else
  401: 	normal-stack-access1
  402:     endif ;
  403: 
  404: : stack-depth { stack -- n }
  405:     current-depth stack stack-number @ th @ ;
  406: 
  407: : part-stack-access { n stack -- }
  408:     \ print _<stack><x>, x=inst-stream? n : maxdepth-currentdepth-n-1
  409:     ." _" stack stack-pointer 2@ type
  410:     stack stack-number @ { stack# }
  411:     stack stack-depth n + { access-depth }
  412:     stack inst-stream-f = if
  413: 	access-depth
  414:     else
  415: 	combined prim-stacks-in stack# th @
  416: 	assert( dup max-depth stack# th @ = )
  417: 	access-depth - 1-
  418:     endif
  419:     0 .r ;
  420: 
  421: : part-stack-read { n stack -- }
  422:     stack stack-depth n + ( ndepth )
  423:     stack stack-number @ part-num @ s-c-max-depth @
  424: \    max-depth stack stack-number @ th @ ( ndepth nmaxdepth )
  425:     over <= if ( ndepth ) \ load from memory
  426: 	stack state-in normal-stack-access
  427:     else
  428: 	drop n stack part-stack-access
  429:     endif ;
  430: 
  431: : stack-diff ( stack -- n )
  432:     \ in-out
  433:     dup stack-in @ swap stack-out @ - ;
  434: 
  435: : part-stack-write { n stack -- }
  436:     stack stack-depth n +
  437:     stack stack-number @ part-num @ s-c-max-back-depth @
  438:     over <= if ( ndepth )
  439: 	stack combined ['] stack-diff prim-context -
  440: 	stack state-out normal-stack-access
  441:     else
  442: 	drop n stack part-stack-access
  443:     endif ;
  444: 
  445: : stack-read ( n stack -- )
  446:     \ print a stack access at index n of stack
  447:     in-part @ if
  448: 	part-stack-read
  449:     else
  450: 	state-in normal-stack-access
  451:     endif ;
  452: 
  453: : stack-write ( n stack -- )
  454:     \ print a stack access at index n of stack
  455:     in-part @ if
  456: 	part-stack-write
  457:     else
  458: 	state-out normal-stack-access
  459:     endif ;
  460: 
  461: : item-in-index { item -- n }
  462:     \ n is the index of item (in the in-effect)
  463:     item item-stack @ dup >r stack-in @ ( in-size r:stack )
  464:     item r> stack-in-index-xt @ execute ;
  465: 
  466: : item-stack-type-name ( item -- addr u )
  467:     item-stack @ stack-type @ type-c-name 2@ ;
  468: 
  469: : fetch-single ( item -- )
  470:     \ fetch a single stack item from its stack
  471:     >r
  472:     ." vm_" r@ item-stack-type-name type
  473:     ." 2" r@ item-type @ print-type-prefix ." ("
  474:     r@ item-in-index r@ item-stack @ stack-read ." ,"
  475:     r@ item-name 2@ type
  476:     ." );" cr
  477:     rdrop ; 
  478: 
  479: : fetch-double ( item -- )
  480:     \ fetch a double stack item from its stack
  481:     >r
  482:     ." vm_two"
  483:     r@ item-stack-type-name type ." 2"
  484:     r@ item-type @ print-type-prefix ." ("
  485:     r@ item-in-index r@ item-stack @ 2dup ." (Cell)" stack-read
  486:     ." , "                      -1 under+ ." (Cell)" stack-read
  487:     ." , " r@ item-name 2@ type
  488:     ." )" cr
  489:     rdrop ;
  490: 
  491: : same-as-in? ( item -- f )
  492:  \ f is true iff the offset and stack of item is the same as on input
  493:  >r
  494:  r@ item-first @ if
  495:      rdrop false exit
  496:  endif
  497:  r@ item-name 2@ prim prim-items-wordlist @ search-wordlist 0= abort" bug"
  498:  execute @
  499:  dup r@ =
  500:  if \ item first appeared in output
  501:    drop false
  502:  else
  503:    dup  item-stack  @ r@ item-stack  @ = 
  504:    swap item-offset @ r@ item-offset @ = and
  505:  endif
  506:  rdrop ;
  507: 
  508: : item-out-index ( item -- n )
  509:     \ n is the index of item (in the out-effect)
  510:     >r r@ item-stack @ stack-out @ r> item-offset @ - 1- ;
  511: 
  512: : really-store-single ( item -- )
  513:     >r
  514:     ." vm_"
  515:     r@ item-type @ print-type-prefix ." 2"
  516:     r@ item-stack-type-name type ." ("
  517:     r@ item-name 2@ type ." ,"
  518:     r@ item-out-index r@ item-stack @ stack-write ." );"
  519:     rdrop ;
  520: 
  521: : store-single { item -- }
  522:     item item-stack @ { stack }
  523:     store-optimization @ in-part @ 0= and item same-as-in? and
  524:     item item-in-index  stack state-in  stack-reg 0= and \  in in memory?
  525:     item item-out-index stack state-out stack-reg 0= and \ out in memory?
  526:     0= if
  527: 	item really-store-single cr
  528:     endif ;
  529: 
  530: : store-double ( item -- )
  531: \ !! store optimization is not performed, because it is not yet needed
  532:  >r
  533:  ." vm_"
  534:  r@ item-type @ print-type-prefix ." 2two"
  535:  r@ item-stack-type-name type ." ("
  536:  r@ item-name 2@ type ." , "
  537:  r@ item-out-index r@ item-stack @ 2dup stack-write
  538:  ." , "                       -1 under+ stack-write
  539:  ." )" cr
  540:  rdrop ;
  541: 
  542: : single ( -- xt1 xt2 n )
  543:     ['] fetch-single ['] store-single 1 ;
  544: 
  545: : double ( -- xt1 xt2 n )
  546:     ['] fetch-double ['] store-double 2 ;
  547: 
  548: : s, ( addr u -- )
  549: \ allocate a string
  550:  here swap dup allot move ;
  551: 
  552: wordlist constant prefixes
  553: 
  554: : declare ( addr "name" -- )
  555: \ remember that there is a stack item at addr called name
  556:  create , ;
  557: 
  558: : !default ( w addr -- )
  559:     dup @ if
  560: 	2drop \ leave nonzero alone
  561:     else
  562: 	!
  563:     endif ;
  564: 
  565: : create-type { addr u xt1 xt2 n stack -- } ( "prefix" -- )
  566:     \ describes a type
  567:     \ addr u specifies the C type name
  568:     \ stack effect entries of the type start with prefix
  569:     create type% %allot >r
  570:     addr u save-mem r@ type-c-name 2!
  571:     xt1   r@ type-fetch !
  572:     xt2   r@ type-store !
  573:     n     r@ type-size !
  574:     stack r@ type-stack !
  575:     rdrop ;
  576: 
  577: : type-prefix ( addr u xt1 xt2 n stack "prefix" -- )
  578:     get-current >r prefixes set-current
  579:     create-type r> set-current
  580: does> ( item -- )
  581:     \ initialize item
  582:     { item typ }
  583:     typ item item-type !
  584:     typ type-stack @ item item-stack !default
  585:     item item-name 2@ prim prim-items-wordlist @ search-wordlist 0= if
  586: 	item item-name 2@ nextname item declare
  587: 	item item-first on
  588: 	\ typ type-c-name 2@ type space type  ." ;" cr
  589:     else
  590: 	drop
  591: 	item item-first off
  592:     endif ;
  593: 
  594: : execute-prefix ( item addr1 u1 -- )
  595:     \ execute the word ( item -- ) associated with the longest prefix
  596:     \ of addr1 u1
  597:     0 swap ?do
  598: 	dup i prefixes search-wordlist
  599: 	if \ ok, we have the type ( item addr1 xt )
  600: 	    nip execute
  601: 	    UNLOOP EXIT
  602: 	endif
  603: 	-1 s+loop
  604:     \ we did not find a type, abort
  605:     false s" unknown prefix" ?print-error ;
  606: 
  607: : declaration ( item -- )
  608:     dup item-name 2@ execute-prefix ;
  609: 
  610: : declaration-list ( addr1 addr2 -- )
  611:     ['] declaration map-items ;
  612: 
  613: : declarations ( -- )
  614:  wordlist dup prim prim-items-wordlist ! set-current
  615:  prim prim-effect-in prim prim-effect-in-end @ declaration-list
  616:  prim prim-effect-out prim prim-effect-out-end @ declaration-list ;
  617: 
  618: : print-declaration { item -- }
  619:     item item-first @ if
  620: 	item item-type @ type-c-name 2@ type space
  621: 	item item-name 2@ type ." ;" cr
  622:     endif ;
  623: 
  624: : print-declarations ( -- )
  625:     prim prim-effect-in  prim prim-effect-in-end  @ ['] print-declaration map-items
  626:     prim prim-effect-out prim prim-effect-out-end @ ['] print-declaration map-items ;
  627:     
  628: : stack-prefix ( stack "prefix" -- )
  629:     get-current >r prefixes set-current
  630:     name tuck nextname create ( stack length ) 2,
  631:     r> set-current
  632: does> ( item -- )
  633:     2@ { item stack prefix-length }
  634:     item item-name 2@ prefix-length /string item item-name 2!
  635:     stack item item-stack !
  636:     item declaration ;
  637: 
  638: \ types pointed to by stacks for use in combined prims
  639: \ !! output-c-combined shouldn't use these names!
  640: : stack-type-name ( addr u "name" -- )
  641:     single 0 create-type ;
  642: 
  643: wordlist constant type-names \ this is here just to meet the requirement
  644:                     \ that a type be a word; it is never used for lookup
  645: 
  646: : define-type ( addr u -- xt )
  647:     \ define single type with name addr u, without stack
  648:     get-current type-names set-current >r
  649:     2dup nextname stack-type-name
  650:     r> set-current
  651:     latestxt ;
  652: 
  653: : stack ( "name" "stack-pointer" "type" -- )
  654:     \ define stack
  655:     name { d: stack-name }
  656:     name { d: stack-pointer }
  657:     name { d: stack-type }
  658:     stack-type define-type
  659:     stack-pointer rot >body stack-name nextname make-stack ;
  660: 
  661: stack inst-stream IP Cell
  662: ' inst-in-index inst-stream stack-in-index-xt !
  663: ' inst-stream <is> inst-stream-f
  664: \ !! initialize stack-in and stack-out
  665: 
  666: \ registers
  667: 
  668: : make-register ( type addr u -- )
  669:     \ define register with type TYPE and name ADDR U.
  670:     nregisters @ max-registers < s" too many registers" ?print-error
  671:     2dup nextname create register% %allot >r
  672:     r@ register-name 2!
  673:     r@ register-type !
  674:     nregisters @ r@ register-number !
  675:     1 nregisters +!
  676:     rdrop ;
  677: 
  678: : register ( "name" "type" -- )
  679:     \ define register
  680:     name { d: reg-name }
  681:     name { d: reg-type }
  682:     reg-type define-type >body
  683:     reg-name make-register ;
  684: 
  685: \ stack-states
  686: 
  687: : stack-state ( a-addr u uoffset "name" -- )
  688:     create ss% %allot >r
  689:     r@ ss-offset !
  690:     r@ ss-registers 2!
  691:     rdrop ;
  692: 
  693: 0 0 0 stack-state default-ss
  694: 
  695: \ state
  696: 
  697: : state ( "name" -- )
  698:     \ create a state initialized with default-sss
  699:     create state% %allot state-sss { sss }
  700:     max-stacks 0 ?do
  701: 	default-ss sss i th !
  702:     loop ;
  703: 
  704: : set-ss ( ss stack state -- )
  705:     state-sss swap stack-number @ th ! ;
  706: 
  707: \ offset computation
  708: \ the leftmost (i.e. deepest) item has offset 0
  709: \ the rightmost item has the highest offset
  710: 
  711: : compute-offset { item xt -- }
  712:     \ xt specifies in/out; update stack-in/out and set item-offset
  713:     item item-type @ type-size @
  714:     item item-stack @ xt execute dup @ >r +!
  715:     r> item item-offset ! ;
  716: 
  717: : compute-offset-in ( addr1 addr2 -- )
  718:     ['] stack-in compute-offset ;
  719: 
  720: : compute-offset-out ( addr1 addr2 -- )
  721:     ['] stack-out compute-offset ;
  722: 
  723: : compute-offsets ( -- )
  724:     prim prim-stacks-in  max-stacks cells erase
  725:     prim prim-stacks-out max-stacks cells erase
  726:     prim prim-effect-in  prim prim-effect-in-end  @ ['] compute-offset-in  map-items
  727:     prim prim-effect-out prim prim-effect-out-end @ ['] compute-offset-out map-items
  728:     inst-stream stack-out @ 0= s" # can only be on the input side" ?print-error ;
  729: 
  730: : process-simple ( -- )
  731:     prim prim { W^ key } key cell
  732:     combinations ['] constant insert-wordlist
  733:     declarations compute-offsets
  734:     output @ execute ;
  735: 
  736: : flush-a-tos { stack -- }
  737:     stack stack-out @ 0<> stack stack-in @ 0= and
  738:     if
  739: 	." IF_" stack stack-pointer 2@ 2dup type ." TOS("
  740: 	2dup type 0 stack normal-stack-access0 ."  = " type ." TOS);" cr
  741:     endif ;
  742: 
  743: : flush-tos ( -- )
  744:     ['] flush-a-tos map-stacks1 ;
  745: 
  746: : fill-a-tos { stack -- }
  747:     stack stack-out @ 0= stack stack-in @ 0<> and
  748:     if
  749: 	." IF_" stack stack-pointer 2@ 2dup type ." TOS("
  750: 	2dup type ." TOS = " type 0 stack normal-stack-access0 ." );" cr
  751:     endif ;
  752: 
  753: : fill-tos ( -- )
  754:     \ !! inst-stream for prefetching?
  755:     ['] fill-a-tos map-stacks1 ;
  756: 
  757: : fetch ( addr -- )
  758:     dup item-type @ type-fetch @ execute ;
  759: 
  760: : fetches ( -- )
  761:     prim prim-effect-in prim prim-effect-in-end @ ['] fetch map-items ;
  762: 
  763: : stack-update-transform ( n1 stack -- n2 )
  764:     \ n2 is the number by which the stack pointer should be
  765:     \ incremented to pop n1 items
  766:     stack-access-transform @ dup >r execute
  767:     0 r> execute - ;
  768: 
  769: : stack-pointer-update { stack -- }
  770:     \ stacks grow downwards
  771:     stack stack-diff
  772:     ?dup-if \ this check is not necessary, gcc would do this for us
  773: 	stack inst-stream = if
  774: 	    ." INC_IP(" 0 .r ." );" cr
  775: 	else
  776: 	    stack stack-pointer 2@ type ."  += "
  777: 	    stack stack-update-transform 0 .r ." ;" cr
  778: 	endif
  779:     endif ;
  780: 
  781: : stack-pointer-updates ( -- )
  782:     ['] stack-pointer-update map-stacks ;
  783: 
  784: : store ( item -- )
  785: \ f is true if the item should be stored
  786: \ f is false if the store is probably not necessary
  787:  dup item-type @ type-store @ execute ;
  788: 
  789: : stores ( -- )
  790:     prim prim-effect-out prim prim-effect-out-end @ ['] store map-items ;
  791: 
  792: : print-debug-arg { item -- }
  793:     ." fputs(" quote space item item-name 2@ type ." =" quote ." , vm_out); "
  794:     ." printarg_" item item-type @ print-type-prefix
  795:     ." (" item item-name 2@ type ." );" cr ;
  796:     
  797: : print-debug-args ( -- )
  798:     ." #ifdef VM_DEBUG" cr
  799:     ." if (vm_debug) {" cr
  800:     prim prim-effect-in prim prim-effect-in-end @ ['] print-debug-arg map-items
  801: \    ." fputc('\n', vm_out);" cr
  802:     ." }" cr
  803:     ." #endif" cr ;
  804: 
  805: : print-debug-result { item -- }
  806:     item item-first @ if
  807: 	item print-debug-arg
  808:     endif ;
  809: 
  810: : print-debug-results ( -- )
  811:     cr
  812:     ." #ifdef VM_DEBUG" cr
  813:     ." if (vm_debug) {" cr
  814:     ." fputs(" quote ."  -- " quote ." , vm_out); "
  815:     prim prim-effect-out prim prim-effect-out-end @ ['] print-debug-result map-items
  816:     ." fputc('\n', vm_out);" cr
  817:     ." }" cr
  818:     ." #endif" cr ;
  819: 
  820: : output-super-end ( -- )
  821:     prim prim-c-code 2@ s" SET_IP" search if
  822: 	." SUPER_END;" cr
  823:     endif
  824:     2drop ;
  825: 
  826: : output-nextp2 ( -- )
  827:     ." NEXT_P2;" cr ;
  828: 
  829: variable tail-nextp2 \ xt to execute for printing NEXT_P2 in INST_TAIL
  830: ' output-nextp2 tail-nextp2 !
  831: 
  832: : output-label2 ( -- )
  833:     ." LABEL2(" prim prim-c-name 2@ type ." )" cr
  834:     ." NEXT_P2;" cr ;
  835: 
  836: : output-c-tail1 { xt -- }
  837:     \ the final part of the generated C code, with xt printing LABEL2 or not.
  838:     output-super-end
  839:     print-debug-results
  840:     ." NEXT_P1;" cr
  841:     stores
  842:     fill-tos 
  843:     xt execute ;
  844: 
  845: : output-c-tail1-no-stores { xt -- }
  846:     \ the final part of the generated C code for combinations
  847:     output-super-end
  848:     ." NEXT_P1;" cr
  849:     fill-tos 
  850:     xt execute ;
  851: 
  852: : output-c-tail ( -- )
  853:     tail-nextp2 @ output-c-tail1 ;
  854: 
  855: : output-c-tail2 ( -- )
  856:     ['] output-label2 output-c-tail1 ;
  857: 
  858: : output-c-tail-no-stores ( -- )
  859:     tail-nextp2 @ output-c-tail1-no-stores ;
  860: 
  861: : output-c-tail2-no-stores ( -- )
  862:     ['] output-label2 output-c-tail1-no-stores ;
  863: 
  864: : type-c-code ( c-addr u xt -- )
  865:     \ like TYPE, but replaces "INST_TAIL;" with tail code produced by xt
  866:     { xt }
  867:     ." {" cr
  868:     ." #line " c-line @ . quote c-filename 2@ type quote cr
  869:     begin ( c-addr1 u1 )
  870: 	2dup s" INST_TAIL;" search
  871:     while ( c-addr1 u1 c-addr3 u3 )
  872: 	2dup 2>r drop nip over - type
  873: 	xt execute
  874: 	2r> 10 /string
  875: 	\ !! resync #line missing
  876:     repeat
  877:     2drop type
  878:     ." #line " out-nls @ 2 + . quote out-filename 2@ type quote cr
  879:     ." }" cr ;
  880: 
  881: : print-entry ( -- )
  882:     ." LABEL(" prim prim-c-name 2@ type ." )" ;
  883:     
  884: : output-c ( -- ) 
  885:     print-entry ."  /* " prim prim-name 2@ type ."  ( " prim prim-stack-string 2@ type ." ) */" cr
  886:     ." /* " prim prim-doc 2@ type ."  */" cr
  887:     ." NAME(" quote prim prim-name 2@ type quote ." )" cr \ debugging
  888:     ." {" cr
  889:     ." DEF_CA" cr
  890:     print-declarations
  891:     ." NEXT_P0;" cr
  892:     flush-tos
  893:     fetches
  894:     print-debug-args
  895:     stack-pointer-updates
  896:     prim prim-c-code 2@ ['] output-c-tail type-c-code
  897:     output-c-tail2
  898:     ." }" cr
  899:     cr
  900: ;
  901: 
  902: : disasm-arg { item -- }
  903:     item item-stack @ inst-stream = if
  904: 	." {" cr
  905: 	item print-declaration
  906: 	item fetch
  907: 	item print-debug-arg
  908: 	." }" cr
  909:     endif ;
  910: 
  911: : disasm-args ( -- )
  912:     prim prim-effect-in prim prim-effect-in-end @ ['] disasm-arg map-items ;
  913: 
  914: : output-disasm ( -- )
  915:     \ generate code for disassembling VM instructions
  916:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
  917:     ."   fputs(" quote prim prim-name 2@ type quote ." , vm_out);" cr
  918:     disasm-args
  919:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
  920:     ."   goto _endif_;" cr
  921:     ." }" cr ;
  922: 
  923: : output-profile ( -- )
  924:     \ generate code for postprocessing the VM block profile stuff
  925:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
  926:     ."   add_inst(b, " quote prim prim-name 2@ type quote ." );" cr
  927:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
  928:     prim prim-c-code 2@  s" SET_IP"    search nip nip
  929:     prim prim-c-code 2@  s" SUPER_END" search nip nip or if
  930: 	."   return;" cr
  931:     else
  932: 	."   goto _endif_;" cr
  933:     endif
  934:     ." }" cr ;
  935: 
  936: : output-profile-part ( p )
  937:     ."   add_inst(b, " quote
  938:     prim-name 2@ type
  939:     quote ." );" cr ;
  940:     
  941: : output-profile-combined ( -- )
  942:     \ generate code for postprocessing the VM block profile stuff
  943:     ." if (VM_IS_INST(*ip, " function-number @ 0 .r ." )) {" cr
  944:     ['] output-profile-part map-combined
  945:     ."   ip += " inst-stream stack-in @ 1+ 0 .r ." ;" cr
  946:     combined-prims num-combined @ 1- th @ prim-c-code 2@  s" SET_IP"    search nip nip
  947:     combined-prims num-combined @ 1- th @ prim-c-code 2@  s" SUPER_END" search nip nip or if
  948: 	."   return;" cr
  949:     else
  950: 	."   goto _endif_;" cr
  951:     endif
  952:     ." }" cr ;
  953: 
  954: : prim-branch? { prim -- f }
  955:     \ true if prim is a branch or super-end
  956:     prim prim-c-code 2@  s" SET_IP" search nip nip 0<> ;
  957: 
  958: : output-superend ( -- )
  959:     \ output flag specifying whether the current word ends a dynamic superinst
  960:     prim prim-branch?
  961:     prim prim-c-code 2@  s" SUPER_END" search nip nip 0<> or
  962:     prim prim-c-code 2@  s" SUPER_CONTINUE" search nip nip 0= and
  963:     negate 0 .r ." , /* " prim prim-name 2@ type ."  */" cr ;
  964: 
  965: : gen-arg-parm { item -- }
  966:     item item-stack @ inst-stream = if
  967: 	." , " item item-type @ type-c-name 2@ type space
  968: 	item item-name 2@ type
  969:     endif ;
  970: 
  971: : gen-args-parm ( -- )
  972:     prim prim-effect-in prim prim-effect-in-end @ ['] gen-arg-parm map-items ;
  973: 
  974: : gen-arg-gen { item -- }
  975:     item item-stack @ inst-stream = if
  976: 	."   genarg_" item item-type @ print-type-prefix
  977:         ." (ctp, " item item-name 2@ type ." );" cr
  978:     endif ;
  979: 
  980: : gen-args-gen ( -- )
  981:     prim prim-effect-in prim prim-effect-in-end @ ['] gen-arg-gen map-items ;
  982: 
  983: : output-gen ( -- )
  984:     \ generate C code for generating VM instructions
  985:     ." void gen_" prim prim-c-name 2@ type ." (Inst **ctp" gen-args-parm ." )" cr
  986:     ." {" cr
  987:     ."   gen_inst(ctp, vm_prim[" function-number @ 0 .r ." ]);" cr
  988:     gen-args-gen
  989:     ." }" cr ;
  990: 
  991: : stack-used? { stack -- f }
  992:     stack stack-in @ stack stack-out @ or 0<> ;
  993: 
  994: : output-funclabel ( -- )
  995:   ." &I_" prim prim-c-name 2@ type ." ," cr ;
  996: 
  997: : output-forthname ( -- )
  998:   '" emit prim prim-name 2@ type '" emit ." ," cr ;
  999: 
 1000: \  : output-c-func ( -- )
 1001: \  \ used for word libraries
 1002: \      ." Cell * I_" prim prim-c-name 2@ type ." (Cell *SP, Cell **FP)      /* " prim prim-name 2@ type
 1003: \      ."  ( " prim prim-stack-string 2@ type ."  ) */" cr
 1004: \      ." /* " prim prim-doc 2@ type ."  */" cr
 1005: \      ." NAME(" quote prim prim-name 2@ type quote ." )" cr
 1006: \      \ debugging
 1007: \      ." {" cr
 1008: \      print-declarations
 1009: \      \ !! don't know what to do about that
 1010: \      inst-stream  stack-used? IF ." Cell *ip=IP;" cr THEN
 1011: \      data-stack   stack-used? IF ." Cell *sp=SP;" cr THEN
 1012: \      fp-stack     stack-used? IF ." Cell *fp=*FP;" cr THEN
 1013: \      return-stack stack-used? IF ." Cell *rp=*RP;" cr THEN
 1014: \      flush-tos
 1015: \      fetches
 1016: \      stack-pointer-updates
 1017: \      fp-stack   stack-used? IF ." *FP=fp;" cr THEN
 1018: \      ." {" cr
 1019: \      ." #line " c-line @ . quote c-filename 2@ type quote cr
 1020: \      prim prim-c-code 2@ type
 1021: \      ." }" cr
 1022: \      stores
 1023: \      fill-tos
 1024: \      ." return (sp);" cr
 1025: \      ." }" cr
 1026: \      cr ;
 1027: 
 1028: : output-label ( -- )  
 1029:     ." INST_ADDR(" prim prim-c-name 2@ type ." )," cr ;
 1030: 
 1031: : output-alias ( -- ) 
 1032:     ( primitive-number @ . ." alias " ) ." Primitive " prim prim-name 2@ type cr ;
 1033: 
 1034: : output-c-prim-num ( -- )
 1035:     ." N_" prim prim-c-name 2@ type ." ," cr ;
 1036: 
 1037: : output-forth ( -- )  
 1038:     prim prim-forth-code @ 0=
 1039:     IF    	\ output-alias
 1040: 	\ this is bad for ec: an alias is compiled if tho word does not exist!
 1041: 	\ JAW
 1042:     ELSE  ." : " prim prim-name 2@ type ."   ( "
 1043: 	prim prim-stack-string 2@ type ." )" cr
 1044: 	prim prim-forth-code 2@ type cr
 1045:     THEN ;
 1046: 
 1047: : output-tag-file ( -- )
 1048:     name-filename 2@ last-name-filename 2@ compare if
 1049: 	name-filename 2@ last-name-filename 2!
 1050: 	#ff emit cr
 1051: 	name-filename 2@ type
 1052: 	." ,0" cr
 1053:     endif ;
 1054: 
 1055: : output-tag ( -- )
 1056:     output-tag-file
 1057:     prim prim-name 2@ 1+ type
 1058:     127 emit
 1059:     space prim prim-name 2@ type space
 1060:     1 emit
 1061:     name-line @ 0 .r
 1062:     ." ,0" cr ;
 1063: 
 1064: : output-vi-tag ( -- )
 1065:     name-filename 2@ type #tab emit
 1066:     prim prim-name 2@ type #tab emit
 1067:     ." /^" prim prim-name 2@ type ."  *(/" cr ;
 1068: 
 1069: [IFDEF] documentation
 1070: : register-doc ( -- )
 1071:     prim prim-name 2@ documentation ['] create insert-wordlist
 1072:     prim prim-name 2@ 2,
 1073:     prim prim-stack-string 2@ condition-stack-effect 2,
 1074:     prim prim-wordset 2@ 2,
 1075:     prim prim-c-name 2@ condition-pronounciation 2,
 1076:     prim prim-doc 2@ 2, ;
 1077: [THEN]
 1078: 
 1079: 
 1080: \ combining instructions
 1081: 
 1082: \ The input should look like this:
 1083: 
 1084: \ lit_+ = lit +
 1085: 
 1086: \ The output should look like this:
 1087: 
 1088: \  I_lit_+:
 1089: \  {
 1090: \  DEF_CA
 1091: \  Cell _x_ip0;
 1092: \  Cell _x_sp0;
 1093: \  Cell _x_sp1;
 1094: \  NEXT_P0;
 1095: \  _x_ip0 = (Cell) IPTOS;
 1096: \  _x_sp0 = (Cell) spTOS;
 1097: \  INC_IP(1);
 1098: \  /* sp += 0; */
 1099: \  /* lit ( #w -- w ) */
 1100: \  /*  */
 1101: \  NAME("lit")
 1102: \  {
 1103: \  Cell w;
 1104: \  w = (Cell) _x_ip0;
 1105: \  #ifdef VM_DEBUG
 1106: \  if (vm_debug) {
 1107: \  fputs(" w=", vm_out); printarg_w (w);
 1108: \  fputc('\n', vm_out);
 1109: \  }
 1110: \  #endif
 1111: \  {
 1112: \  #line 136 "./prim"
 1113: \  }
 1114: \  _x_sp1 = (Cell)w;
 1115: \  }
 1116: \  I_plus:	/* + ( n1 n2 -- n ) */
 1117: \  /*  */
 1118: \  NAME("+")
 1119: \  {
 1120: \  DEF_CA
 1121: \  Cell n1;
 1122: \  Cell n2;
 1123: \  Cell n;
 1124: \  NEXT_P0;
 1125: \  n1 = (Cell) _x_sp0;
 1126: \  n2 = (Cell) _x_sp1;
 1127: \  #ifdef VM_DEBUG
 1128: \  if (vm_debug) {
 1129: \  fputs(" n1=", vm_out); printarg_n (n1);
 1130: \  fputs(" n2=", vm_out); printarg_n (n2);
 1131: \  fputc('\n', vm_out);
 1132: \  }
 1133: \  #endif
 1134: \  {
 1135: \  #line 516 "./prim"
 1136: \  n = n1+n2;
 1137: \  }
 1138: \  _x_sp0 = (Cell)n;
 1139: \  }
 1140: \  NEXT_P1;
 1141: \  spTOS = (Cell)_x_sp0;
 1142: \  NEXT_P2;
 1143: 
 1144: : init-combined ( -- )
 1145:     prim to combined
 1146:     0 num-combined !
 1147:     current-depth max-stacks cells erase
 1148:     include-skipped-insts @ current-depth 0 th !
 1149:     max-depth     max-stacks cells erase
 1150:     min-depth     max-stacks cells erase
 1151:     prim prim-effect-in  prim prim-effect-in-end  !
 1152:     prim prim-effect-out prim prim-effect-out-end ! ;
 1153: 
 1154: : max! ( n addr -- )
 1155:     tuck @ max swap ! ;
 1156: 
 1157: : min! ( n addr -- )
 1158:     tuck @ min swap ! ;
 1159: 
 1160: : inst-stream-adjustment ( nstack -- n )
 1161:     \ number of stack items to add for each part
 1162:     0= include-skipped-insts @ and negate ;
 1163: 
 1164: : add-depths { p -- }
 1165:     \ combine stack effect of p with *-depths
 1166:     max-stacks 0 ?do
 1167: 	current-depth i th @
 1168: 	p prim-stacks-in  i th @ + i inst-stream-adjustment +
 1169: 	dup max-depth i th max!
 1170: 	p prim-stacks-out i th @ -
 1171: 	dup min-depth i th min!
 1172: 	current-depth i th !
 1173:     loop ;
 1174: 
 1175: : copy-maxdepths ( n -- )
 1176:     max-depth max-depths rot max-stacks * th max-stacks cells move ;
 1177: 
 1178: : add-prim ( addr u -- )
 1179:     \ add primitive given by "addr u" to combined-prims
 1180:     primitives search-wordlist s" unknown primitive" ?print-error
 1181:     execute { p }
 1182:     p combined-prims num-combined @ th !
 1183:     num-combined @ copy-maxdepths
 1184:     1 num-combined +!
 1185:     p add-depths
 1186:     num-combined @ copy-maxdepths ;
 1187: 
 1188: : compute-effects { q -- }
 1189:     \ compute the stack effects of q from the depths
 1190:     max-stacks 0 ?do
 1191: 	max-depth i th @ dup
 1192: 	q prim-stacks-in i th !
 1193: 	current-depth i th @ -
 1194: 	q prim-stacks-out i th !
 1195:     loop ;
 1196: 
 1197: : make-effect-items { stack# items effect-endp -- }
 1198:     \ effect-endp points to a pointer to the end of the current item-array
 1199:     \ and has to be updated
 1200:     stacks stack# th @ { stack }
 1201:     items 0 +do
 1202: 	effect-endp @ { item }
 1203: 	i 0 <# #s stack stack-pointer 2@ holds [char] _ hold #> save-mem
 1204: 	item item-name 2!
 1205: 	stack item item-stack !
 1206: 	stack stack-type @ item item-type !
 1207: 	i item item-offset !
 1208: 	item item-first on
 1209: 	item% %size effect-endp +!
 1210:     loop ;
 1211: 
 1212: : init-effects { q -- }
 1213:     \ initialize effects field for FETCHES and STORES
 1214:     max-stacks 0 ?do
 1215: 	i q prim-stacks-in  i th @ q prim-effect-in-end  make-effect-items
 1216: 	i q prim-stacks-out i th @ q prim-effect-out-end make-effect-items
 1217:     loop ;
 1218: 
 1219: : compute-stack-max-back-depths ( stack -- )
 1220:     stack-number @ { stack# }
 1221:     current-depth stack# th @ dup
 1222:     dup stack# num-combined @ s-c-max-back-depth !
 1223:     -1 num-combined @ 1- -do ( max-depth current-depth )
 1224: 	combined-prims i th @ { p }
 1225: 	p prim-stacks-out stack# th @ +
 1226: 	dup >r max r>
 1227: 	over stack# i s-c-max-back-depth !
 1228: 	p prim-stacks-in stack# th @ -
 1229: 	stack# inst-stream-adjustment -
 1230:     1 -loop
 1231:     assert( dup stack# inst-stream-adjustment negate = )
 1232:     assert( over max-depth stack# th @ = )
 1233:     2drop ;
 1234: 
 1235: : compute-max-back-depths ( -- )
 1236:     \ compute max-back-depths.
 1237:     \ assumes that current-depths is correct for the end of the combination
 1238:     ['] compute-stack-max-back-depths map-stacks ;
 1239: 
 1240: : process-combined ( -- )
 1241:     combined combined-prims num-combined @ cells
 1242:     combinations ['] constant insert-wordlist
 1243:     combined-prims num-combined @ 1- th ( last-part )
 1244:     @ prim-c-code 2@ prim prim-c-code 2! \ used by output-super-end
 1245:     prim compute-effects
 1246:     prim init-effects
 1247:     compute-max-back-depths
 1248:     output-combined perform ;
 1249: 
 1250: \ C output
 1251: 
 1252: : print-item { n stack -- }
 1253:     \ print nth stack item name
 1254:     stack stack-type @ type-c-name 2@ type space
 1255:     ." MAYBE_UNUSED _" stack stack-pointer 2@ type n 0 .r ;
 1256: 
 1257: : print-declarations-combined ( -- )
 1258:     max-stacks 0 ?do
 1259: 	max-depth i th @ min-depth i th @ - 0 +do
 1260: 	    i stacks j th @ print-item ." ;" cr
 1261: 	loop
 1262:     loop ;
 1263: 
 1264: : part-fetches ( -- )
 1265:     fetches ;
 1266: 
 1267: : part-output-c-tail ( -- )
 1268:     print-debug-results
 1269:     stores ;
 1270: 
 1271: : output-combined-tail ( -- )
 1272:     part-output-c-tail
 1273:     in-part @ >r in-part off
 1274:     combined ['] output-c-tail-no-stores prim-context
 1275:     r> in-part ! ;
 1276: 
 1277: : part-stack-pointer-updates ( -- )
 1278:     next-stack-number @ 0 +do
 1279: 	i part-num @ 1+ s-c-max-depth @ dup
 1280: 	i num-combined @ s-c-max-depth @ =    \ final depth
 1281: 	swap i part-num @ s-c-max-depth @ <> \ just reached now
 1282: 	part-num @ 0= \ first part
 1283: 	or and if
 1284: 	    stacks i th @ stack-pointer-update
 1285: 	endif
 1286:     loop ;
 1287: 
 1288: : output-part ( p -- )
 1289:     to prim
 1290:     ." /* " prim prim-name 2@ type ."  ( " prim prim-stack-string 2@ type ." ) */" cr
 1291:     ." NAME(" quote prim prim-name 2@ type quote ." )" cr \ debugging
 1292:     ." {" cr
 1293:     print-declarations
 1294:     part-fetches
 1295:     print-debug-args
 1296:     combined ['] part-stack-pointer-updates prim-context
 1297:     1 part-num +!
 1298:     prim add-depths \ !! right place?
 1299:     prim prim-c-code 2@ ['] output-combined-tail type-c-code
 1300:     part-output-c-tail
 1301:     ." }" cr ;
 1302: 
 1303: : output-parts ( -- )
 1304:     prim >r in-part on
 1305:     current-depth max-stacks cells erase
 1306:     0 part-num !
 1307:     ['] output-part map-combined
 1308:     in-part off
 1309:     r> to prim ;
 1310: 
 1311: : output-c-combined ( -- )
 1312:     print-entry cr
 1313:     \ debugging messages just in parts
 1314:     ." {" cr
 1315:     ." DEF_CA" cr
 1316:     print-declarations-combined
 1317:     ." NEXT_P0;" cr
 1318:     flush-tos
 1319:     \ fetches \ now in parts
 1320:     \ print-debug-args
 1321:     \ stack-pointer-updates now in parts
 1322:     output-parts
 1323:     output-c-tail2-no-stores
 1324:     ." }" cr
 1325:     cr ;
 1326: 
 1327: : output-forth-combined ( -- )
 1328: ;
 1329: 
 1330: 
 1331: \ peephole optimization rules
 1332: 
 1333: \ data for a simple peephole optimizer that always tries to combine
 1334: \ the currently compiled instruction with the last one.
 1335: 
 1336: \ in order for this to work as intended, shorter combinations for each
 1337: \ length must be present, and the longer combinations must follow
 1338: \ shorter ones (this restriction may go away in the future).
 1339:   
 1340: : output-peephole ( -- )
 1341:     combined-prims num-combined @ 1- cells combinations search-wordlist
 1342:     s" the prefix for this superinstruction must be defined earlier" ?print-error
 1343:     ." {"
 1344:     execute prim-num @ 5 .r ." ,"
 1345:     combined-prims num-combined @ 1- th @ prim-num @ 5 .r ." ,"
 1346:     combined prim-num @ 5 .r ." }, /* "
 1347:     combined prim-c-name 2@ type ."  */"
 1348:     cr ;
 1349: 
 1350: 
 1351: \ cost and superinstruction data for a sophisticated combiner (e.g.,
 1352: \ shortest path)
 1353: 
 1354: \ This is intended as initializer for a structure like this
 1355: 
 1356: \  struct cost {
 1357: \    int loads;       /* number of stack loads */
 1358: \    int stores;      /* number of stack stores */
 1359: \    int updates;     /* number of stack pointer updates */
 1360: \    int offset;      /* offset into super2 table */
 1361: \    int length;      /* number of components */
 1362: \  };
 1363: 
 1364: \ How do you know which primitive or combined instruction this
 1365: \ structure refers to?  By the order of cost structures, as in most
 1366: \ other cases.
 1367: 
 1368: : super2-length ( -- n )
 1369:     combined if
 1370: 	num-combined @
 1371:     else
 1372: 	1
 1373:     endif ;
 1374: 
 1375: : compute-costs { p -- nloads nstores nupdates }
 1376:     \ compute the number of loads, stores, and stack pointer updates
 1377:     \ of a primitive or combined instruction; does not take TOS
 1378:     \ caching into account
 1379:     0 max-stacks 0 +do
 1380: 	p prim-stacks-in i th @ +
 1381:     loop
 1382:     super2-length 1- - \ don't count instruction fetches of subsumed insts
 1383:     0 max-stacks 0 +do
 1384: 	p prim-stacks-out i th @ +
 1385:     loop
 1386:     0 max-stacks 1 +do \ don't count ip updates, therefore "1 +do"
 1387: 	p prim-stacks-in i th @ p prim-stacks-out i th @ <> -
 1388:     loop ;
 1389: 
 1390: : output-num-part ( p -- )
 1391:     ." N_" prim-c-name 2@ type ." ," ;
 1392:     \ prim-num @ 4 .r ." ," ;
 1393: 
 1394: : output-name-comment ( -- )
 1395:     ."  /* " prim prim-name 2@ type ."  */" ;
 1396: 
 1397: variable offset-super2  0 offset-super2 ! \ offset into the super2 table
 1398: 
 1399: : output-costs-prefix ( -- )
 1400:     ." {" prim compute-costs
 1401:     rot 2 .r ." ," swap 2 .r ." ," 2 .r ." , "
 1402:     prim prim-branch? negate . ." ," ;
 1403: 
 1404: : output-costs-gforth-simple ( -- )
 1405:     output-costs-prefix
 1406:     prim output-num-part
 1407:     1 2 .r ." },"
 1408:     output-name-comment
 1409:     cr ;
 1410: 
 1411: : output-costs-gforth-combined ( -- )
 1412:     output-costs-prefix
 1413:     ." N_START_SUPER+" offset-super2 @ 5 .r ." ,"
 1414:     super2-length dup 2 .r ." }," offset-super2 +!
 1415:     output-name-comment
 1416:     cr ;
 1417: 
 1418: : output-costs ( -- )
 1419:     \ description of superinstructions and simple instructions
 1420:     ." {" prim compute-costs
 1421:     rot 2 .r ." ," swap 2 .r ." ," 2 .r ." ,"
 1422:     offset-super2 @ 5 .r ." ,"
 1423:     super2-length dup 2 .r ." }," offset-super2 +!
 1424:     output-name-comment
 1425:     cr ;
 1426: 
 1427: : output-super2 ( -- )
 1428:     \ table of superinstructions without requirement for existing prefixes
 1429:     combined if
 1430: 	['] output-num-part map-combined 
 1431:     else
 1432: 	prim output-num-part
 1433:     endif
 1434:     output-name-comment
 1435:     cr ;   
 1436: 
 1437: \ the parser
 1438: 
 1439: eof-char max-member \ the whole character set + EOF
 1440: 
 1441: : getinput ( -- n )
 1442:  rawinput @ endrawinput @ =
 1443:  if
 1444:    eof-char
 1445:  else
 1446:    cookedinput @ c@
 1447:  endif ;
 1448: 
 1449: :noname ( n -- )
 1450:  dup bl > if
 1451:   emit space
 1452:  else
 1453:   .
 1454:  endif ;
 1455: print-token !
 1456: 
 1457: : testchar? ( set -- f )
 1458:  getinput member? ;
 1459: ' testchar? test-vector !
 1460: 
 1461: : checksynclines ( -- )
 1462:     \ when input points to a newline, check if the next line is a
 1463:     \ sync line.  If it is, perform the appropriate actions.
 1464:     rawinput @ begin >r
 1465: 	s" #line " r@ over compare if
 1466: 	    rdrop 1 line +! EXIT
 1467: 	endif
 1468: 	0. r> 6 chars + 20 >number drop >r drop line ! r> ( c-addr )
 1469: 	dup c@ bl = if
 1470: 	    char+ dup c@ [char] " <> 0= s" sync line syntax" ?print-error
 1471: 	    char+ dup 100 [char] " scan drop swap 2dup - save-mem filename 2!
 1472: 	    char+
 1473: 	endif
 1474: 	dup c@ nl-char <> 0= s" sync line syntax" ?print-error
 1475: 	skipsynclines @ if
 1476: 	    char+ dup rawinput !
 1477: 	    rawinput @ c@ cookedinput @ c!
 1478: 	endif
 1479:     again ;
 1480: 
 1481: : ?nextchar ( f -- )
 1482:     s" syntax error, wrong char" ?print-error
 1483:     rawinput @ endrawinput @ <> if
 1484: 	rawinput @ c@
 1485: 	1 chars rawinput +!
 1486: 	1 chars cookedinput +!
 1487: 	nl-char = if
 1488: 	    checksynclines
 1489: 	    rawinput @ line-start !
 1490: 	endif
 1491: 	rawinput @ c@
 1492: 	cookedinput @ c!
 1493:     endif ;
 1494: 
 1495: : charclass ( set "name" -- )
 1496:  ['] ?nextchar terminal ;
 1497: 
 1498: : .. ( c1 c2 -- set )
 1499:  ( creates a set that includes the characters c, c1<=c<=c2 )
 1500:  empty copy-set
 1501:  swap 1+ rot do
 1502:   i over add-member
 1503:  loop ;
 1504: 
 1505: : ` ( -- terminal ) ( use: ` c )
 1506:  ( creates anonymous terminal for the character c )
 1507:  char singleton ['] ?nextchar make-terminal ;
 1508: 
 1509: char a char z ..  char A char Z ..  union char _ singleton union  charclass letter
 1510: char 0 char 9 ..					charclass digit
 1511: bl singleton tab-char over add-member			charclass white
 1512: nl-char singleton eof-char over add-member complement	charclass nonl
 1513: nl-char singleton eof-char over add-member
 1514:     char : over add-member complement                   charclass nocolonnl
 1515: nl-char singleton eof-char over add-member
 1516:     char } over add-member complement                   charclass nobracenl
 1517: bl 1+ maxchar .. char \ singleton complement intersection
 1518:                                                         charclass nowhitebq
 1519: bl 1+ maxchar ..                                        charclass nowhite
 1520: char " singleton eof-char over add-member complement	charclass noquote
 1521: nl-char singleton					charclass nl
 1522: eof-char singleton					charclass eof
 1523: nl-char singleton eof-char over add-member		charclass nleof
 1524: 
 1525: (( letter (( letter || digit )) **
 1526: )) <- c-ident ( -- )
 1527: 
 1528: (( ` # ?? (( letter || digit || ` : )) ++
 1529: )) <- stack-ident ( -- )
 1530: 
 1531: (( nowhitebq nowhite ** ))
 1532: <- forth-ident ( -- )
 1533: 
 1534: Variable forth-flag
 1535: Variable c-flag
 1536: 
 1537: (( (( ` e || ` E )) {{ start }} nonl ** 
 1538:    {{ end evaluate }}
 1539: )) <- eval-comment ( ... -- ... )
 1540: 
 1541: (( (( ` f || ` F )) {{ start }} nonl ** 
 1542:    {{ end forth-flag @ IF type cr ELSE 2drop THEN }}
 1543: )) <- forth-comment ( -- )
 1544: 
 1545: (( (( ` c || ` C )) {{ start }} nonl ** 
 1546:    {{ end c-flag @ IF type cr ELSE 2drop THEN }}
 1547: )) <- c-comment ( -- )
 1548: 
 1549: (( ` - nonl ** {{ 
 1550: 	forth-flag @ IF forth-fdiff ." [ELSE]" cr THEN
 1551: 	c-flag @ IF
 1552: 	    function-diff
 1553: 	    ." #else /* " function-number @ 0 .r ."  */" cr THEN }}
 1554: )) <- else-comment
 1555: 
 1556: (( ` + {{ start }} nonl ** {{ end
 1557: 	dup
 1558: 	IF	c-flag @
 1559: 	    IF
 1560: 		function-diff
 1561: 		." #ifdef HAS_" bounds ?DO  I c@ toupper emit  LOOP cr
 1562: 		THEN
 1563: 		forth-flag @
 1564: 		IF  forth-fdiff  ." has? " type ."  [IF]"  cr THEN
 1565: 	ELSE	2drop
 1566: 	    c-flag @      IF
 1567: 		function-diff  ." #endif" cr THEN
 1568: 	    forth-flag @  IF  forth-fdiff  ." [THEN]"  cr THEN
 1569: 	THEN }}
 1570: )) <- if-comment
 1571: 
 1572: (( (( ` g || ` G )) {{ start }} nonl **
 1573:    {{ end
 1574:       forth-flag @ IF  forth-fdiff  ." group " type cr  THEN
 1575:       c-flag @     IF  function-diff
 1576: 	  ." GROUP(" type ." , " function-number @ 0 .r ." )" cr  THEN }}
 1577: )) <- group-comment
 1578: 
 1579: (( (( eval-comment || forth-comment || c-comment || else-comment || if-comment || group-comment )) ?? nonl ** )) <- comment-body
 1580: 
 1581: (( ` \ comment-body nleof )) <- comment ( -- )
 1582: 
 1583: (( {{ start }} stack-ident {{ end 2 pick init-item item% %size + }} white ** )) **
 1584: <- stack-items
 1585: 
 1586: (( {{ prim prim-effect-in }}  stack-items {{ prim prim-effect-in-end ! }}
 1587:    ` - ` - white **
 1588:    {{ prim prim-effect-out }} stack-items {{ prim prim-effect-out-end ! }}
 1589: )) <- stack-effect ( -- )
 1590: 
 1591: (( {{ prim create-prim }}
 1592:    ` ( white ** {{ start }} stack-effect {{ end prim prim-stack-string 2! }} ` ) white **
 1593:    (( {{ start }} forth-ident {{ end prim prim-wordset 2! }} white **
 1594:       (( {{ start }}  c-ident {{ end prim prim-c-name 2! }} )) ??
 1595:    )) ??  nleof
 1596:    (( ` " ` "  {{ start }} (( noquote ++ ` " )) ++ {{ end 1- prim prim-doc 2! }} ` " white ** nleof )) ??
 1597:    {{ skipsynclines off line @ c-line ! filename 2@ c-filename 2! start }}
 1598:    (( (( ` { nonl ** nleof (( (( nobracenl {{ line @ drop }} nonl ** )) ?? nleof )) ** ` } white ** nleof white ** ))
 1599:    || (( nocolonnl nonl **  nleof white ** )) ** ))
 1600:    {{ end prim prim-c-code 2! skipsynclines on }}
 1601:    (( ` :  white ** nleof
 1602:       {{ start }} (( nonl ++  nleof white ** )) ++ {{ end prim prim-forth-code 2! }}
 1603:    )) ?? {{ process-simple }}
 1604:    nleof
 1605: )) <- simple-primitive ( -- )
 1606: 
 1607: (( {{ init-combined }}
 1608:    ` = white ** (( {{ start }} forth-ident {{ end add-prim }} white ** )) ++
 1609:    nleof {{ process-combined }}
 1610: )) <- combined-primitive
 1611: 
 1612: (( {{ make-prim to prim 0 to combined
 1613:       line @ name-line ! filename 2@ name-filename 2!
 1614:       function-number @ prim prim-num !
 1615:       start }} [ifdef] vmgen c-ident [else] forth-ident [then] {{ end
 1616:       2dup prim prim-name 2! prim prim-c-name 2! }}  white **
 1617:    (( ` / white ** {{ start }} c-ident {{ end prim prim-c-name 2! }} white ** )) ??
 1618:    (( simple-primitive || combined-primitive ))
 1619:    {{ 1 function-number +! }}
 1620: )) <- primitive ( -- )
 1621: 
 1622: (( (( comment || primitive || nl white ** )) ** eof ))
 1623: parser primitives2something
 1624: warnings @ [IF]
 1625: .( parser generated ok ) cr
 1626: [THEN]
 1627: 
 1628: 
 1629: \ run with gforth-0.5.0 (slurp-file is missing)
 1630: [IFUNDEF] slurp-file
 1631: : slurp-file ( c-addr1 u1 -- c-addr2 u2 )
 1632:     \ c-addr1 u1 is the filename, c-addr2 u2 is the file's contents
 1633:     r/o bin open-file throw >r
 1634:     r@ file-size throw abort" file too large"
 1635:     dup allocate throw swap
 1636:     2dup r@ read-file throw over <> abort" could not read whole file"
 1637:     r> close-file throw ;
 1638: [THEN]
 1639: 
 1640: : primfilter ( addr u -- )
 1641:     \ process the string at addr u
 1642:     over dup rawinput ! dup line-start ! cookedinput !
 1643:     + endrawinput !
 1644:     checksynclines
 1645:     primitives2something ;    
 1646: 
 1647: : unixify ( c-addr u1 -- c-addr u2 )
 1648:     \ delete crs from the string
 1649:     bounds tuck tuck ?do ( c-addr1 )
 1650: 	i c@ dup #cr <> if
 1651: 	    over c! char+
 1652: 	else
 1653: 	    drop
 1654: 	endif
 1655:     loop
 1656:     over - ;
 1657: 
 1658: : process-file ( addr u xt-simple x-combined -- )
 1659:     output-combined ! output !
 1660:     save-mem 2dup filename 2!
 1661:     slurp-file unixify
 1662:     warnings @ if
 1663: 	." ------------ CUT HERE -------------" cr  endif
 1664:     primfilter ;
 1665: 
 1666: \  : process      ( xt -- )
 1667: \      bl word count rot
 1668: \      process-file ;

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