File:  [gforth] / gforth / doc / vmgen.texi
Revision 1.31: download - view: text, annotated - select for diffs
Mon Dec 31 19:02:25 2007 UTC (15 years, 1 month ago) by anton
Branches: MAIN
CVS tags: HEAD
updated copyright year after changing license notice

    1: \input texinfo    @c -*-texinfo-*-
    2: @comment %**start of header
    3: @setfilename
    4: @include version.texi
    5: @settitle Vmgen (Gforth @value{VERSION})
    6: @c @syncodeindex pg cp
    7: @comment %**end of header
    8: @copying
    9: This manual is for Vmgen
   10: (version @value{VERSION}, @value{UPDATED}),
   11: the virtual machine interpreter generator
   13: Copyright @copyright{} 2002,2003,2005,2007 Free Software Foundation, Inc.
   15: @quotation
   16: Permission is granted to copy, distribute and/or modify this document
   17: under the terms of the GNU Free Documentation License, Version 1.2 or
   18: any later version published by the Free Software Foundation; with no
   19: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   20: and with the Back-Cover Texts as in (a) below.  A copy of the
   21: license is included in the section entitled ``GNU Free Documentation
   22: License.''
   24: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   25: this GNU Manual, like GNU software.  Copies published by the Free
   26: Software Foundation raise funds for GNU development.''
   27: @end quotation
   28: @end copying
   30: @dircategory Software development
   31: @direntry
   32: * Vmgen: (vmgen).               Virtual machine interpreter generator
   33: @end direntry
   35: @titlepage
   36: @title Vmgen
   37: @subtitle for Gforth version @value{VERSION}, @value{UPDATED}
   38: @author M. Anton Ertl (@email{})
   39: @page
   40: @vskip 0pt plus 1filll
   41: @insertcopying
   42: @end titlepage
   44: @contents
   46: @ifnottex
   47: @node Top, Introduction, (dir), (dir)
   48: @top Vmgen
   50: @insertcopying
   51: @end ifnottex
   53: @menu
   54: * Introduction::                What can Vmgen do for you?
   55: * Why interpreters?::           Advantages and disadvantages
   56: * Concepts::                    VM interpreter background
   57: * Invoking Vmgen::              
   58: * Example::                     
   59: * Input File Format::           
   60: * Error messages::              reported by Vmgen
   61: * Using the generated code::    
   62: * Hints::                       VM archictecture, efficiency
   63: * The future::                  
   64: * Changes::                     from earlier versions
   65: * Contact::                     Bug reporting etc.
   66: * Copying This Manual::         Manual License
   67: * Index::                       
   69: @detailmenu
   70:  --- The Detailed Node Listing ---
   72: Concepts
   74: * Front end and VM interpreter::  Modularizing an interpretive system
   75: * Data handling::               Stacks, registers, immediate arguments
   76: * Dispatch::                    From one VM instruction to the next
   78: Example
   80: * Example overview::            
   81: * Using profiling to create superinstructions::  
   83: Input File Format
   85: * Input File Grammar::          
   86: * Simple instructions::         
   87: * Superinstructions::           
   88: * Store Optimization::          
   89: * Register Machines::           How to define register VM instructions
   91: Input File Grammar
   93: * Eval escapes::                what follows \E
   95: Simple instructions
   97: * Explicit stack access::       If the C code accesses a stack pointer
   98: * C Code Macros::               Macros recognized by Vmgen
   99: * C Code restrictions::         Vmgen makes assumptions about C code
  100: * Stack growth direction::      is configurable per stack
  102: Using the generated code
  104: * VM engine::                   Executing VM code
  105: * VM instruction table::        
  106: * VM code generation::          Creating VM code (in the front-end)
  107: * Peephole optimization::       Creating VM superinstructions
  108: * VM disassembler::             for debugging the front end
  109: * VM profiler::                 for finding worthwhile superinstructions
  111: Hints
  113: * Floating point::              and stacks
  115: Copying This Manual
  117: * GNU Free Documentation License::  License for copying this manual.
  119: @end detailmenu
  120: @end menu
  122: @c @ifnottex
  123: @c This file documents Vmgen (Gforth @value{VERSION}).
  125: @c ************************************************************
  126: @node Introduction, Why interpreters?, Top, Top
  127: @chapter Introduction
  129: Vmgen is a tool for writing efficient interpreters.  It takes a simple
  130: virtual machine description and generates efficient C code for dealing
  131: with the virtual machine code in various ways (in particular, executing
  132: it).  The run-time efficiency of the resulting interpreters is usually
  133: within a factor of 10 of machine code produced by an optimizing
  134: compiler.
  136: The interpreter design strategy supported by Vmgen is to divide the
  137: interpreter into two parts:
  139: @itemize @bullet
  141: @item The @emph{front end} takes the source code of the language to be
  142: implemented, and translates it into virtual machine code.  This is
  143: similar to an ordinary compiler front end; typically an interpreter
  144: front-end performs no optimization, so it is relatively simple to
  145: implement and runs fast.
  147: @item The @emph{virtual machine interpreter} executes the virtual
  148: machine code.
  150: @end itemize
  152: Such a division is usually used in interpreters, for modularity as well
  153: as for efficiency.  The virtual machine code is typically passed between
  154: front end and virtual machine interpreter in memory, like in a
  155: load-and-go compiler; this avoids the complexity and time cost of
  156: writing the code to a file and reading it again.
  158: A @emph{virtual machine} (VM) represents the program as a sequence of
  159: @emph{VM instructions}, following each other in memory, similar to real
  160: machine code.  Control flow occurs through VM branch instructions, like
  161: in a real machine.
  163: @cindex functionality features overview
  164: In this setup, Vmgen can generate most of the code dealing with virtual
  165: machine instructions from a simple description of the virtual machine
  166: instructions (@pxref{Input File Format}), in particular:
  168: @table @strong
  170: @item VM instruction execution
  172: @item VM code generation
  173: Useful in the front end.
  175: @item VM code decompiler
  176: Useful for debugging the front end.
  178: @item VM code tracing
  179: Useful for debugging the front end and the VM interpreter.  You will
  180: typically provide other means for debugging the user's programs at the
  181: source level.
  183: @item VM code profiling
  184: Useful for optimizing the VM interpreter with superinstructions
  185: (@pxref{VM profiler}).
  187: @end table
  189: To create parts of the interpretive system that do not deal with VM
  190: instructions, you have to use other tools (e.g., @command{bison}) and/or
  191: hand-code them.
  193: @cindex efficiency features overview
  194: @noindent
  195: Vmgen supports efficient interpreters though various optimizations, in
  196: particular
  198: @itemize @bullet
  200: @item Threaded code
  202: @item Caching the top-of-stack in a register
  204: @item Combining VM instructions into superinstructions
  206: @item
  207: Replicating VM (super)instructions for better BTB prediction accuracy
  208: (not yet in vmgen-ex, but already in Gforth).
  210: @end itemize
  212: @cindex speed for JVM
  213: As a result, Vmgen-based interpreters are only about an order of
  214: magnitude slower than native code from an optimizing C compiler on small
  215: benchmarks; on large benchmarks, which spend more time in the run-time
  216: system, the slowdown is often less (e.g., the slowdown of a
  217: Vmgen-generated JVM interpreter over the best JVM JIT compiler we
  218: measured is only a factor of 2-3 for large benchmarks; some other JITs
  219: and all other interpreters we looked at were slower than our
  220: interpreter).
  222: VMs are usually designed as stack machines (passing data between VM
  223: instructions on a stack), and Vmgen supports such designs especially
  224: well; however, you can also use Vmgen for implementing a register VM
  225: (@pxref{Register Machines}) and still benefit from most of the advantages
  226: offered by Vmgen.
  228: There are many potential uses of the instruction descriptions that are
  229: not implemented at the moment, but we are open for feature requests, and
  230: we will consider new features if someone asks for them; so the feature
  231: list above is not exhaustive.
  233: @c *********************************************************************
  234: @node Why interpreters?, Concepts, Introduction, Top
  235: @chapter Why interpreters?
  236: @cindex interpreters, advantages
  237: @cindex advantages of interpreters
  238: @cindex advantages of vmgen
  240: Interpreters are a popular language implementation technique because
  241: they combine all three of the following advantages:
  243: @itemize @bullet
  245: @item Ease of implementation
  247: @item Portability
  249: @item Fast edit-compile-run cycle
  251: @end itemize
  253: Vmgen makes it even easier to implement interpreters.
  255: @cindex speed of interpreters
  256: The main disadvantage of interpreters is their run-time speed.  However,
  257: there are huge differences between different interpreters in this area:
  258: the slowdown over optimized C code on programs consisting of simple
  259: operations is typically a factor of 10 for the more efficient
  260: interpreters, and a factor of 1000 for the less efficient ones (the
  261: slowdown for programs executing complex operations is less, because the
  262: time spent in libraries for executing complex operations is the same in
  263: all implementation strategies).
  265: Vmgen supports techniques for building efficient interpreters.
  267: @c ********************************************************************
  268: @node Concepts, Invoking Vmgen, Why interpreters?, Top
  269: @chapter Concepts
  271: @menu
  272: * Front end and VM interpreter::  Modularizing an interpretive system
  273: * Data handling::               Stacks, registers, immediate arguments
  274: * Dispatch::                    From one VM instruction to the next
  275: @end menu
  277: @c --------------------------------------------------------------------
  278: @node Front end and VM interpreter, Data handling, Concepts, Concepts
  279: @section Front end and VM interpreter
  280: @cindex modularization of interpreters
  282: @cindex front-end
  283: Interpretive systems are typically divided into a @emph{front end} that
  284: parses the input language and produces an intermediate representation
  285: for the program, and an interpreter that executes the intermediate
  286: representation of the program.
  288: @cindex virtual machine
  289: @cindex VM
  290: @cindex VM instruction
  291: @cindex instruction, VM
  292: @cindex VM branch instruction
  293: @cindex branch instruction, VM
  294: @cindex VM register
  295: @cindex register, VM
  296: @cindex opcode, VM instruction
  297: @cindex immediate argument, VM instruction
  298: For efficient interpreters the intermediate representation of choice is
  299: virtual machine code (rather than, e.g., an abstract syntax tree).
  300: @emph{Virtual machine} (VM) code consists of VM instructions arranged
  301: sequentially in memory; they are executed in sequence by the VM
  302: interpreter, but VM branch instructions can change the control flow and
  303: are used for implementing control structures.  The conceptual similarity
  304: to real machine code results in the name @emph{virtual machine}.
  305: Various terms similar to terms for real machines are used; e.g., there
  306: are @emph{VM registers} (like the instruction pointer and stack
  307: pointer(s)), and the VM instruction consists of an @emph{opcode} and
  308: @emph{immediate arguments}.
  310: In this framework, Vmgen supports building the VM interpreter and any
  311: other component dealing with VM instructions.  It does not have any
  312: support for the front end, apart from VM code generation support.  The
  313: front end can be implemented with classical compiler front-end
  314: techniques, supported by tools like @command{flex} and @command{bison}.
  316: The intermediate representation is usually just internal to the
  317: interpreter, but some systems also support saving it to a file, either
  318: as an image file, or in a full-blown linkable file format (e.g., JVM).
  319: Vmgen currently has no special support for such features, but the
  320: information in the instruction descriptions can be helpful, and we are
  321: open to feature requests and suggestions.
  323: @c --------------------------------------------------------------------
  324: @node Data handling, Dispatch, Front end and VM interpreter, Concepts
  325: @section Data handling
  327: @cindex stack machine
  328: @cindex register machine
  329: Most VMs use one or more stacks for passing temporary data between VM
  330: instructions.  Another option is to use a register machine architecture
  331: for the virtual machine; we believe that using a stack architecture is
  332: usually both simpler and faster.
  334: however, this option is slower or
  335: significantly more complex to implement than a stack machine architecture.
  337: Vmgen has special support and optimizations for stack VMs, making their
  338: implementation easy and efficient.
  340: You can also implement a register VM with Vmgen (@pxref{Register
  341: Machines}), and you will still profit from most Vmgen features.
  343: @cindex stack item size
  344: @cindex size, stack items
  345: Stack items all have the same size, so they typically will be as wide as
  346: an integer, pointer, or floating-point value.  Vmgen supports treating
  347: two consecutive stack items as a single value, but anything larger is
  348: best kept in some other memory area (e.g., the heap), with pointers to
  349: the data on the stack.
  351: @cindex instruction stream
  352: @cindex immediate arguments
  353: Another source of data is immediate arguments VM instructions (in the VM
  354: instruction stream).  The VM instruction stream is handled similar to a
  355: stack in Vmgen.
  357: @cindex garbage collection
  358: @cindex reference counting
  359: Vmgen has no built-in support for, nor restrictions against
  360: @emph{garbage collection}.  If you need garbage collection, you need to
  361: provide it in your run-time libraries.  Using @emph{reference counting}
  362: is probably harder, but might be possible (contact us if you are
  363: interested).
  364: @c reference counting might be possible by including counting code in 
  365: @c the conversion macros.
  367: @c --------------------------------------------------------------------
  368: @node Dispatch,  , Data handling, Concepts
  369: @section Dispatch
  370: @cindex Dispatch of VM instructions
  371: @cindex main interpreter loop
  373: Understanding this section is probably not necessary for using Vmgen,
  374: but it may help.  You may want to skip it now, and read it if you find statements about dispatch methods confusing.
  376: After executing one VM instruction, the VM interpreter has to dispatch
  377: the next VM instruction (Vmgen calls the dispatch routine @samp{NEXT}).
  378: Vmgen supports two methods of dispatch:
  380: @table @strong
  382: @item switch dispatch
  383: @cindex switch dispatch
  384: In this method the VM interpreter contains a giant @code{switch}
  385: statement, with one @code{case} for each VM instruction.  The VM
  386: instruction opcodes are represented by integers (e.g., produced by an
  387: @code{enum}) in the VM code, and dispatch occurs by loading the next
  388: opcode, @code{switch}ing on it, and continuing at the appropriate
  389: @code{case}; after executing the VM instruction, the VM interpreter
  390: jumps back to the dispatch code.
  392: @item threaded code
  393: @cindex threaded code
  394: This method represents a VM instruction opcode by the address of the
  395: start of the machine code fragment for executing the VM instruction.
  396: Dispatch consists of loading this address, jumping to it, and
  397: incrementing the VM instruction pointer.  Typically the threaded-code
  398: dispatch code is appended directly to the code for executing the VM
  399: instruction.  Threaded code cannot be implemented in ANSI C, but it can
  400: be implemented using GNU C's labels-as-values extension (@pxref{Labels
  401: as Values, , Labels as Values,, GNU C Manual}).
  403: @c call threading
  404: @end table
  406: Threaded code can be twice as fast as switch dispatch, depending on the
  407: interpreter, the benchmark, and the machine.
  409: @c *************************************************************
  410: @node Invoking Vmgen, Example, Concepts, Top
  411: @chapter Invoking Vmgen
  412: @cindex Invoking Vmgen
  414: The usual way to invoke Vmgen is as follows:
  416: @example
  417: vmgen @var{inputfile}
  418: @end example
  420: Here @var{inputfile} is the VM instruction description file, which
  421: usually ends in @file{.vmg}.  The output filenames are made by taking
  422: the basename of @file{inputfile} (i.e., the output files will be created
  423: in the current working directory) and replacing @file{.vmg} with
  424: @file{-vm.i}, @file{-disasm.i}, @file{-gen.i}, @file{-labels.i},
  425: @file{-profile.i}, and @file{-peephole.i}.  E.g., @command{vmgen
  426: hack/foo.vmg} will create @file{foo-vm.i}, @file{foo-disasm.i},
  427: @file{foo-gen.i}, @file{foo-labels.i}, @file{foo-profile.i} and
  428: @file{foo-peephole.i}.
  430: The command-line options supported by Vmgen are
  432: @table @option
  434: @cindex -h, command-line option
  435: @cindex --help, command-line option
  436: @item --help
  437: @itemx -h
  438: Print a message about the command-line options
  440: @cindex -v, command-line option
  441: @cindex --version, command-line option
  442: @item --version
  443: @itemx -v
  444: Print version and exit
  445: @end table
  449: @c ****************************************************************
  450: @node Example, Input File Format, Invoking Vmgen, Top
  451: @chapter Example
  452: @cindex example of a Vmgen-based interpreter
  454: @menu
  455: * Example overview::            
  456: * Using profiling to create superinstructions::  
  457: @end menu
  459: @c --------------------------------------------------------------------
  460: @node Example overview, Using profiling to create superinstructions, Example, Example
  461: @section Example overview
  462: @cindex example overview
  463: @cindex @file{vmgen-ex}
  464: @cindex @file{vmgen-ex2}
  466: There are two versions of the same example for using Vmgen:
  467: @file{vmgen-ex} and @file{vmgen-ex2} (you can also see Gforth as
  468: example, but it uses additional (undocumented) features, and also
  469: differs in some other respects).  The example implements @emph{mini}, a
  470: tiny Modula-2-like language with a small JavaVM-like virtual machine.
  472: The difference between the examples is that @file{vmgen-ex} uses many
  473: casts, and @file{vmgen-ex2} tries to avoids most casts and uses unions
  474: instead.  In the rest of this manual we usually mention just files in
  475: @file{vmgen-ex}; if you want to use unions, use the equivalent file in
  476: @file{vmgen-ex2}.
  477: @cindex unions example
  478: @cindex casts example
  480: The files provided with each example are:
  481: @cindex example files
  483: @example
  484: Makefile
  485: README
  486: disasm.c           wrapper file
  487: engine.c           wrapper file
  488: peephole.c         wrapper file
  489: profile.c          wrapper file
  490: mini-inst.vmg      simple VM instructions
  491: mini-super.vmg     superinstructions (empty at first)
  492: mini.h             common declarations
  493: mini.l             scanner
  494: mini.y             front end (parser, VM code generator)
  495: support.c          main() and other support functions
  496:           example mini program
  497:        example mini program
  498:          example mini program (tests everything)
  499: test.out  output
  500: stat.awk           script for aggregating profile information
  501: peephole-blacklist list of instructions not allowed in superinstructions
  502: seq2rule.awk       script for creating superinstructions
  503: @end example
  505: For your own interpreter, you would typically copy the following files
  506: and change little, if anything:
  507: @cindex wrapper files
  509: @example
  510: disasm.c           wrapper file
  511: engine.c           wrapper file
  512: peephole.c         wrapper file
  513: profile.c          wrapper file
  514: stat.awk           script for aggregating profile information
  515: seq2rule.awk       script for creating superinstructions
  516: @end example
  518: @noindent
  519: You would typically change much in or replace the following files:
  521: @example
  522: Makefile
  523: mini-inst.vmg      simple VM instructions
  524: mini.h             common declarations
  525: mini.l             scanner
  526: mini.y             front end (parser, VM code generator)
  527: support.c          main() and other support functions
  528: peephole-blacklist list of instructions not allowed in superinstructions
  529: @end example
  531: You can build the example by @code{cd}ing into the example's directory,
  532: and then typing @code{make}; you can check that it works with @code{make
  533: check}.  You can run run mini programs like this:
  535: @example
  536: ./mini
  537: @end example
  539: To learn about the options, type @code{./mini -h}.
  541: @c --------------------------------------------------------------------
  542: @node Using profiling to create superinstructions,  , Example overview, Example
  543: @section Using profiling to create superinstructions
  544: @cindex profiling example
  545: @cindex superinstructions example
  547: I have not added rules for this in the @file{Makefile} (there are many
  548: options for selecting superinstructions, and I did not want to hardcode
  549: one into the @file{Makefile}), but there are some supporting scripts, and
  550: here's an example:
  552: Suppose you want to use @file{} and @file{} as training
  553: programs, you get the profiles like this:
  555: @example
  556: make #takes a few seconds
  557: @end example
  559: You can aggregate these profiles with @file{stat.awk}:
  561: @example
  562: awk -f stat.awk
  563: @end example
  565: The result contains lines like:
  567: @example
  568:       2      16        36910041 loadlocal lit
  569: @end example
  571: This means that the sequence @code{loadlocal lit} statically occurs a
  572: total of 16 times in 2 profiles, with a dynamic execution count of
  573: 36910041.
  575: The numbers can be used in various ways to select superinstructions.
  576: E.g., if you just want to select all sequences with a dynamic
  577: execution count exceeding 10000, you would use the following pipeline:
  579: @example
  580: awk -f stat.awk|
  581: awk '$3>=10000'|                #select sequences
  582: fgrep -v -f peephole-blacklist| #eliminate wrong instructions
  583: awk -f seq2rule.awk|  #transform sequences into superinstruction rules
  584: sort -k 3 >mini-super.vmg       #sort sequences
  585: @end example
  587: The file @file{peephole-blacklist} contains all instructions that
  588: directly access a stack or stack pointer (for mini: @code{call},
  589: @code{return}); the sort step is necessary to ensure that prefixes
  590: precede larger superinstructions.
  592: Now you can create a version of mini with superinstructions by just
  593: saying @samp{make}
  596: @c ***************************************************************
  597: @node Input File Format, Error messages, Example, Top
  598: @chapter Input File Format
  599: @cindex input file format
  600: @cindex format, input file
  602: Vmgen takes as input a file containing specifications of virtual machine
  603: instructions.  This file usually has a name ending in @file{.vmg}.
  605: Most examples are taken from the example in @file{vmgen-ex}.
  607: @menu
  608: * Input File Grammar::          
  609: * Simple instructions::         
  610: * Superinstructions::           
  611: * Store Optimization::          
  612: * Register Machines::           How to define register VM instructions
  613: @end menu
  615: @c --------------------------------------------------------------------
  616: @node Input File Grammar, Simple instructions, Input File Format, Input File Format
  617: @section Input File Grammar
  618: @cindex grammar, input file
  619: @cindex input file grammar
  621: The grammar is in EBNF format, with @code{@var{a}|@var{b}} meaning
  622: ``@var{a} or @var{b}'', @code{@{@var{c}@}} meaning 0 or more repetitions
  623: of @var{c} and @code{[@var{d}]} meaning 0 or 1 repetitions of @var{d}.
  625: @cindex free-format, not
  626: @cindex newlines, significance in syntax
  627: Vmgen input is not free-format, so you have to take care where you put
  628: newlines (and, in a few cases, white space).
  630: @example
  631: description: @{instruction|comment|eval-escape|c-escape@}
  633: instruction: simple-inst|superinst
  635: simple-inst: ident '(' stack-effect ')' newline c-code newline newline
  637: stack-effect: @{ident@} '--' @{ident@}
  639: super-inst: ident '=' ident @{ident@}  
  641: comment:      '\ '  text newline
  643: eval-escape:  '\E ' text newline
  645: c-escape:     '\C ' text newline
  646: @end example
  647: @c \+ \- \g \f \c
  649: Note that the @code{\}s in this grammar are meant literally, not as
  650: C-style encodings for non-printable characters.
  652: There are two ways to delimit the C code in @code{simple-inst}:
  654: @itemize @bullet
  656: @item
  657: If you start it with a @samp{@{} at the start of a line (i.e., not even
  658: white space before it), you have to end it with a @samp{@}} at the start
  659: of a line (followed by a newline).  In this case you may have empty
  660: lines within the C code (typically used between variable definitions and
  661: statements).
  663: @item
  664: You do not start it with @samp{@{}.  Then the C code ends at the first
  665: empty line, so you cannot have empty lines within this code.
  667: @end itemize
  669: The text in @code{comment}, @code{eval-escape} and @code{c-escape} must
  670: not contain a newline.  @code{Ident} must conform to the usual
  671: conventions of C identifiers (otherwise the C compiler would choke on
  672: the Vmgen output), except that idents in @code{stack-effect} may have a
  673: stack prefix (for stack prefix syntax, @pxref{Eval escapes}).
  675: @cindex C escape
  676: @cindex @code{\C}
  677: @cindex conditional compilation of Vmgen output
  678: The @code{c-escape} passes the text through to each output file (without
  679: the @samp{\C}).  This is useful mainly for conditional compilation
  680: (i.e., you write @samp{\C #if ...} etc.).
  682: @cindex sync lines
  683: @cindex @code{#line}
  684: In addition to the syntax given in the grammer, Vmgen also processes
  685: sync lines (lines starting with @samp{#line}), as produced by @samp{m4
  686: -s} (@pxref{Invoking m4, , Invoking m4,, GNU m4}) and similar
  687: tools.  This allows associating C compiler error messages with the
  688: original source of the C code.
  690: Vmgen understands a few extensions beyond the grammar given here, but
  691: these extensions are only useful for building Gforth.  You can find a
  692: description of the format used for Gforth in @file{prim}.
  694: @menu
  695: * Eval escapes::                what follows \E
  696: @end menu
  698: @node Eval escapes,  , Input File Grammar, Input File Grammar
  699: @subsection Eval escapes
  700: @cindex escape to Forth
  701: @cindex eval escape
  702: @cindex @code{\E}
  704: @c woanders?
  705: The text in @code{eval-escape} is Forth code that is evaluated when
  706: Vmgen reads the line.  You will normally use this feature to define
  707: stacks and types.
  709: If you do not know (and do not want to learn) Forth, you can build the
  710: text according to the following grammar; these rules are normally all
  711: Forth you need for using Vmgen:
  713: @example
  714: text: stack-decl|type-prefix-decl|stack-prefix-decl|set-flag
  716: stack-decl: 'stack ' ident ident ident
  717: type-prefix-decl: 
  718:     's" ' string '" ' ('single'|'double') ident 'type-prefix' ident
  719: stack-prefix-decl:  ident 'stack-prefix' string
  720: set-flag: ('store-optimization'|'include-skipped-insts') ('on'|'off')
  721: @end example
  723: Note that the syntax of this code is not checked thoroughly (there are
  724: many other Forth program fragments that could be written in an
  725: eval-escape).
  727: A stack prefix can contain letters, digits, or @samp{:}, and may start
  728: with an @samp{#}; e.g., in Gforth the return stack has the stack prefix
  729: @samp{R:}.  This restriction is not checked during the stack prefix
  730: definition, but it is enforced by the parsing rules for stack items
  731: later.
  733: If you know Forth, the stack effects of the non-standard words involved
  734: are:
  735: @findex stack
  736: @findex type-prefix
  737: @findex single
  738: @findex double
  739: @findex stack-prefix
  740: @findex store-optimization
  741: @example
  742: stack                 ( "name" "pointer" "type" -- )
  743:                       ( name execution: -- stack )
  744: type-prefix           ( addr u item-size stack "prefix" -- )
  745: single                ( -- item-size )
  746: double                ( -- item-size )
  747: stack-prefix          ( stack "prefix" -- )
  748: store-optimization    ( -- addr )
  749: include-skipped-insts ( -- addr )
  750: @end example
  752: An @var{item-size} takes three cells on the stack.
  754: @c --------------------------------------------------------------------
  755: @node Simple instructions, Superinstructions, Input File Grammar, Input File Format
  756: @section Simple instructions
  757: @cindex simple VM instruction
  758: @cindex instruction, simple VM
  760: We will use the following simple VM instruction description as example:
  762: @example
  763: sub ( i1 i2 -- i )
  764: i = i1-i2;
  765: @end example
  767: The first line specifies the name of the VM instruction (@code{sub}) and
  768: its stack effect (@code{i1 i2 -- i}).  The rest of the description is
  769: just plain C code.
  771: @cindex stack effect
  772: @cindex effect, stack
  773: The stack effect specifies that @code{sub} pulls two integers from the
  774: data stack and puts them in the C variables @code{i1} and @code{i2}
  775: (with the rightmost item (@code{i2}) taken from the top of stack;
  776: intuition: if you push @code{i1}, then @code{i2} on the stack, the
  777: resulting stack picture is @code{i1 i2}) and later pushes one integer
  778: (@code{i}) on the data stack (the rightmost item is on the top
  779: afterwards).
  781: @cindex prefix, type
  782: @cindex type prefix
  783: @cindex default stack of a type prefix
  784: How do we know the type and stack of the stack items?  Vmgen uses
  785: prefixes, similar to Fortran; in contrast to Fortran, you have to
  786: define the prefix first:
  788: @example
  789: \E s" Cell"   single data-stack type-prefix i
  790: @end example
  792: This defines the prefix @code{i} to refer to the type @code{Cell}
  793: (defined as @code{long} in @file{mini.h}) and, by default, to the
  794: @code{data-stack}.  It also specifies that this type takes one stack
  795: item (@code{single}).  The type prefix is part of the variable name.
  797: @cindex stack definition
  798: @cindex defining a stack
  799: Before we can use @code{data-stack} in this way, we have to define it:
  801: @example
  802: \E stack data-stack sp Cell
  803: @end example
  804: @c !! use something other than Cell
  806: @cindex stack basic type
  807: @cindex basic type of a stack
  808: @cindex type of a stack, basic
  809: This line defines the stack @code{data-stack}, which uses the stack
  810: pointer @code{sp}, and each item has the basic type @code{Cell}; other
  811: types have to fit into one or two @code{Cell}s (depending on whether the
  812: type is @code{single} or @code{double} wide), and are cast from and to
  813: Cells on accessing the @code{data-stack} with type cast macros
  814: (@pxref{VM engine}).  By default, stacks grow towards lower addresses in
  815: Vmgen-erated interpreters (@pxref{Stack growth direction}).
  817: @cindex stack prefix
  818: @cindex prefix, stack
  819: We can override the default stack of a stack item by using a stack
  820: prefix.  E.g., consider the following instruction:
  822: @example
  823: lit ( #i -- i )
  824: @end example
  826: The VM instruction @code{lit} takes the item @code{i} from the
  827: instruction stream (indicated by the prefix @code{#}), and pushes it on
  828: the (default) data stack.  The stack prefix is not part of the variable
  829: name.  Stack prefixes are defined like this:
  831: @example
  832: \E inst-stream stack-prefix #
  833: \E data-stack  stack-prefix S:
  834: @end example
  836: This definition defines that the stack prefix @code{#} specifies the
  837: ``stack'' @code{inst-stream}.  Since the instruction stream behaves a
  838: little differently than an ordinary stack, it is predefined, and you do
  839: not need to define it.
  841: @cindex instruction stream
  842: The instruction stream contains instructions and their immediate
  843: arguments, so specifying that an argument comes from the instruction
  844: stream indicates an immediate argument.  Of course, instruction stream
  845: arguments can only appear to the left of @code{--} in the stack effect.
  846: If there are multiple instruction stream arguments, the leftmost is the
  847: first one (just as the intuition suggests).
  849: @menu
  850: * Explicit stack access::       If the C code accesses a stack pointer
  851: * C Code Macros::               Macros recognized by Vmgen
  852: * C Code restrictions::         Vmgen makes assumptions about C code
  853: * Stack growth direction::      is configurable per stack
  854: @end menu
  856: @c --------------------------------------------------------------------
  857: @node  Explicit stack access, C Code Macros, Simple instructions, Simple instructions
  858: @subsection Explicit stack access
  859: @cindex stack access, explicit
  860: @cindex Stack pointer access
  861: @cindex explicit stack access
  863: Not all stack effects can be specified using the stack effect
  864: specifications above.  For VM instructions that have other stack
  865: effects, you can specify them explicitly by accessing the stack
  866: pointer in the C code; however, you have to notify Vmgen of such
  867: explicit stack accesses, otherwise Vmgens optimizations could conflict
  868: with your explicit stack accesses.
  870: You notify Vmgen by putting @code{...} with the appropriate stack
  871: prefix into the stack comment.  Then the VM instruction will first
  872: take the other stack items specified in the stack effect into C
  873: variables, then make sure that all other stack items for that stack
  874: are in memory, and that the stack pointer for the stack points to the
  875: top-of-stack (by default, unless you change the stack access
  876: transformation: @pxref{Stack growth direction}).
  878: The general rule is: If you mention a stack pointer in the C code of a
  879: VM instruction, you should put a @code{...} for that stack in the stack
  880: effect.
  882: Consider this example:
  884: @example
  885: return ( #iadjust S:... target afp i1 -- i2 )
  886: SET_IP(target);
  887: sp = (Cell *)(((char *)sp)+iadjust);
  888: fp = afp;
  889: i2=i1;
  890: @end example
  892: First the variables @code{target afp i1} are popped off the stack,
  893: then the stack pointer @code{sp} is set correctly for the new stack
  894: depth, then the C code changes the stack depth and does other things,
  895: and finally @code{i2} is pushed on the stack with the new depth.
  897: The position of the @code{...} within the stack effect does not
  898: matter.  You can use several @code{...}s, for different stacks, and
  899: also several for the same stack (that has no additional effect).  If
  900: you use @code{...} without a stack prefix, this specifies all the
  901: stacks except the instruction stream.
  903: You cannot use @code{...} for the instruction stream, but that is not
  904: necessary: At the start of the C code, @code{IP} points to the start
  905: of the next VM instruction (i.e., right beyond the end of the current
  906: VM instruction), and you can change the instruction pointer with
  907: @code{SET_IP} (@pxref{VM engine}).
  910: @c --------------------------------------------------------------------
  911: @node C Code Macros, C Code restrictions, Explicit stack access, Simple instructions
  912: @subsection C Code Macros
  913: @cindex macros recognized by Vmgen
  914: @cindex basic block, VM level
  916: Vmgen recognizes the following strings in the C code part of simple
  917: instructions:
  919: @table @code
  921: @item SET_IP
  922: @findex SET_IP
  923: As far as Vmgen is concerned, a VM instruction containing this ends a VM
  924: basic block (used in profiling to delimit profiled sequences).  On the C
  925: level, this also sets the instruction pointer.
  927: @item SUPER_END
  928: @findex SUPER_END
  929: This ends a basic block (for profiling), even if the instruction
  930: contains no @code{SET_IP}.
  932: @item INST_TAIL;
  933: @findex INST_TAIL;
  934: Vmgen replaces @samp{INST_TAIL;} with code for ending a VM instruction and
  935: dispatching the next VM instruction.  Even without a @samp{INST_TAIL;} this
  936: happens automatically when control reaches the end of the C code.  If
  937: you want to have this in the middle of the C code, you need to use
  938: @samp{INST_TAIL;}.  A typical example is a conditional VM branch:
  940: @example
  941: if (branch_condition) @{
  942:   SET_IP(target); INST_TAIL;
  943: @}
  944: /* implicit tail follows here */
  945: @end example
  947: In this example, @samp{INST_TAIL;} is not strictly necessary, because there
  948: is another one implicitly after the if-statement, but using it improves
  949: branch prediction accuracy slightly and allows other optimizations.
  951: @item SUPER_CONTINUE
  952: @findex SUPER_CONTINUE
  953: This indicates that the implicit tail at the end of the VM instruction
  954: dispatches the sequentially next VM instruction even if there is a
  955: @code{SET_IP} in the VM instruction.  This enables an optimization that
  956: is not yet implemented in the vmgen-ex code (but in Gforth).  The
  957: typical application is in conditional VM branches:
  959: @example
  960: if (branch_condition) @{
  961:   SET_IP(target); INST_TAIL; /* now this INST_TAIL is necessary */
  962: @}
  964: @end example
  966: @item VM_JUMP
  967: @findex VM_JUMP
  968: @code{VM_JUMP(target)} is equivalent to @code{goto *(target)}, but
  969: allows Vmgen to do dynamic superinstructions and replication.  You
  970: still need to say @code{SUPER_END}.  Also, the goto only happens at
  971: the end (wherever the VM_JUMP is).  Essentially, this just suppresses
  972: much of the ordinary dispatch mechanism.
  974: @end table
  976: Note that Vmgen is not smart about C-level tokenization, comments,
  977: strings, or conditional compilation, so it will interpret even a
  978: commented-out SUPER_END as ending a basic block (or, e.g.,
  979: @samp{RESET_IP;} as @samp{SET_IP;}).  Conversely, Vmgen requires the literal
  980: presence of these strings; Vmgen will not see them if they are hiding in
  981: a C preprocessor macro.
  984: @c --------------------------------------------------------------------
  985: @node C Code restrictions, Stack growth direction, C Code Macros, Simple instructions
  986: @subsection C Code restrictions
  987: @cindex C code restrictions
  988: @cindex restrictions on C code
  989: @cindex assumptions about C code
  991: @cindex accessing stack (pointer)
  992: @cindex stack pointer, access
  993: @cindex instruction pointer, access
  994: Vmgen generates code and performs some optimizations under the
  995: assumption that the user-supplied C code does not access the stack
  996: pointers or stack items, and that accesses to the instruction pointer
  997: only occur through special macros.  In general you should heed these
  998: restrictions.  However, if you need to break these restrictions, read
  999: the following.
 1001: Accessing a stack or stack pointer directly can be a problem for several
 1002: reasons: 
 1003: @cindex stack caching, restriction on C code
 1004: @cindex superinstructions, restrictions on components
 1006: @itemize @bullet
 1008: @item
 1009: Vmgen optionally supports caching the top-of-stack item in a local
 1010: variable (that is allocated to a register).  This is the most frequent
 1011: source of trouble.  You can deal with it either by not using
 1012: top-of-stack caching (slowdown factor 1-1.4, depending on machine), or
 1013: by inserting flushing code (e.g., @samp{IF_spTOS(sp[...] = spTOS);}) at
 1014: the start and reloading code (e.g., @samp{IF_spTOS(spTOS = sp[0])}) at
 1015: the end of problematic C code.  Vmgen inserts a stack pointer update
 1016: before the start of the user-supplied C code, so the flushing code has
 1017: to use an index that corrects for that.  In the future, this flushing
 1018: may be done automatically by mentioning a special string in the C code.
 1019: @c sometimes flushing and/or reloading unnecessary
 1021: @item
 1022: The Vmgen-erated code loads the stack items from stack-pointer-indexed
 1023: memory into variables before the user-supplied C code, and stores them
 1024: from variables to stack-pointer-indexed memory afterwards.  If you do
 1025: any writes to the stack through its stack pointer in your C code, it
 1026: will not affect the variables, and your write may be overwritten by the
 1027: stores after the C code.  Similarly, a read from a stack using a stack
 1028: pointer will not reflect computations of stack items in the same VM
 1029: instruction.
 1031: @item
 1032: Superinstructions keep stack items in variables across the whole
 1033: superinstruction.  So you should not include VM instructions, that
 1034: access a stack or stack pointer, as components of superinstructions
 1035: (@pxref{VM profiler}).
 1037: @end itemize
 1039: You should access the instruction pointer only through its special
 1040: macros (@samp{IP}, @samp{SET_IP}, @samp{IPTOS}); this ensure that these
 1041: macros can be implemented in several ways for best performance.
 1042: @samp{IP} points to the next instruction, and @samp{IPTOS} is its
 1043: contents.
 1045: @c --------------------------------------------------------------------
 1046: @node Stack growth direction,  , C Code restrictions, Simple instructions
 1047: @subsection Stack growth direction
 1048: @cindex stack growth direction
 1050: @cindex @code{stack-access-transform}
 1051: By default, the stacks grow towards lower addresses.  You can change
 1052: this for a stack by setting the @code{stack-access-transform} field of
 1053: the stack to an xt @code{( itemnum -- index )} that performs the
 1054: appropriate index transformation.
 1056: E.g., if you want to let @code{data-stack} grow towards higher
 1057: addresses, with the stack pointer always pointing just beyond the
 1058: top-of-stack, use this right after defining @code{data-stack}:
 1060: @example
 1061: \E : sp-access-transform ( itemnum -- index ) negate 1- ;
 1062: \E ' sp-access-transform ' data-stack >body stack-access-transform !
 1063: @end example
 1065: This means that @code{sp-access-transform} will be used to generate
 1066: indexes for accessing @code{data-stack}.  The definition of
 1067: @code{sp-access-transform} above transforms n into -n-1, e.g, 1 into -2.
 1068: This will access the 0th data-stack element (top-of-stack) at sp[-1],
 1069: the 1st at sp[-2], etc., which is the typical way upward-growing
 1070: stacks are used.  If you need a different transform and do not know
 1071: enough Forth to program it, let me know.
 1073: @c --------------------------------------------------------------------
 1074: @node Superinstructions, Store Optimization, Simple instructions, Input File Format
 1075: @section Superinstructions
 1076: @cindex superinstructions, defining
 1077: @cindex defining superinstructions
 1079: Note: don't invest too much work in (static) superinstructions; a future
 1080: version of Vmgen will support dynamic superinstructions (see Ian
 1081: Piumarta and Fabio Riccardi, @cite{Optimizing Direct Threaded Code by
 1082: Selective Inlining}, PLDI'98), and static superinstructions have much
 1083: less benefit in that context (preliminary results indicate only a factor
 1084: 1.1 speedup).
 1086: Here is an example of a superinstruction definition:
 1088: @example
 1089: lit_sub = lit sub
 1090: @end example
 1092: @code{lit_sub} is the name of the superinstruction, and @code{lit} and
 1093: @code{sub} are its components.  This superinstruction performs the same
 1094: action as the sequence @code{lit} and @code{sub}.  It is generated
 1095: automatically by the VM code generation functions whenever that sequence
 1096: occurs, so if you want to use this superinstruction, you just need to
 1097: add this definition (and even that can be partially automatized,
 1098: @pxref{VM profiler}).
 1100: @cindex prefixes of superinstructions
 1101: Vmgen requires that the component instructions are simple instructions
 1102: defined before superinstructions using the components.  Currently, Vmgen
 1103: also requires that all the subsequences at the start of a
 1104: superinstruction (prefixes) must be defined as superinstruction before
 1105: the superinstruction.  I.e., if you want to define a superinstruction
 1107: @example
 1108: foo4 = load add sub mul
 1109: @end example
 1111: you first have to define @code{load}, @code{add}, @code{sub} and
 1112: @code{mul}, plus
 1114: @example
 1115: foo2 = load add
 1116: foo3 = load add sub
 1117: @end example
 1119: Here, @code{sumof4} is the longest prefix of @code{sumof5}, and @code{sumof3}
 1120: is the longest prefix of @code{sumof4}.
 1122: Note that Vmgen assumes that only the code it generates accesses stack
 1123: pointers, the instruction pointer, and various stack items, and it
 1124: performs optimizations based on this assumption.  Therefore, VM
 1125: instructions where your C code changes the instruction pointer should
 1126: only be used as last component; a VM instruction where your C code
 1127: accesses a stack pointer should not be used as component at all.  Vmgen
 1128: does not check these restrictions, they just result in bugs in your
 1129: interpreter.
 1131: @cindex include-skipped-insts
 1132: The Vmgen flag @code{include-skipped-insts} influences superinstruction
 1133: code generation.  Currently there is no support in the peephole
 1134: optimizer for both variations, so leave this flag alone for now.
 1136: @c -------------------------------------------------------------------
 1137: @node  Store Optimization, Register Machines, Superinstructions, Input File Format
 1138: @section Store Optimization
 1139: @cindex store optimization
 1140: @cindex optimization, stack stores
 1141: @cindex stack stores, optimization
 1142: @cindex eliminating stack stores
 1144: This minor optimization (0.6\%--0.8\% reduction in executed instructions
 1145: for Gforth) puts additional requirements on the instruction descriptions
 1146: and is therefore disabled by default.
 1148: What does it do?  Consider an instruction like
 1150: @example
 1151: dup ( n -- n n )
 1152: @end example
 1154: For simplicity, also assume that we are not caching the top-of-stack in
 1155: a register.  Now, the C code for dup first loads @code{n} from the
 1156: stack, and then stores it twice to the stack, one time to the address
 1157: where it came from; that time is unnecessary, but gcc does not optimize
 1158: it away, so vmgen can do it instead (if you turn on the store
 1159: optimization).
 1161: Vmgen uses the stack item's name to determine if the stack item contains
 1162: the same value as it did at the start.  Therefore, if you use the store
 1163: optimization, you have to ensure that stack items that have the same
 1164: name on input and output also have the same value, and are not changed
 1165: in the C code you supply.  I.e., the following code could fail if you
 1166: turn on the store optimization:
 1168: @example
 1169: add1 ( n -- n )
 1170: n++;
 1171: @end example
 1173: Instead, you have to use different names, i.e.:
 1175: @example
 1176: add1 ( n1 -- n2 )
 1177: n2=n1+1;
 1178: @end example
 1180: Similarly, the store optimization assumes that the stack pointer is only
 1181: changed by Vmgen-erated code.  If your C code changes the stack pointer,
 1182: use different names in input and output stack items to avoid a (probably
 1183: wrong) store optimization, or turn the store optimization off for this
 1184: VM instruction.
 1186: To turn on the store optimization, write
 1188: @example
 1189: \E store-optimization on
 1190: @end example
 1192: at the start of the file.  You can turn this optimization on or off
 1193: between any two VM instruction descriptions.  For turning it off again,
 1194: you can use
 1196: @example
 1197: \E store-optimization off
 1198: @end example
 1200: @c -------------------------------------------------------------------
 1201: @node Register Machines,  , Store Optimization, Input File Format
 1202: @section Register Machines
 1203: @cindex Register VM
 1204: @cindex Superinstructions for register VMs
 1205: @cindex tracing of register VMs
 1207: If you want to implement a register VM rather than a stack VM with
 1208: Vmgen, there are two ways to do it: Directly and through
 1209: superinstructions.
 1211: If you use the direct way, you define instructions that take the
 1212: register numbers as immediate arguments, like this:
 1214: @example
 1215: add3 ( #src1 #src2 #dest -- )
 1216: reg[dest] = reg[src1]+reg[src2];
 1217: @end example
 1219: A disadvantage of this method is that during tracing you only see the
 1220: register numbers, but not the register contents.  Actually, with an
 1221: appropriate definition of @code{printarg_src} (@pxref{VM engine}), you
 1222: can print the values of the source registers on entry, but you cannot
 1223: print the value of the destination register on exit.
 1225: If you use superinstructions to define a register VM, you define simple
 1226: instructions that use a stack, and then define superinstructions that
 1227: have no overall stack effect, like this:
 1229: @example
 1230: loadreg ( #src -- n )
 1231: n = reg[src];
 1233: storereg ( n #dest -- )
 1234: reg[dest] = n;
 1236: adds ( n1 n2 -- n )
 1237: n = n1+n2;
 1239: add3 = loadreg loadreg adds storereg
 1240: @end example
 1242: An advantage of this method is that you see the values and not just the
 1243: register numbers in tracing.  A disadvantage of this method is that
 1244: currently you cannot generate superinstructions directly, but only
 1245: through generating a sequence of simple instructions (we might change
 1246: this in the future if there is demand).
 1248: Could the register VM support be improved, apart from the issues
 1249: mentioned above?  It is hard to see how to do it in a general way,
 1250: because there are a number of different designs that different people
 1251: mean when they use the term @emph{register machine} in connection with
 1252: VM interpreters.  However, if you have ideas or requests in that
 1253: direction, please let me know (@pxref{Contact}).
 1255: @c ********************************************************************
 1256: @node Error messages, Using the generated code, Input File Format, Top
 1257: @chapter Error messages
 1258: @cindex error messages
 1260: These error messages are created by Vmgen:
 1262: @table @code
 1264: @cindex @code{# can only be on the input side} error
 1265: @item # can only be on the input side
 1266: You have used an instruction-stream prefix (usually @samp{#}) after the
 1267: @samp{--} (the output side); you can only use it before (the input
 1268: side).
 1270: @cindex @code{prefix for this combination must be defined earlier} error
 1271: @item the prefix for this superinstruction must be defined earlier
 1272: You have defined a superinstruction (e.g. @code{abc = a b c}) without
 1273: defining its direct prefix (e.g., @code{ab = a b}),
 1274: @xref{Superinstructions}.
 1276: @cindex @code{sync line syntax} error
 1277: @item sync line syntax
 1278: If you are using a preprocessor (e.g., @command{m4}) to generate Vmgen
 1279: input code, you may want to create @code{#line} directives (aka sync
 1280: lines).  This error indicates that such a line is not in th syntax
 1281: expected by Vmgen (this should not happen; please report the offending
 1282: line in a bug report).
 1284: @cindex @code{syntax error, wrong char} error
 1285: @item syntax error, wrong char
 1286: A syntax error.  If you do not see right away where the error is, it may
 1287: be helpful to check the following: Did you put an empty line in a VM
 1288: instruction where the C code is not delimited by braces (then the empty
 1289: line ends the VM instruction)?  If you used brace-delimited C code, did
 1290: you put the delimiting braces (and only those) at the start of the line,
 1291: without preceding white space?  Did you forget a delimiting brace?
 1293: @cindex @code{too many stacks} error
 1294: @item too many stacks
 1295: Vmgen currently supports 3 stacks (plus the instruction stream); if you
 1296: need more, let us know.
 1298: @cindex @code{unknown prefix} error
 1299: @item unknown prefix
 1300: The stack item does not match any defined type prefix (after stripping
 1301: away any stack prefix).  You should either declare the type prefix you
 1302: want for that stack item, or use a different type prefix
 1304: @cindex @code{unknown primitive} error
 1305: @item unknown primitive
 1306: You have used the name of a simple VM instruction in a superinstruction
 1307: definition without defining the simple VM instruction first.
 1309: @end table
 1311: In addition, the C compiler can produce errors due to code produced by
 1312: Vmgen; e.g., you need to define type cast functions.
 1314: @c ********************************************************************
 1315: @node Using the generated code, Hints, Error messages, Top
 1316: @chapter Using the generated code
 1317: @cindex generated code, usage
 1318: @cindex Using vmgen-erated code
 1320: The easiest way to create a working VM interpreter with Vmgen is
 1321: probably to start with @file{vmgen-ex}, and modify it for your purposes.
 1322: This chapter explains what the various wrapper and generated files do.
 1323: It also contains reference-manual style descriptions of the macros,
 1324: variables etc. used by the generated code, and you can skip that on
 1325: first reading.
 1327: @menu
 1328: * VM engine::                   Executing VM code
 1329: * VM instruction table::        
 1330: * VM code generation::          Creating VM code (in the front-end)
 1331: * Peephole optimization::       Creating VM superinstructions
 1332: * VM disassembler::             for debugging the front end
 1333: * VM profiler::                 for finding worthwhile superinstructions
 1334: @end menu
 1336: @c --------------------------------------------------------------------
 1337: @node VM engine, VM instruction table, Using the generated code, Using the generated code
 1338: @section VM engine
 1339: @cindex VM instruction execution
 1340: @cindex engine
 1341: @cindex executing VM code
 1342: @cindex @file{engine.c}
 1343: @cindex @file{-vm.i} output file
 1345: The VM engine is the VM interpreter that executes the VM code.  It is
 1346: essential for an interpretive system.
 1348: Vmgen supports two methods of VM instruction dispatch: @emph{threaded
 1349: code} (fast, but gcc-specific), and @emph{switch dispatch} (slow, but
 1350: portable across C compilers); you can use conditional compilation
 1351: (@samp{defined(__GNUC__)}) to choose between these methods, and our
 1352: example does so.
 1354: For both methods, the VM engine is contained in a C-level function.
 1355: Vmgen generates most of the contents of the function for you
 1356: (@file{@var{name}-vm.i}), but you have to define this function, and
 1357: macros and variables used in the engine, and initialize the variables.
 1358: In our example the engine function also includes
 1359: @file{@var{name}-labels.i} (@pxref{VM instruction table}).
 1361: @cindex tracing VM code
 1362: @cindex superinstructions and tracing
 1363: In addition to executing the code, the VM engine can optionally also
 1364: print out a trace of the executed instructions, their arguments and
 1365: results.  For superinstructions it prints the trace as if only component
 1366: instructions were executed; this allows to introduce new
 1367: superinstructions while keeping the traces comparable to old ones
 1368: (important for regression tests).
 1370: It costs significant performance to check in each instruction whether to
 1371: print tracing code, so we recommend producing two copies of the engine:
 1372: one for fast execution, and one for tracing.  See the rules for
 1373: @file{engine.o} and @file{engine-debug.o} in @file{vmgen-ex/Makefile}
 1374: for an example.
 1376: The following macros and variables are used in @file{@var{name}-vm.i}:
 1378: @table @code
 1380: @findex LABEL
 1381: @item LABEL(@var{inst_name})
 1382: This is used just before each VM instruction to provide a jump or
 1383: @code{switch} label (the @samp{:} is provided by Vmgen).  For switch
 1384: dispatch this should expand to @samp{case @var{label}:}; for
 1385: threaded-code dispatch this should just expand to @samp{@var{label}:}.
 1386: In either case @var{label} is usually the @var{inst_name} with some
 1387: prefix or suffix to avoid naming conflicts.
 1389: @findex LABEL2
 1390: @item LABEL2(@var{inst_name})
 1391: This will be used for dynamic superinstructions; at the moment, this
 1392: should expand to nothing.
 1394: @findex NAME
 1395: @item NAME(@var{inst_name_string})
 1396: Called on entering a VM instruction with a string containing the name of
 1397: the VM instruction as parameter.  In normal execution this should be
 1398: expand to nothing, but for tracing this usually prints the name, and
 1399: possibly other information (several VM registers in our example).
 1401: @findex DEF_CA
 1402: @item DEF_CA
 1403: Usually empty.  Called just inside a new scope at the start of a VM
 1404: instruction.  Can be used to define variables that should be visible
 1405: during every VM instruction.  If you define this macro as non-empty, you
 1406: have to provide the finishing @samp{;} in the macro.
 1408: @findex NEXT_P0
 1409: @findex NEXT_P1
 1410: @findex NEXT_P2
 1411: @item NEXT_P0 NEXT_P1 NEXT_P2
 1412: The three parts of instruction dispatch.  They can be defined in
 1413: different ways for best performance on various processors (see
 1414: @file{engine.c} in the example or @file{engine/threaded.h} in Gforth).
 1415: @samp{NEXT_P0} is invoked right at the start of the VM instruction (but
 1416: after @samp{DEF_CA}), @samp{NEXT_P1} right after the user-supplied C
 1417: code, and @samp{NEXT_P2} at the end.  The actual jump has to be
 1418: performed by @samp{NEXT_P2} (if you would do it earlier, important parts
 1419: of the VM instruction would not be executed).
 1421: The simplest variant is if @samp{NEXT_P2} does everything and the other
 1422: macros do nothing.  Then also related macros like @samp{IP},
 1423: @samp{SET_IP}, @samp{IP}, @samp{INC_IP} and @samp{IPTOS} are very
 1424: straightforward to define.  For switch dispatch this code consists just
 1425: of a jump to the dispatch code (@samp{goto next_inst;} in our example);
 1426: for direct threaded code it consists of something like
 1427: @samp{(@{cfa=*ip++; goto *cfa;@})}.
 1429: Pulling code (usually the @samp{cfa=*ip++;}) up into @samp{NEXT_P1}
 1430: usually does not cause problems, but pulling things up into
 1431: @samp{NEXT_P0} usually requires changing the other macros (and, at least
 1432: for Gforth on Alpha, it does not buy much, because the compiler often
 1433: manages to schedule the relevant stuff up by itself).  An even more
 1434: extreme variant is to pull code up even further, into, e.g., NEXT_P1 of
 1435: the previous VM instruction (prefetching, useful on PowerPCs).
 1437: @findex INC_IP
 1438: @item INC_IP(@var{n})
 1439: This increments @code{IP} by @var{n}.
 1441: @findex SET_IP
 1442: @item SET_IP(@var{target})
 1443: This sets @code{IP} to @var{target}.
 1445: @cindex type cast macro
 1446: @findex vm_@var{A}2@var{B}
 1447: @item vm_@var{A}2@var{B}(a,b)
 1448: Type casting macro that assigns @samp{a} (of type @var{A}) to @samp{b}
 1449: (of type @var{B}).  This is mainly used for getting stack items into
 1450: variables and back.  So you need to define macros for every combination
 1451: of stack basic type (@code{Cell} in our example) and type-prefix types
 1452: used with that stack (in both directions).  For the type-prefix type,
 1453: you use the type-prefix (not the C type string) as type name (e.g.,
 1454: @samp{vm_Cell2i}, not @samp{vm_Cell2Cell}).  In addition, you have to
 1455: define a vm_@var{X}2@var{X} macro for the stack's basic type @var{X}
 1456: (used in superinstructions).
 1458: @cindex instruction stream, basic type
 1459: The stack basic type for the predefined @samp{inst-stream} is
 1460: @samp{Cell}.  If you want a stack with the same item size, making its
 1461: basic type @samp{Cell} usually reduces the number of macros you have to
 1462: define.
 1464: @cindex unions in type cast macros
 1465: @cindex casts in type cast macros
 1466: @cindex type casting between floats and integers
 1467: Here our examples differ a lot: @file{vmgen-ex} uses casts in these
 1468: macros, whereas @file{vmgen-ex2} uses union-field selection (or
 1469: assignment to union fields).  Note that casting floats into integers and
 1470: vice versa changes the bit pattern (and you do not want that).  In this
 1471: case your options are to use a (temporary) union, or to take the address
 1472: of the value, cast the pointer, and dereference that (not always
 1473: possible, and sometimes expensive).
 1475: @findex vm_two@var{A}2@var{B}
 1476: @findex vm_@var{B}2two@var{A}
 1477: @item vm_two@var{A}2@var{B}(a1,a2,b)
 1478: @item vm_@var{B}2two@var{A}(b,a1,a2)
 1479: Type casting between two stack items (@code{a1}, @code{a2}) and a
 1480: variable @code{b} of a type that takes two stack items.  This does not
 1481: occur in our small examples, but you can look at Gforth for examples
 1482: (see @code{vm_twoCell2d} in @file{engine/forth.h}).
 1484: @cindex stack pointer definition
 1485: @cindex instruction pointer definition
 1486: @item @var{stackpointer}
 1487: For each stack used, the stackpointer name given in the stack
 1488: declaration is used.  For a regular stack this must be an l-expression;
 1489: typically it is a variable declared as a pointer to the stack's basic
 1490: type.  For @samp{inst-stream}, the name is @samp{IP}, and it can be a
 1491: plain r-value; typically it is a macro that abstracts away the
 1492: differences between the various implementations of @code{NEXT_P*}.
 1494: @cindex IMM_ARG
 1495: @findex IMM_ARG
 1496: @item IMM_ARG(access,value)
 1497: Define this to expland to ``(access)''.  This is just a placeholder for
 1498: future extensions.
 1500: @cindex top of stack caching
 1501: @cindex stack caching
 1502: @cindex TOS
 1503: @findex IPTOS
 1504: @item @var{stackpointer}TOS
 1505: The top-of-stack for the stack pointed to by @var{stackpointer}.  If you
 1506: are using top-of-stack caching for that stack, this should be defined as
 1507: variable; if you are not using top-of-stack caching for that stack, this
 1508: should be a macro expanding to @samp{@var{stackpointer}[0]}.  The stack
 1509: pointer for the predefined @samp{inst-stream} is called @samp{IP}, so
 1510: the top-of-stack is called @samp{IPTOS}.
 1512: @findex IF_@var{stackpointer}TOS
 1513: @item IF_@var{stackpointer}TOS(@var{expr})
 1514: Macro for executing @var{expr}, if top-of-stack caching is used for the
 1515: @var{stackpointer} stack.  I.e., this should do @var{expr} if there is
 1516: top-of-stack caching for @var{stackpointer}; otherwise it should do
 1517: nothing.
 1519: @findex SUPER_END
 1520: @item SUPER_END
 1521: This is used by the VM profiler (@pxref{VM profiler}); it should not do
 1522: anything in normal operation, and call @code{vm_count_block(IP)} for
 1523: profiling.
 1525: @findex SUPER_CONTINUE
 1526: @item SUPER_CONTINUE
 1527: This is just a hint to Vmgen and does nothing at the C level.
 1529: @findex MAYBE_UNUSED
 1530: @item MAYBE_UNUSED
 1531: This should be defined as @code{__attribute__((unused))} for gcc-2.7 and
 1532: higher.  It suppresses the warnings about unused variables in the code
 1533: for superinstructions.  You need to define this only if you are using
 1534: superinstructions.
 1536: @findex VM_DEBUG
 1537: @item VM_DEBUG
 1538: If this is defined, the tracing code will be compiled in (slower
 1539: interpretation, but better debugging).  Our example compiles two
 1540: versions of the engine, a fast-running one that cannot trace, and one
 1541: with potential tracing and profiling.
 1543: @findex vm_debug
 1544: @item vm_debug
 1545: Needed only if @samp{VM_DEBUG} is defined.  If this variable contains
 1546: true, the VM instructions produce trace output.  It can be turned on or
 1547: off at any time.
 1549: @findex vm_out
 1550: @item vm_out
 1551: Needed only if @samp{VM_DEBUG} is defined.  Specifies the file on which
 1552: to print the trace output (type @samp{FILE *}).
 1554: @findex printarg_@var{type}
 1555: @item printarg_@var{type}(@var{value})
 1556: Needed only if @samp{VM_DEBUG} is defined.  Macro or function for
 1557: printing @var{value} in a way appropriate for the @var{type}.  This is
 1558: used for printing the values of stack items during tracing.  @var{Type}
 1559: is normally the type prefix specified in a @code{type-prefix} definition
 1560: (e.g., @samp{printarg_i}); in superinstructions it is currently the
 1561: basic type of the stack.
 1563: @end table
 1566: @c --------------------------------------------------------------------
 1567: @node VM instruction table, VM code generation, VM engine, Using the generated code
 1568: @section VM instruction table
 1569: @cindex instruction table
 1570: @cindex opcode definition
 1571: @cindex labels for threaded code
 1572: @cindex @code{vm_prim}, definition
 1573: @cindex @file{-labels.i} output file
 1575: For threaded code we also need to produce a table containing the labels
 1576: of all VM instructions.  This is needed for VM code generation
 1577: (@pxref{VM code generation}), and it has to be done in the engine
 1578: function, because the labels are not visible outside.  It then has to be
 1579: passed outside the function (and assigned to @samp{vm_prim}), to be used
 1580: by the VM code generation functions.
 1582: This means that the engine function has to be called first to produce
 1583: the VM instruction table, and later, after generating VM code, it has to
 1584: be called again to execute the generated VM code (yes, this is ugly).
 1585: In our example program, these two modes of calling the engine function
 1586: are differentiated by the value of the parameter ip0 (if it equals 0,
 1587: then the table is passed out, otherwise the VM code is executed); in our
 1588: example, we pass the table out by assigning it to @samp{vm_prim} and
 1589: returning from @samp{engine}.
 1591: In our example (@file{vmgen-ex/engine.c}), we also build such a table for
 1592: switch dispatch; this is mainly done for uniformity.
 1594: For switch dispatch, we also need to define the VM instruction opcodes
 1595: used as case labels in an @code{enum}.
 1597: For both purposes (VM instruction table, and enum), the file
 1598: @file{@var{name}-labels.i} is generated by Vmgen.  You have to define
 1599: the following macro used in this file:
 1601: @table @code
 1603: @findex INST_ADDR
 1604: @item INST_ADDR(@var{inst_name})
 1605: For switch dispatch, this is just the name of the switch label (the same
 1606: name as used in @samp{LABEL(@var{inst_name})}), for both uses of
 1607: @file{@var{name}-labels.i}.  For threaded-code dispatch, this is the
 1608: address of the label defined in @samp{LABEL(@var{inst_name})}); the
 1609: address is taken with @samp{&&} (@pxref{Labels as Values, , Labels as
 1610: Values,, GNU C Manual}).
 1612: @end table
 1615: @c --------------------------------------------------------------------
 1616: @node VM code generation, Peephole optimization, VM instruction table, Using the generated code
 1617: @section VM code generation
 1618: @cindex VM code generation
 1619: @cindex code generation, VM
 1620: @cindex @file{-gen.i} output file
 1622: Vmgen generates VM code generation functions in @file{@var{name}-gen.i}
 1623: that the front end can call to generate VM code.  This is essential for
 1624: an interpretive system.
 1626: @findex gen_@var{inst}
 1627: For a VM instruction @samp{x ( #a b #c -- d )}, Vmgen generates a
 1628: function with the prototype
 1630: @example
 1631: void gen_x(Inst **ctp, a_type a, c_type c)
 1632: @end example
 1634: The @code{ctp} argument points to a pointer to the next instruction.
 1635: @code{*ctp} is increased by the generation functions; i.e., you should
 1636: allocate memory for the code to be generated beforehand, and start with
 1637: *ctp set at the start of this memory area.  Before running out of
 1638: memory, allocate a new area, and generate a VM-level jump to the new
 1639: area (this overflow handling is not implemented in our examples).
 1641: @cindex immediate arguments, VM code generation
 1642: The other arguments correspond to the immediate arguments of the VM
 1643: instruction (with their appropriate types as defined in the
 1644: @code{type_prefix} declaration.
 1646: The following types, variables, and functions are used in
 1647: @file{@var{name}-gen.i}:
 1649: @table @code
 1651: @findex Inst
 1652: @item Inst
 1653: The type of the VM instruction; if you use threaded code, this is
 1654: @code{void *}; for switch dispatch this is an integer type.
 1656: @cindex @code{vm_prim}, use
 1657: @item vm_prim
 1658: The VM instruction table (type: @code{Inst *}, @pxref{VM instruction table}).
 1660: @findex gen_inst
 1661: @item gen_inst(Inst **ctp, Inst i)
 1662: This function compiles the instruction @code{i}.  Take a look at it in
 1663: @file{vmgen-ex/peephole.c}.  It is trivial when you don't want to use
 1664: superinstructions (just the last two lines of the example function), and
 1665: slightly more complicated in the example due to its ability to use
 1666: superinstructions (@pxref{Peephole optimization}).
 1668: @findex genarg_@var{type_prefix}
 1669: @item genarg_@var{type_prefix}(Inst **ctp, @var{type} @var{type_prefix})
 1670: This compiles an immediate argument of @var{type} (as defined in a
 1671: @code{type-prefix} definition).  These functions are trivial to define
 1672: (see @file{vmgen-ex/support.c}).  You need one of these functions for
 1673: every type that you use as immediate argument.
 1675: @end table
 1677: @findex BB_BOUNDARY
 1678: In addition to using these functions to generate code, you should call
 1679: @code{BB_BOUNDARY} at every basic block entry point if you ever want to
 1680: use superinstructions (or if you want to use the profiling supported by
 1681: Vmgen; but this support is also useful mainly for selecting
 1682: superinstructions).  If you use @code{BB_BOUNDARY}, you should also
 1683: define it (take a look at its definition in @file{vmgen-ex/mini.y}).
 1685: You do not need to call @code{BB_BOUNDARY} after branches, because you
 1686: will not define superinstructions that contain branches in the middle
 1687: (and if you did, and it would work, there would be no reason to end the
 1688: superinstruction at the branch), and because the branches announce
 1689: themselves to the profiler.
 1692: @c --------------------------------------------------------------------
 1693: @node Peephole optimization, VM disassembler, VM code generation, Using the generated code
 1694: @section Peephole optimization
 1695: @cindex peephole optimization
 1696: @cindex superinstructions, generating
 1697: @cindex @file{peephole.c}
 1698: @cindex @file{-peephole.i} output file
 1700: You need peephole optimization only if you want to use
 1701: superinstructions.  But having the code for it does not hurt much if you
 1702: do not use superinstructions.
 1704: A simple greedy peephole optimization algorithm is used for
 1705: superinstruction selection: every time @code{gen_inst} compiles a VM
 1706: instruction, it checks if it can combine it with the last VM instruction
 1707: (which may also be a superinstruction resulting from a previous peephole
 1708: optimization); if so, it changes the last instruction to the combined
 1709: instruction instead of laying down @code{i} at the current @samp{*ctp}.
 1711: The code for peephole optimization is in @file{vmgen-ex/peephole.c}.
 1712: You can use this file almost verbatim.  Vmgen generates
 1713: @file{@var{file}-peephole.i} which contains data for the peephole
 1714: optimizer.
 1716: @findex init_peeptable
 1717: You have to call @samp{init_peeptable()} after initializing
 1718: @samp{vm_prim}, and before compiling any VM code to initialize data
 1719: structures for peephole optimization.  After that, compiling with the VM
 1720: code generation functions will automatically combine VM instructions
 1721: into superinstructions.  Since you do not want to combine instructions
 1722: across VM branch targets (otherwise there will not be a proper VM
 1723: instruction to branch to), you have to call @code{BB_BOUNDARY}
 1724: (@pxref{VM code generation}) at branch targets.
 1727: @c --------------------------------------------------------------------
 1728: @node VM disassembler, VM profiler, Peephole optimization, Using the generated code
 1729: @section VM disassembler
 1730: @cindex VM disassembler
 1731: @cindex disassembler, VM code
 1732: @cindex @file{disasm.c}
 1733: @cindex @file{-disasm.i} output file
 1735: A VM code disassembler is optional for an interpretive system, but
 1736: highly recommended during its development and maintenance, because it is
 1737: very useful for detecting bugs in the front end (and for distinguishing
 1738: them from VM interpreter bugs).
 1740: Vmgen supports VM code disassembling by generating
 1741: @file{@var{file}-disasm.i}.  This code has to be wrapped into a
 1742: function, as is done in @file{vmgen-ex/disasm.c}.  You can use this file
 1743: almost verbatim.  In addition to @samp{vm_@var{A}2@var{B}(a,b)},
 1744: @samp{vm_out}, @samp{printarg_@var{type}(@var{value})}, which are
 1745: explained above, the following macros and variables are used in
 1746: @file{@var{file}-disasm.i} (and you have to define them):
 1748: @table @code
 1750: @item ip
 1751: This variable points to the opcode of the current VM instruction.
 1753: @cindex @code{IP}, @code{IPTOS} in disassmbler
 1754: @item IP IPTOS
 1755: @samp{IPTOS} is the first argument of the current VM instruction, and
 1756: @samp{IP} points to it; this is just as in the engine, but here
 1757: @samp{ip} points to the opcode of the VM instruction (in contrast to the
 1758: engine, where @samp{ip} points to the next cell, or even one further).
 1760: @findex VM_IS_INST
 1761: @item VM_IS_INST(Inst i, int n)
 1762: Tests if the opcode @samp{i} is the same as the @samp{n}th entry in the
 1763: VM instruction table.
 1765: @end table
 1768: @c --------------------------------------------------------------------
 1769: @node VM profiler,  , VM disassembler, Using the generated code
 1770: @section VM profiler
 1771: @cindex VM profiler
 1772: @cindex profiling for selecting superinstructions
 1773: @cindex superinstructions and profiling
 1774: @cindex @file{profile.c}
 1775: @cindex @file{-profile.i} output file
 1777: The VM profiler is designed for getting execution and occurence counts
 1778: for VM instruction sequences, and these counts can then be used for
 1779: selecting sequences as superinstructions.  The VM profiler is probably
 1780: not useful as profiling tool for the interpretive system.  I.e., the VM
 1781: profiler is useful for the developers, but not the users of the
 1782: interpretive system.
 1784: The output of the profiler is: for each basic block (executed at least
 1785: once), it produces the dynamic execution count of that basic block and
 1786: all its subsequences; e.g.,
 1788: @example
 1789:        9227465  lit storelocal 
 1790:        9227465  storelocal branch 
 1791:        9227465  lit storelocal branch 
 1792: @end example
 1794: I.e., a basic block consisting of @samp{lit storelocal branch} is
 1795: executed 9227465 times.
 1797: @cindex @file{stat.awk}
 1798: @cindex @file{seq2rule.awk}
 1799: This output can be combined in various ways.  E.g.,
 1800: @file{vmgen-ex/stat.awk} adds up the occurences of a given sequence wrt
 1801: dynamic execution, static occurence, and per-program occurence.  E.g.,
 1803: @example
 1804:       2      16        36910041 loadlocal lit 
 1805: @end example
 1807: @noindent
 1808: indicates that the sequence @samp{loadlocal lit} occurs in 2 programs,
 1809: in 16 places, and has been executed 36910041 times.  Now you can select
 1810: superinstructions in any way you like (note that compile time and space
 1811: typically limit the number of superinstructions to 100--1000).  After
 1812: you have done that, @file{vmgen/seq2rule.awk} turns lines of the form
 1813: above into rules for inclusion in a Vmgen input file.  Note that this
 1814: script does not ensure that all prefixes are defined, so you have to do
 1815: that in other ways.  So, an overall script for turning profiles into
 1816: superinstructions can look like this:
 1818: @example
 1819: awk -f stat.awk|
 1820: awk '$3>=10000'|                #select sequences
 1821: fgrep -v -f peephole-blacklist| #eliminate wrong instructions
 1822: awk -f seq2rule.awk|            #turn into superinstructions
 1823: sort -k 3 >mini-super.vmg       #sort sequences
 1824: @end example
 1826: Here the dynamic count is used for selecting sequences (preliminary
 1827: results indicate that the static count gives better results, though);
 1828: the third line eliminates sequences containing instructions that must not
 1829: occur in a superinstruction, because they access a stack directly.  The
 1830: dynamic count selection ensures that all subsequences (including
 1831: prefixes) of longer sequences occur (because subsequences have at least
 1832: the same count as the longer sequences); the sort in the last line
 1833: ensures that longer superinstructions occur after their prefixes.
 1835: But before using this, you have to have the profiler.  Vmgen supports its
 1836: creation by generating @file{@var{file}-profile.i}; you also need the
 1837: wrapper file @file{vmgen-ex/profile.c} that you can use almost verbatim.
 1839: @cindex @code{SUPER_END} in profiling
 1840: @cindex @code{BB_BOUNDARY} in profiling
 1841: The profiler works by recording the targets of all VM control flow
 1842: changes (through @code{SUPER_END} during execution, and through
 1843: @code{BB_BOUNDARY} in the front end), and counting (through
 1844: @code{SUPER_END}) how often they were targeted.  After the program run,
 1845: the numbers are corrected such that each VM basic block has the correct
 1846: count (entering a block without executing a branch does not increase the
 1847: count, and the correction fixes that), then the subsequences of all
 1848: basic blocks are printed.  To get all this, you just have to define
 1849: @code{SUPER_END} (and @code{BB_BOUNDARY}) appropriately, and call
 1850: @code{vm_print_profile(FILE *file)} when you want to output the profile
 1851: on @code{file}.
 1853: @cindex @code{VM_IS_INST} in profiling
 1854: The @file{@var{file}-profile.i} is similar to the disassembler file, and
 1855: it uses variables and functions defined in @file{vmgen-ex/profile.c},
 1856: plus @code{VM_IS_INST} already defined for the VM disassembler
 1857: (@pxref{VM disassembler}).
 1859: @c **********************************************************
 1860: @node Hints, The future, Using the generated code, Top
 1861: @chapter Hints
 1862: @cindex hints
 1864: @menu
 1865: * Floating point::              and stacks
 1866: @end menu
 1868: @c --------------------------------------------------------------------
 1869: @node Floating point,  , Hints, Hints
 1870: @section Floating point
 1872: How should you deal with floating point values?  Should you use the same
 1873: stack as for integers/pointers, or a different one?  This section
 1874: discusses this issue with a view on execution speed.
 1876: The simpler approach is to use a separate floating-point stack.  This
 1877: allows you to choose FP value size without considering the size of the
 1878: integers/pointers, and you avoid a number of performance problems.  The
 1879: main downside is that this needs an FP stack pointer (and that may not
 1880: fit in the register file on the 386 arhitecture, costing some
 1881: performance, but comparatively little if you take the other option into
 1882: account).  If you use a separate FP stack (with stack pointer @code{fp}),
 1883: using an fpTOS is helpful on most machines, but some spill the fpTOS
 1884: register into memory, and fpTOS should not be used there.
 1886: The other approach is to share one stack (pointed to by, say, @code{sp})
 1887: between integer/pointer and floating-point values.  This is ok if you do
 1888: not use @code{spTOS}.  If you do use @code{spTOS}, the compiler has to
 1889: decide whether to put that variable into an integer or a floating point
 1890: register, and the other type of operation becomes quite expensive on
 1891: most machines (because moving values between integer and FP registers is
 1892: quite expensive).  If a value of one type has to be synthesized out of
 1893: two values of the other type (@code{double} types), things are even more
 1894: interesting.
 1896: One way around this problem would be to not use the @code{spTOS}
 1897: supported by Vmgen, but to use explicit top-of-stack variables (one for
 1898: integers, one for FP values), and having a kind of accumulator+stack
 1899: architecture (e.g., Ocaml bytecode uses this approach); however, this is
 1900: a major change, and it's ramifications are not completely clear.
 1902: @c **********************************************************
 1903: @node The future, Changes, Hints, Top
 1904: @chapter The future
 1905: @cindex future ideas
 1907: We have a number of ideas for future versions of Vmgen.  However, there
 1908: are so many possible things to do that we would like some feedback from
 1909: you.  What are you doing with Vmgen, what features are you missing, and
 1910: why?
 1912: One idea we are thinking about is to generate just one @file{.c} file
 1913: instead of letting you copy and adapt all the wrapper files (you would
 1914: still have to define stuff like the type-specific macros, and stack
 1915: pointers etc. somewhere).  The advantage would be that, if we change the
 1916: wrapper files between versions, you would not need to integrate your
 1917: changes and our changes to them; Vmgen would also be easier to use for
 1918: beginners.  The main disadvantage of that is that it would reduce the
 1919: flexibility of Vmgen a little (well, those who like flexibility could
 1920: still patch the resulting @file{.c} file, like they are now doing for
 1921: the wrapper files).  In any case, if you are doing things to the wrapper
 1922: files that would cause problems in a generated-@file{.c}-file approach,
 1923: please let us know.
 1925: @c **********************************************************
 1926: @node Changes, Contact, The future, Top
 1927: @chapter Changes
 1928: @cindex Changes from old versions
 1930: User-visible changes between 0.5.9-20020822 and 0.5.9-20020901:
 1932: The store optimization is now disabled by default, but can be enabled by
 1933: the user (@pxref{Store Optimization}).  Documentation for this
 1934: optimization is also new.
 1936: User-visible changes between 0.5.9-20010501 and 0.5.9-20020822:
 1938: There is now a manual (in info, HTML, Postscript, or plain text format).
 1940: There is the vmgen-ex2 variant of the vmgen-ex example; the new
 1941: variant uses a union type instead of lots of casting.
 1943: Both variants of the example can now be compiled with an ANSI C compiler
 1944: (using switch dispatch and losing quite a bit of performance); tested
 1945: with @command{lcc}.
 1947: Users of the gforth-0.5.9-20010501 version of Vmgen need to change
 1948: several things in their source code to use the current version.  I
 1949: recommend keeping the gforth-0.5.9-20010501 version until you have
 1950: completed the change (note that you can have several versions of Gforth
 1951: installed at the same time).  I hope to avoid such incompatible changes
 1952: in the future.
 1954: The required changes are:
 1956: @table @code
 1958: @cindex @code{TAIL;}, changes
 1959: @item TAIL;
 1960: has been renamed into @code{INST_TAIL;} (less chance of an accidental
 1961: match).
 1963: @cindex @code{vm_@var{A}2@var{B}}, changes
 1964: @item vm_@var{A}2@var{B}
 1965: now takes two arguments.
 1967: @cindex @code{vm_two@var{A}2@var{B}}, changes
 1968: @item vm_two@var{A}2@var{B}(b,a1,a2);
 1969: changed to vm_two@var{A}2@var{B}(a1,a2,b) (note the absence of the @samp{;}).
 1971: @end table
 1973: Also some new macros have to be defined, e.g., @code{INST_ADDR}, and
 1974: @code{LABEL}; some macros have to be defined in new contexts, e.g.,
 1975: @code{VM_IS_INST} is now also needed in the disassembler.
 1977: @c *********************************************************
 1978: @node Contact, Copying This Manual, Changes, Top
 1979: @chapter Contact
 1981: To report a bug, use
 1982: @url{}.
 1984: For discussion on Vmgen (e.g., how to use it), use the mailing list
 1985: @email{} (use
 1986: @url{} to subscribe).
 1988: You can find vmgen information at
 1989: @url{}.
 1991: @c ***********************************************************
 1992: @node Copying This Manual, Index, Contact, Top
 1993: @appendix Copying This Manual
 1995: @menu
 1996: * GNU Free Documentation License::  License for copying this manual.
 1997: @end menu
 1999: @node GNU Free Documentation License,  , Copying This Manual, Copying This Manual
 2000: @appendixsec GNU Free Documentation License
 2001: @include fdl.texi
 2004: @node Index,  , Copying This Manual, Top
 2005: @unnumbered Index
 2007: @printindex cp
 2009: @bye

FreeBSD-CVSweb <>