Full Code of johnwinans/rvalp for AI

master aa309812b30d cached
56 files
391.0 KB
129.8k tokens
4 symbols
1 requests
Download .txt
Showing preview only (410K chars total). Download the full file or copy to clipboard to get everything.
Repository: johnwinans/rvalp
Branch: master
Commit: aa309812b30d
Files: 56
Total size: 391.0 KB

Directory structure:
gitextract_vt1ez9jz/

├── .gitignore
├── LICENSE
├── Make.rules
├── Makefile
├── README.md
├── book/
│   ├── .gitignore
│   ├── Makefile
│   ├── amodes/
│   │   └── chapter.tex
│   ├── ascii/
│   │   └── chapter.tex
│   ├── bibliography.bib
│   ├── binary/
│   │   ├── chapter.tex
│   │   └── rvddt_memdump.out
│   ├── colors.tex
│   ├── copyright/
│   │   └── chapter.tex
│   ├── elements/
│   │   ├── chapter.tex
│   │   ├── zero4regs.S
│   │   └── zero4regs.out
│   ├── float/
│   │   ├── chapter.tex
│   │   ├── cleandecimal.c
│   │   ├── cleandecimal.out
│   │   ├── erroraccumulation.c
│   │   ├── erroraccumulation.out
│   │   ├── errorcompensation.c
│   │   ├── errorcompensation.out
│   │   ├── powersoftwo.c
│   │   └── powersoftwo.out
│   ├── glossary.tex
│   ├── insnformats.tex
│   ├── insnsummary/
│   │   └── chapter.tex
│   ├── install/
│   │   └── chapter.tex
│   ├── intro/
│   │   └── chapter.tex
│   ├── license/
│   │   └── chapter.tex
│   ├── preamble.tex
│   ├── preface/
│   │   └── chapter.tex
│   ├── priv/
│   │   └── chapter.tex
│   ├── programs/
│   │   ├── chapter.tex
│   │   └── src/
│   │       ├── .gitignore
│   │       ├── Make.rules
│   │       ├── Makefile
│   │       └── mvzero/
│   │           ├── .gitignore
│   │           ├── Makefile
│   │           ├── mv.S
│   │           ├── mv.lst
│   │           ├── mv.out
│   │           └── run.sh
│   ├── refcard/
│   │   └── chapter.tex
│   ├── rv32/
│   │   ├── base.tex
│   │   ├── chapter.tex
│   │   └── insn/
│   │       └── lui.tex
│   ├── rv32m/
│   │   └── chapter.tex
│   ├── rvalp.tex
│   └── toolchain/
│       └── chapter.tex
└── texlib/
    ├── ENote.sty
    ├── MyFigs.sty
    ├── MyVerbatim.sty
    └── index.ist

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.swp


================================================
FILE: LICENSE
================================================
Attribution 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.

     Considerations for licensors: Our public licenses are
     intended for use by those authorized to give the public
     permission to use material in ways otherwise restricted by
     copyright and certain other rights. Our licenses are
     irrevocable. Licensors should read and understand the terms
     and conditions of the license they choose before applying it.
     Licensors should also secure all rights necessary before
     applying our licenses so that the public can reuse the
     material as expected. Licensors should clearly mark any
     material not subject to the license. This includes other CC-
     licensed material, or material used under an exception or
     limitation to copyright. More considerations for licensors:
	wiki.creativecommons.org/Considerations_for_licensors

     Considerations for the public: By using one of our public
     licenses, a licensor grants the public permission to use the
     licensed material under specified terms and conditions. If
     the licensor's permission is not necessary for any reason--for
     example, because of any applicable exception or limitation to
     copyright--then that use is not regulated by the license. Our
     licenses grant only permissions under copyright and certain
     other rights that a licensor has authority to grant. Use of
     the licensed material may still be restricted for other
     reasons, including because others have copyright or other
     rights in the material. A licensor may make special requests,
     such as asking that all changes be marked or described.
     Although not required by our licenses, you are encouraged to
     respect those requests where reasonable. More_considerations
     for the public:
	wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution 4.0 International Public License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.


Section 1 -- Definitions.

  a. Adapted Material means material subject to Copyright and Similar
     Rights that is derived from or based upon the Licensed Material
     and in which the Licensed Material is translated, altered,
     arranged, transformed, or otherwise modified in a manner requiring
     permission under the Copyright and Similar Rights held by the
     Licensor. For purposes of this Public License, where the Licensed
     Material is a musical work, performance, or sound recording,
     Adapted Material is always produced where the Licensed Material is
     synched in timed relation with a moving image.

  b. Adapter's License means the license You apply to Your Copyright
     and Similar Rights in Your contributions to Adapted Material in
     accordance with the terms and conditions of this Public License.

  c. Copyright and Similar Rights means copyright and/or similar rights
     closely related to copyright including, without limitation,
     performance, broadcast, sound recording, and Sui Generis Database
     Rights, without regard to how the rights are labeled or
     categorized. For purposes of this Public License, the rights
     specified in Section 2(b)(1)-(2) are not Copyright and Similar
     Rights.

  d. Effective Technological Measures means those measures that, in the
     absence of proper authority, may not be circumvented under laws
     fulfilling obligations under Article 11 of the WIPO Copyright
     Treaty adopted on December 20, 1996, and/or similar international
     agreements.

  e. Exceptions and Limitations means fair use, fair dealing, and/or
     any other exception or limitation to Copyright and Similar Rights
     that applies to Your use of the Licensed Material.

  f. Licensed Material means the artistic or literary work, database,
     or other material to which the Licensor applied this Public
     License.

  g. Licensed Rights means the rights granted to You subject to the
     terms and conditions of this Public License, which are limited to
     all Copyright and Similar Rights that apply to Your use of the
     Licensed Material and that the Licensor has authority to license.

  h. Licensor means the individual(s) or entity(ies) granting rights
     under this Public License.

  i. Share means to provide material to the public by any means or
     process that requires permission under the Licensed Rights, such
     as reproduction, public display, public performance, distribution,
     dissemination, communication, or importation, and to make material
     available to the public including in ways that members of the
     public may access the material from a place and at a time
     individually chosen by them.

  j. Sui Generis Database Rights means rights other than copyright
     resulting from Directive 96/9/EC of the European Parliament and of
     the Council of 11 March 1996 on the legal protection of databases,
     as amended and/or succeeded, as well as other essentially
     equivalent rights anywhere in the world.

  k. You means the individual or entity exercising the Licensed Rights
     under this Public License. Your has a corresponding meaning.


Section 2 -- Scope.

  a. License grant.

       1. Subject to the terms and conditions of this Public License,
          the Licensor hereby grants You a worldwide, royalty-free,
          non-sublicensable, non-exclusive, irrevocable license to
          exercise the Licensed Rights in the Licensed Material to:

            a. reproduce and Share the Licensed Material, in whole or
               in part; and

            b. produce, reproduce, and Share Adapted Material.

       2. Exceptions and Limitations. For the avoidance of doubt, where
          Exceptions and Limitations apply to Your use, this Public
          License does not apply, and You do not need to comply with
          its terms and conditions.

       3. Term. The term of this Public License is specified in Section
          6(a).

       4. Media and formats; technical modifications allowed. The
          Licensor authorizes You to exercise the Licensed Rights in
          all media and formats whether now known or hereafter created,
          and to make technical modifications necessary to do so. The
          Licensor waives and/or agrees not to assert any right or
          authority to forbid You from making technical modifications
          necessary to exercise the Licensed Rights, including
          technical modifications necessary to circumvent Effective
          Technological Measures. For purposes of this Public License,
          simply making modifications authorized by this Section 2(a)
          (4) never produces Adapted Material.

       5. Downstream recipients.

            a. Offer from the Licensor -- Licensed Material. Every
               recipient of the Licensed Material automatically
               receives an offer from the Licensor to exercise the
               Licensed Rights under the terms and conditions of this
               Public License.

            b. No downstream restrictions. You may not offer or impose
               any additional or different terms or conditions on, or
               apply any Effective Technological Measures to, the
               Licensed Material if doing so restricts exercise of the
               Licensed Rights by any recipient of the Licensed
               Material.

       6. No endorsement. Nothing in this Public License constitutes or
          may be construed as permission to assert or imply that You
          are, or that Your use of the Licensed Material is, connected
          with, or sponsored, endorsed, or granted official status by,
          the Licensor or others designated to receive attribution as
          provided in Section 3(a)(1)(A)(i).

  b. Other rights.

       1. Moral rights, such as the right of integrity, are not
          licensed under this Public License, nor are publicity,
          privacy, and/or other similar personality rights; however, to
          the extent possible, the Licensor waives and/or agrees not to
          assert any such rights held by the Licensor to the limited
          extent necessary to allow You to exercise the Licensed
          Rights, but not otherwise.

       2. Patent and trademark rights are not licensed under this
          Public License.

       3. To the extent possible, the Licensor waives any right to
          collect royalties from You for the exercise of the Licensed
          Rights, whether directly or through a collecting society
          under any voluntary or waivable statutory or compulsory
          licensing scheme. In all other cases the Licensor expressly
          reserves any right to collect such royalties.


Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the
following conditions.

  a. Attribution.

       1. If You Share the Licensed Material (including in modified
          form), You must:

            a. retain the following if it is supplied by the Licensor
               with the Licensed Material:

                 i. identification of the creator(s) of the Licensed
                    Material and any others designated to receive
                    attribution, in any reasonable manner requested by
                    the Licensor (including by pseudonym if
                    designated);

                ii. a copyright notice;

               iii. a notice that refers to this Public License;

                iv. a notice that refers to the disclaimer of
                    warranties;

                 v. a URI or hyperlink to the Licensed Material to the
                    extent reasonably practicable;

            b. indicate if You modified the Licensed Material and
               retain an indication of any previous modifications; and

            c. indicate the Licensed Material is licensed under this
               Public License, and include the text of, or the URI or
               hyperlink to, this Public License.

       2. You may satisfy the conditions in Section 3(a)(1) in any
          reasonable manner based on the medium, means, and context in
          which You Share the Licensed Material. For example, it may be
          reasonable to satisfy the conditions by providing a URI or
          hyperlink to a resource that includes the required
          information.

       3. If requested by the Licensor, You must remove any of the
          information required by Section 3(a)(1)(A) to the extent
          reasonably practicable.

       4. If You Share Adapted Material You produce, the Adapter's
          License You apply must not prevent recipients of the Adapted
          Material from complying with this Public License.


Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:

  a. for the avoidance of doubt, Section 2(a)(1) grants You the right
     to extract, reuse, reproduce, and Share all or a substantial
     portion of the contents of the database;

  b. if You include all or a substantial portion of the database
     contents in a database in which You have Sui Generis Database
     Rights, then the database in which You have Sui Generis Database
     Rights (but not its individual contents) is Adapted Material; and

  c. You must comply with the conditions in Section 3(a) if You Share
     all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.


Section 5 -- Disclaimer of Warranties and Limitation of Liability.

  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

  c. The disclaimer of warranties and limitation of liability provided
     above shall be interpreted in a manner that, to the extent
     possible, most closely approximates an absolute disclaimer and
     waiver of all liability.


Section 6 -- Term and Termination.

  a. This Public License applies for the term of the Copyright and
     Similar Rights licensed here. However, if You fail to comply with
     this Public License, then Your rights under this Public License
     terminate automatically.

  b. Where Your right to use the Licensed Material has terminated under
     Section 6(a), it reinstates:

       1. automatically as of the date the violation is cured, provided
          it is cured within 30 days of Your discovery of the
          violation; or

       2. upon express reinstatement by the Licensor.

     For the avoidance of doubt, this Section 6(b) does not affect any
     right the Licensor may have to seek remedies for Your violations
     of this Public License.

  c. For the avoidance of doubt, the Licensor may also offer the
     Licensed Material under separate terms or conditions or stop
     distributing the Licensed Material at any time; however, doing so
     will not terminate this Public License.

  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
     License.


Section 7 -- Other Terms and Conditions.

  a. The Licensor shall not be bound by any additional or different
     terms or conditions communicated by You unless expressly agreed.

  b. Any arrangements, understandings, or agreements regarding the
     Licensed Material not stated herein are separate from and
     independent of the terms and conditions of this Public License.


Section 8 -- Interpretation.

  a. For the avoidance of doubt, this Public License does not, and
     shall not be interpreted to, reduce, limit, restrict, or impose
     conditions on any use of the Licensed Material that could lawfully
     be made without permission under this Public License.

  b. To the extent possible, if any provision of this Public License is
     deemed unenforceable, it shall be automatically reformed to the
     minimum extent necessary to make it enforceable. If the provision
     cannot be reformed, it shall be severed from this Public License
     without affecting the enforceability of the remaining terms and
     conditions.

  c. No term or condition of this Public License will be waived and no
     failure to comply consented to unless expressly agreed to by the
     Licensor.

  d. Nothing in this Public License constitutes or may be interpreted
     as a limitation upon, or waiver of, any privileges and immunities
     that apply to the Licensor or You, including from the legal
     processes of any jurisdiction or authority.


=======================================================================

Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.

Creative Commons may be contacted at creativecommons.org.



================================================
FILE: Make.rules
================================================
TEXLIB=$(TOP)/texlib

# BEFORE including this file, you must define: TEXPATH


# This only works if there is at least one tag in the git repo
#GIT_SHOW_FORMAT=%ae %ci
GIT_SHOW_FORMAT=%ci
LATEXFLAGS="\newcommand\GitFileName{"`pwd | sed -e 's|^.*rvalp/|\\\textasciitilde/rvalp/|'`/"}\newcommand\GitDescription{"`git describe --long --dirty; git show -s --format='$(GIT_SHOW_FORMAT)';`"}\newcommand\GitRevision{"`git describe --long --dirty`"}\input{$<}"

LATEX_CLEANFILES = *.aux *.log *.dvi *.toc *.lof *.bbl *.blg *.ind *.ilg *.idx *.glo *.glg *.gls *.glsdefs *.out *.ist *.brf

.SUFFIXES: .tex .pdf .eps .fig .dot .png

.tex.pdf:
		( export TEXINPUTS=$(TEXPATH):$(TEXLIB)::; \
		BIBINPUTS=${TEXINPUTS}; export BIBINPUTS; \
		pdflatex $(LATEXFLAGS) $<; \
		cp $@ out-$@; \
		bibtex ${<:.tex=}; \
		makeindex -s $(TEXLIB)/index.ist ${<:.tex=}; \
		pdflatex $(LATEXFLAGS) $<; \
		cp $@ out-$@; \
		pdflatex $(LATEXFLAGS) $<;\
		cp $@ out-$@; )

#makeglossaries ${<:.tex=}; \

.fig.eps:
	fig2dev -L eps $< > $@

.fig.pdf:
	fig2dev -L pdftex $< > $@


# Rules for converting dot files into png files
.dot.png:
	dot -Tpng -o $@ $<

.dot.pdf:
	dot -Tpdf -o $@ $<



# Rules for walking a tree of Makefiles
# Add a prefix to each directory name to make unique versions for all, clean,...
CLEAN_DIRS=$(SUBDIRS:%=clean-%)
ALL_DIRS=$(SUBDIRS:%=all-%)

.PHONY: all clean world doc $(CLEAN_DIRS) $(ALL_DIRS) 

all:: $(ALL_DIRS)

clean:: $(CLEAN_DIRS)

# for each dir, do a make all
$(ALL_DIRS)::
	$(MAKE) -C $(@:all-%=%) all

# for each dir, do a make clean
$(CLEAN_DIRS)::
	$(MAKE) -C $(@:clean-%=%) clean

world:: clean all


================================================
FILE: Makefile
================================================
TOP=.

SUBDIRS=book

include $(TOP)/Make.rules


================================================
FILE: README.md
================================================
# rvalp

RISC-V Assembly Language Programming

This is an attempt to create a book on RISC-V programming in assembly language.

See the Releases page for pre-made PDF versions: https://github.com/johnwinans/rvalp/releases

Pull requests are welcome.

I will release PDFs after useful improvements from time to time into the releases area for those 
that don't wish to build their own.

You can find the rvddt simulator mentioned in the text here: https://github.com/johnwinans/rvddt
    
I developed this using LaTeX via texlive.  LaTeX is very portable.  You should 
be able to tinker with it on most any platform.  

On Ubuntu 20.04 and 18.04 LTS, loading the following packages worked for me:

	sudo apt install make      
	sudo apt install git
	sudo apt install texlive-latex-extra

I suspect the same (above) would work on 16.04 as well.

Then clone and build this repo:

    git clone https://github.com/johnwinans/rvalp.git
    cd rvalp
    make world

# Related Projects

The RISC-V simulator that I use to generate figures: https://github.com/johnwinans/rvddt

A RISC-V simulator with more advanced features (but is also more complicated): https://github.com/johnwinans/riscv-toolchain-install-guide

The toolchain used to assemble and compile programs in this book: https://github.com/riscv/riscv-gnu-toolchain


See Appendix A of rvalp for the precise details on how I downloaded and build each of these tools on Linux.

Note: During the great on-line COVID school year I recorded some lectures 
on RISC-V that use this book as a reference.  
These lectures appear in the following YouTube playlists:

* [RISC-V Lectures From NIU CSCI 463](https://www.youtube.com/playlist?list=PL3by7evD3F53Dz2RiB47Ztp9l_piGVuus)
* [The Whole NIU CSCI 463 Spring 2021 Playlist](https://www.youtube.com/playlist?list=PL3by7evD3F50NMukhaMqNdOt4pUHXT2Vo)


================================================
FILE: book/.gitignore
================================================
rvalp.aux
rvalp.brf
rvalp.idx
rvalp.ilg
rvalp.ind
rvalp.lof
rvalp.log
rvalp.pdf
rvalp.toc
rvalp.bbl
rvalp.blg
rvalp.out
*.aux
rvalp.glg
rvalp.glo
rvalp.gls
rvalp.glsdefs
rvalp.ist
*.bak
out-rvalp.pdf


================================================
FILE: book/Makefile
================================================
SUBDIRS=
#	programs/src

TOP=..
include $(TOP)/Make.rules

TEXPATH=float:intro:rv32:copyright:license:elements:binary:programs/src

all:: rvalp.pdf

clean::
	rm -f rvalp.pdf */*.aux $(LATEX_CLEANFILES)

rvalp.pdf:: *.tex bibliography.bib

spell:
	#find . -name "*.tex" -exec aspell --lang=en --mode=tex check "{}" \;
	find . -name "*.tex" -exec aspell --mode=tex check "{}" \;


================================================
FILE: book/amodes/chapter.tex
================================================
\chapter{Addressing Modes}


A box showing +/- 2KB regions for \reg{gp} addressing with 
LB, LBU, SB, LH, LHU, SH, LW, and SW instructions.

\BeginTikzPicture
	\draw(1.5,0) node{.data};
	\draw[->] (3,0) -- (4,0);		% right arrow

	\draw(2,10) node{gp};
	\draw[->] (3,10) -- (4,10);		% right arrow


%	\draw(0,15) node{+2KB};
%	\draw(0,5) node{-2KB};
	\draw[->] (6,9) -- (6,1);		% up arrow
	\draw[->] (6,11) -- (6,19);		% down arrow


	\draw(6,20) node{\tt 0x8fff};
	\draw(6,10) node{\tt 0x8800};
	\draw(6,0) node{\tt 0x8000};
\EndTikzPicture



================================================
FILE: book/ascii/chapter.tex
================================================
\chapter{The ASCII Character Set}
\label{chapter:ascii}
\index{ASCII}

A slightly abridged version of the Linux ``ASCII'' man(1) page.

\section{NAME}

ascii - ASCII character set encoded in octal, decimal, and hexadecimal

\section{DESCRIPTION}

       ASCII is the American Standard Code for Information Interchange.  It is
       a 7-bit code.  Many 8-bit codes (e.g., ISO  8859-1)  contain  ASCII  as
       their  lower  half.  The international counterpart of ASCII is known as
       ISO 646-IRV.

       The following table contains the 128 ASCII characters.

       C program '\verb@\X@' escapes are noted.

\begin{verbatim}
       Oct   Dec   Hex   Char                        Oct   Dec   Hex   Char
       ------------------------------------------------------------------------
       000   0     00    NUL '\0' (null character)   100   64    40    @
       001   1     01    SOH (start of heading)      101   65    41    A
       002   2     02    STX (start of text)         102   66    42    B
       003   3     03    ETX (end of text)           103   67    43    C
       004   4     04    EOT (end of transmission)   104   68    44    D
       005   5     05    ENQ (enquiry)               105   69    45    E
       006   6     06    ACK (acknowledge)           106   70    46    F
       007   7     07    BEL '\a' (bell)             107   71    47    G
       010   8     08    BS  '\b' (backspace)        110   72    48    H
       011   9     09    HT  '\t' (horizontal tab)   111   73    49    I
       012   10    0A    LF  '\n' (new line)         112   74    4A    J
       013   11    0B    VT  '\v' (vertical tab)     113   75    4B    K
       014   12    0C    FF  '\f' (form feed)        114   76    4C    L
       015   13    0D    CR  '\r' (carriage ret)     115   77    4D    M
       016   14    0E    SO  (shift out)             116   78    4E    N
       017   15    0F    SI  (shift in)              117   79    4F    O
       020   16    10    DLE (data link escape)      120   80    50    P
       021   17    11    DC1 (device control 1)      121   81    51    Q
       022   18    12    DC2 (device control 2)      122   82    52    R
       023   19    13    DC3 (device control 3)      123   83    53    S
       024   20    14    DC4 (device control 4)      124   84    54    T
       025   21    15    NAK (negative ack.)         125   85    55    U
       026   22    16    SYN (synchronous idle)      126   86    56    V
       027   23    17    ETB (end of trans. blk)     127   87    57    W
       030   24    18    CAN (cancel)                130   88    58    X
       031   25    19    EM  (end of medium)         131   89    59    Y
       032   26    1A    SUB (substitute)            132   90    5A    Z
       033   27    1B    ESC (escape)                133   91    5B    [
       034   28    1C    FS  (file separator)        134   92    5C    \  '\\'
       035   29    1D    GS  (group separator)       135   93    5D    ]
       036   30    1E    RS  (record separator)      136   94    5E    ^
       037   31    1F    US  (unit separator)        137   95    5F    _
       040   32    20    SPACE                       140   96    60    `
       041   33    21    !                           141   97    61    a
       042   34    22    "                           142   98    62    b
       043   35    23    #                           143   99    63    c
       044   36    24    $                           144   100   64    d
       045   37    25    %                           145   101   65    e
       046   38    26    &                           146   102   66    f
       047   39    27    '                           147   103   67    g
       050   40    28    (                           150   104   68    h
       051   41    29    )                           151   105   69    i
       052   42    2A    *                           152   106   6A    j
       053   43    2B    +                           153   107   6B    k
       054   44    2C    ,                           154   108   6C    l
       055   45    2D    -                           155   109   6D    m
       056   46    2E    .                           156   110   6E    n
       057   47    2F    /                           157   111   6F    o
       060   48    30    0                           160   112   70    p
       061   49    31    1                           161   113   71    q
       062   50    32    2                           162   114   72    r
       063   51    33    3                           163   115   73    s
       064   52    34    4                           164   116   74    t
       065   53    35    5                           165   117   75    u
       066   54    36    6                           166   118   76    v
       067   55    37    7                           167   119   77    w
       070   56    38    8                           170   120   78    x
       071   57    39    9                           171   121   79    y
       072   58    3A    :                           172   122   7A    z
       073   59    3B    ;                           173   123   7B    {
       074   60    3C    <                           174   124   7C    |
       075   61    3D    =                           175   125   7D    }
       076   62    3E    >                           176   126   7E    ~
       077   63    3F    ?                           177   127   7F    DEL
\end{verbatim}

\subsection{Tables}
For convenience, below are more compact tables in hex and decimal.

\begin{verbatim}
          2 3 4 5 6 7       30 40 50 60 70 80 90 100 110 120
        -------------      ---------------------------------
       0:   0 @ P ` p     0:    (  2  <  F  P  Z  d   n   x
       1: ! 1 A Q a q     1:    )  3  =  G  Q  [  e   o   y
       2: " 2 B R b r     2:    *  4  >  H  R  \  f   p   z
       3: # 3 C S c s     3: !  +  5  ?  I  S  ]  g   q   {
       4: $ 4 D T d t     4: "  ,  6  @  J  T  ^  h   r   |
       5: % 5 E U e u     5: #  -  7  A  K  U  _  i   s   }
       6: & 6 F V f v     6: $  .  8  B  L  V  `  j   t   ~
       7: ' 7 G W g w     7: %  /  9  C  M  W  a  k   u  DEL
       8: ( 8 H X h x     8: &  0  :  D  N  X  b  l   v
       9: ) 9 I Y i y     9: '  1  ;  E  O  Y  c  m   w
       A: * : J Z j z
       B: + ; K [ k {
       C: , < L \ l |
       D: - = M ] m }
       E: . > N ^ n ~
       F: / ? O _ o DEL
\end{verbatim}

\section{NOTES}
\subsection{History}

       An ascii manual page appeared in Version 7 of AT\&T UNIX.

       On older terminals, the underscore code is displayed as a  left  arrow,
       called  backarrow, the caret is displayed as an up-arrow and the 
vertical bar has a hole in the middle.

       Uppercase and lowercase characters differ by just one bit and the ASCII
       character  2  differs from the double quote by just one bit, too.  That
       made it much easier to encode characters mechanically or  with  a  
non-microcontroller-based electronic keyboard and that pairing was found on
       old teletypes.

       The ASCII standard was published by the United States of America  
Standards Institute (USASI) in 1968.

\section{COLOPHON}

       This page is part of release 4.04 of the Linux  man-pages  project.   A
       description  of  the project, information about reporting bugs, and the
       latest    version    of    this    page,    can     be     found     at
       \url{http://www.kernel.org/doc/man-pages/}.


================================================
FILE: book/bibliography.bib
================================================
@string{IETF="Internet Engineering Task Force"}

@manual{rvismv1v22:2017,
	title        = "\href{https://github.com/riscv/riscv-isa-manual}{The RISC-V Instruction Set Manual, Volume I: User-Level ISA, Document Version 2.2}",
	organization = "\href{https://riscv.org/}{RISC-V Foundation}",
	year         = 2017,
	month        = {May},
	note		 = {Editors Andrew Waterman and Krste Asanovi\'c}
}

@manual{rvismv2:2017,
	title        = "\href{https://github.com/riscv/riscv-isa-manual}{The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Document Version 1.10}",
	organization = "\href{https://riscv.org/}{RISC-V Foundation}",
	year         = 2017,
	month        = {May},
	note		 = {Editors Andrew Waterman and Krste Asanovi\'c}
}


@manual{rvpsabi:2017,
	title		= "\href{https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md}{RISC-V ELF psABI specification}",
	author		= {Palmer Dabbelt and Stefan O'Rear and Kito Cheng and Andrew Waterman and Michael Clark and Alex Bradbury and David Horner and Max Nordlund and Karsten Merker},
	year		= 2017
	
}


@book{riscvreader:2017,
	title			= {The RISC-V Reader: An Open Architecture Atlas},
	author			= {David Patterson and Andrew Waterman},
	publisher		= {Strawberry Canyon},
	month			= {Nov},
	year			= 2017,
	note			= {ISBN: 978-0999249116}
}

@book{codriscv:2017,
	title			= {Computer Organization and Design RISC-V Edition: The Hardware Software Interface},
	author			= {David Patterson and John Hennessy},
	publisher		= {Morgan Kaufmann},
	month			= {Apr},
	year			= 2017,
	note			= {ISBN: 978-0128122754}
}

@book{gcc:2017,
	title        = "\href{https://gcc.gnu.org/onlinedocs/}{Using the GNU Compiler Collection (For GCC version 7.3.0)}",
	author		 = {Richard M. Stallman and the GCC Developer Community},
	publisher	 = {GNU Press},
	address		 = {Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA},
	year         = 2017
}


@article{Decker:1985:MAT:989369.989375,
 author = {Decker, William F.},
 title = {A Modern Approach to Teaching Computer Organization and Assembly Language Programming},
 journal = {SIGCSE Bull.},
 issue_date = {December 1985},
 volume = {17},
 number = {4},
 month = {Dec},
 year = {1985},
 issn = {0097-8418},
 pages = {38--44},
 numpages = {7},
 url = {http://doi.acm.org/10.1145/989369.989375},
 doi = {10.1145/989369.989375},
 acmid = {989375},
 publisher = {ACM},
 address = {New York, NY, USA}
}


@manual{mcs85:1978,
	title        = {MCS-85 User's Manual},
	organization = {Intel},
	month        = {Sep},
	year         = 1978
}

@manual{edtasm:1978,
	title        = {TRS-80 Editor/Assembler Operation and Reference Manual},
	organization = {Radio Shack},
	year         = 1978
}

@manual{mc68000:1980,
	title        = {MC68000 16--bit Microprocessor User's Manual},
	edition		 = {2nd},
	organization = {Motorola},
	month		 = {Jan},
	year         = 1980,
	note		 = {MC68000UM(AD2)}
}
@manual{ns32k:1986,
	title        = {Series 32000 Databook},
	organization = {National Semiconductor Coprporation},
	year         = 1986
}

@book{assist:1983,
	title        = {Assembler Language With ASSIST},
	author		 = {Ross A. Overbeek and W. E. Singletary},
	edition		 = {2nd},
	publisher	 = {Science Research Associates, Inc.},
	year         = 1983
}

@manual{poo:1980,
    title			= {IBM System/370 Principals of Operation},
	edition			= {7th},
    organization	= {IBM},
	month			= {Mar},
    year			= 1980
}

@manual{assembler370:1979,
    title			= {OS/VS-DOS/VSE-VM/370 Assembler Language},
	edition			= {6th},
    organization	= {IBM},
	month			= {Mar},
    year			= 1979
}


@manual{ttl74154:1979,
	title			= "\href{http://www.ti.com/general/docs/lit/getliterature.tsp?baseLiteratureNumber=sdls056&fileType=pdf}{SN54154, SN74154 4--line to 16--line Decoders/Demultiplexers}",
	organization	= {Texas Instruments},
	month			= {Dec},
	year			= 1972
}

@manual{ttl74191:1979,
	title			= "\href{http://www.ti.com/lit/ds/symlink/sn74ls191.pdf}{SN54190, SN54191, SN54LS190, SN54LS191, SN74190, SN74191, SN74LS190, SN74LS191 Synchronous Up/Down Counters With Down/Up Mode Control}",
	organization	= {Texas Instruments},
	month			= {Mar},
	year			= 1988
}



@Misc{IEN137,
  author =       "Danny Cohen",
  title =        "\href{http://www.ietf.org/rfc/ien/ien137.txt}{IEN 137, On Holy Wars and a Plea for Peace}",
  month =        {Apr},
  year =         "1980",
  note =         "This note discusses the Big-Endian/Little-Endian
                 byte/bit-order controversy, but did not settle it. A
                 decade later, David V. James in ``Multiplexed Buses:
                 The Endian Wars Continue'', {\em IEEE Micro}, {\bf
                 10}(3), 9--21 (1990) continued the discussion.",
%%%  URL =          "http://www.ietf.org/rfc/ien/ien137.txt",
}


@misc{subtrahend,
  title = {Definition of Subtrahend},
  howpublished = {\href{https://www.mathsisfun.com/definitions/subtrahend.html}{www.mathsisfun.com/definitions/subtrahend.html}},
  note = {Accessed: 2018-06-02}
}

@article{ieee:754,
  author={},
  journal={IEEE Std 754-2019 (Revision of IEEE 754-2008)}, 
  title={IEEE Standard for Floating-Point Arithmetic}, 
  year={2019},
  volume={},
  number={},
  pages={1-84},}


@manual{zilog:1977,
    title           = {Z80 Assembly Language Programming Manual},
    organization    = {Zilog Inc.},
	month			= {Jan},
    year            = 1977
}


@book{leventhal:1979,
    title        = {Z80 Assembly Language Programming},
    author       = {Lance A. Leventhal},
    publisher    = {Osborne/McGraw-Hill},
    year         = 1979
}



================================================
FILE: book/binary/chapter.tex
================================================
\chapter{Numbers and Storage Systems}
\label{chapter:numbers}

This chapter discusses how data are represented and stored in a computer.

In the context of computing, {\em boolean} refers to a condition that can 
be either true or false and {\em binary} refers to the use of a base-2 
numeric system to represent numbers.

RISC-V assembly language uses binary to represent all values, be they 
boolean or numeric.  It is the context within which they are used that
determines whether they are boolean or numeric.

\enote{Add some diagrams here showing bits, bytes and the MSB, 
LSB,\ldots\ perhaps relocated from the RV32I chapter?}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Boolean Functions}

Boolean functions apply on a per-bit basis.
When applied to multi-bit values, each bit position is operated upon 
independent of the other bits.

RISC-V assembly language uses zero to represent {\em false} and one 
to represent {\em true}.  In general, however, it is useful to relax 
this and define zero {\bf and only zero} to be {\em false} and anything 
that is not {\em false} is therefore {\em true}.%
\footnote{This is how {\em true} and {\em false} behave in C, C++, and
many other languages as well as the common assembly language idioms
discussed in this text.}

The reason for this relaxation is to describe the common case 
where the CPU processes data, multiple \gls{bit}s at-a-time.

These
groups have names like \gls{byte} (8 bits), \gls{halfword} (16 bits) 
and \gls{fullword} (32 bits).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{NOT}

The {\em NOT} operator applies to a single operand and represents the 
opposite of the input.
\enote{Need to define unary, binary and ternary operators without 
confusing binary operators with binary numbers.}

If the input is 1 then the output is 0.  If the input is 0 then the
output is 1.  In other words, the output value is {\em not} that of the 
input value.

Expressing the {\em not} function in the form of a truth table:

\begin{center}
\begin{tabular}{c|c}
A & $\overline{\mbox{A}}$\\
\hline
0 & 1 \\
1 & 0 \\
\end{tabular}
\end{center}

A truth table is drawn by indicating all of the possible input values on 
the left of the vertical bar with each row displaying the output values 
that correspond to the input for that row.  The column headings are used
to define the illustrated operation expressed using a mathematical 
notation.  The {\em not} operation is indicated by the presence of
an {\em overline}.

In computer programming languages, things like an overline can not be 
efficiently expressed using a standard keyboard.  Therefore it is common 
to use a notation such as that used  by the C language when discussing 
the {\em NOT} operator in symbolic form.  Specifically the tilde: `\verb@~@'.

It is also uncommon to for programming languages to express boolean operations 
on single-bit input(s).  A more generalized operation is used that applies 
to a set of bits all at once.  For example, performing a {\em not} operation
of eight bits at once can be illustrated as:


\begin{verbatim}
  ~ 1 1 1 1 0 1 0 1  <== A
  -----------------
    0 0 0 0 1 0 1 0  <== output
\end{verbatim}

In a line of code the above might read like this: \verb@output = ~A@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{AND}

The boolean {\em and} function has two or more inputs and the output is a
single bit.  The output is 1 if and only if all of the input values are 1.
Otherwise it is 0.

This function works like it does in spoken language.  For example
if A is 1 {\em and} B is 1 then the output is 1 (true).
Otherwise the output is 0 (false).  

In mathematical notion, the {\em and} operator is expressed the same way
as is {\em multiplication}.  That is by a raised dot between, or by 
juxtaposition of, two variable names.  It is also worth noting that,
in base-2, the {\em and} operation actually {\em is} multiplication!

\begin{center}
\begin{tabular}{cc|c}
A & B & AB \\
\hline
0 & 0 & 0 \\
0 & 1 & 0 \\
1 & 0 & 0 \\
1 & 1 & 1 \\
\end{tabular}
\end{center}

This text will use the operator used in the C language when discussing 
the {\em and} operator in symbolic form.  Specifically the ampersand: `\verb@&@'.

An eight-bit example:

\begin{verbatim}
    1 1 1 1 0 1 0 1  <== A
  & 1 0 0 1 0 0 1 1  <== B
  -----------------
    1 0 0 1 0 0 0 1  <== output
\end{verbatim}

In a line of code the above might read like this: \verb@output = A & B@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{OR}

The boolean {\em or} function has two or more inputs and the output is a
single bit.  The output is 1 if at least one of the input values are 1.

This function works like it does in spoken language.  For example
if A is 1 {\em or} B is 1 then the output is 1 (true).
Otherwise the output is 0 (false).  

In mathematical notion, the {\em or} operator is expressed using the plus 
($+$).  

\begin{center}
\begin{tabular}{cc|c}
A & B & A$+$B \\
\hline
0 & 0 & 0 \\
0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 1 \\
\end{tabular}
\end{center}

This text will use the operator used in the C language when discussing
the {\em or}  operator in symbolic form.  Specifically the pipe: `\verb@|@'.

An eight-bit example:

\begin{verbatim}
    1 1 1 1 0 1 0 1  <== A
  | 1 0 0 1 0 0 1 1  <== B
  -----------------
    1 1 1 1 0 1 1 1  <== output
\end{verbatim}

In a line of code the above might read like this: \verb@output = A | B@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{XOR}

The boolean {\em exclusive or} function has two or more inputs and the 
output is a single bit.  The output is 1 if only an odd number of inputs 
are 1. Otherwise the output will be 0.

Note that when {\em xor} is used with two inputs, the output
is set to 1 (true) when the inputs have different values and 0 
(false) when the inputs both have the same value.

In mathematical notion, the {\em xor} operator is expressed using the plus
in a circle ($\oplus$).

\begin{center}
\begin{tabular}{cc|c}
A & B & A$\oplus{}$B \\
\hline
0 & 0 & 0 \\
0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0 \\
\end{tabular}
\end{center}

This text will use the operator used in the C language when discussing
the {\em xor}  operator in symbolic form.  Specifically the carrot: `\verb@^@'.


An eight-bit example:

\begin{verbatim}
    1 1 1 1 0 1 0 1  <== A
  ^ 1 0 0 1 0 0 1 1  <== B
  -----------------
    0 1 1 0 0 1 1 0  <== output
\end{verbatim}

In a line of code the above might read like this: \verb@output = A ^ B@


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Integers and Counting}

A binary integer is constructed with only 1s and 0s in the same
manner as decimal numbers are constructed with values from 0 to 9.

Counting in binary (base-2) uses the same basic rules as decimal (base-10).  
The difference is when we consider that there are ten decimal digits and 
only two binary digits.  Therefore, in base-10, we must carry when adding one to 
nine (because there is no digit representing a ten) and, in base-2, we must 
carry when adding one to one (because there is no digit representing a two.)

\autoref{Figure:integers} shows an abridged table of the decimal, binary and 
hexadecimal values ranging from $0_{10}$ to $128_{10}$.

\begin{figure}[t]
\begin{center}
\begin{tabular}{|c|c|c||c|c|c|c|c|c|c|c||c|c|}
\hline
\multicolumn{3}{|c||}{Decimal} & \multicolumn{8}{|c||}{Binary} & \multicolumn{2}{|c|}{Hex}\\
\hline
$10^2$	& $10^1$	& $10^0$	& $2^7$ & $2^6$ & $2^5$ & $2^4$ & $2^3$ & $2^2$ & $2^1$ & $2^0$		& $16^1$ & $16^0$	\\
\hline
100		&	10		& 1			& 128	& 64	& 32	& 16	& 8		& 4		& 2		& 1			& 16	& 1			\\
\hline \hline
0		&	0		&	0		& 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0		& 0 & 0 \\
0		&	0		&	1		& 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1		& 0 & 1 \\
0		&	0		&	2		& 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0		& 0 & 2 \\
0		&	0		&	3		& 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1		& 0 & 3 \\
0		&	0		&	4		& 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0		& 0 & 4 \\
0		&	0		&	5		& 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1		& 0 & 5 \\
0		&	0		&	6		& 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0		& 0 & 6 \\
0		&	0		&	7		& 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1		& 0 & 7 \\
0		&	0		&	8		& 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0		& 0 & 8 \\
0		&	0		&	9		& 0 & 0 & 0 & 0 & 1 & 0 & 0 & 1		& 0 & 9 \\
0		&	1		&	0		& 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0		& 0 & a \\
0		&	1		&	1		& 0 & 0 & 0 & 0 & 1 & 0 & 1 & 1		& 0 & b \\
0		&	1		&	2		& 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0		& 0 & c \\
0		&	1		&	3		& 0 & 0 & 0 & 0 & 1 & 1 & 0 & 1		& 0 & d \\
0		&	1		&	4		& 0 & 0 & 0 & 0 & 1 & 1 & 1 & 0		& 0 & e \\
0		&	1		&	5		& 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1		& 0 & f \\
0		&	1		&	6		& 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0		& 1 & 0 \\
0		&	1		&	7		& 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1		& 1 & 1 \\
\hline
\multicolumn{3}{|c||}{\ldots} & \multicolumn{8}{|c||}{\ldots} & \multicolumn{2}{|c|}{\ldots}\\
\hline
1       &   2       &   5		& 0 & 1 & 1 & 1 & 1 & 1 & 0 & 1		& 7 & d \\
1       &   2       &   6		& 0 & 1 & 1 & 1 & 1 & 1 & 1 & 0		& 7 & e \\
1       &   2       &   7		& 0 & 1 & 1 & 1 & 1 & 1 & 1 & 1		& 7 & f \\
1       &   2       &   8		& 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0		& 8 & 0 \\
\hline
\end{tabular}
\end{center}
\captionof{figure}{Counting in decimal, binary and hexadecimal.}
\label{Figure:integers}
\end{figure}

One way to look at this table is on a per-row basis where each 
\gls{place-value}
is represented by the base raised to the power of the \gls{place-value}
position (shown in the column headings.)  
%This is useful when converting arbitrary numeric values between bases.  
For example to interpret the decimal value on the fourth row: 

\begin{equation}
0 \times 10^2 + 0 \times 10^1 + 3 \times 10^0 = 3_{10}
\end{equation}

Interpreting the binary value on the fourth row by converting it to decimal:

\begin{equation}
0 \times 2^7 + 0 \times 2^6 +0 \times 2^5 +0 \times 2^4 +0 \times 2^3 +0 \times 2^2 + 1 \times 2^1 + 1 \times 2^0 = 3_{10}
\end{equation}

Interpreting the hexadecimal value on the fourth row by converting it to decimal:

\begin{equation}
0 \times 16^1 + 3 \times 16^0 = 3_{10}
\end{equation}

\index{Most significant bit}\index{MSB|see {Most significant bit}}%
\index{Least significant bit}\index{LSB|see {Least significant bit}}%
We refer to the place values with the largest exponent (the one furthest to the 
left for any given base) as the most significant digit and the place value
with the lowest exponent as the least significant digit.  For binary
numbers these are the \acrfull{msb} and \acrfull{lsb} respectively.%
\footnote{Changing the value of the MSB will have a more {\em significant}
impact on the numeric value than changing the value of the LSB.} 


Another way to look at this table is on a per-column basis.  When
tasked with drawing such a table by hand, it might be useful 
to observe that, just as in decimal, the right-most column will
cycle through all of the values represented in the chosen base
then cycle back to zero and repeat.  (For example, in binary this
pattern is 0-1-0-1-0-1-0-\ldots) The next column in each base
will cycle in the same manner except each of the values is repeated
as many times as is represented by the place value (in the case of 
decimal, $10^1$ times, binary $2^1$ times, hex $16^1$ times.  Again,
the binary numbers for this pattern are 0-0-1-1-0-0-1-1-\ldots)
This continues for as many columns as are needed to represent the 
magnitude of the desired number.

Another item worth noting is that any even binary number will always
have a 0 LSB and odd numbers will always have a 1 LSB.

As is customary in decimal, leading zeros are sometimes not shown 
for readability.

The relationship between binary and hex values is also worth taking
note.  Because $2^4 = 16$, there is a clean and simple grouping
of 4 \gls{bit}s to 1 \gls{hit} (aka \gls{nybble}).  
There is no such relationship between binary and decimal.  

Writing and reading numbers in binary that are longer than 8 bits 
is cumbersome and prone to error.  The simple conversion between 
binary and hex makes hex a convenient shorthand for expressing 
binary values in many situations.  

For example, consider the following value expressed in binary, 
hexadecimal and decimal (spaced to show the relationship
between binary and hex):

\begin{verbatim}
Binary value:       0010 0111 1011 1010 1100 1100 1111 0101
Hex Value:             2    7    B    A    C    C    F    5
Decimal Value:                                    666553589
\end{verbatim}

Empirically we can see that grouping the bits into sets of four
allows an easy conversion to hex and expressing it as such is
$\frac{1}{4}$ as long as in binary while at the same time
allowing for easy conversion back to binary.

The decimal value in this example does not easily convey a sense
of the binary value.

\begin{tcolorbox}
In programming languages like the C, its derivatives and RISC-V 
assembly, numeric values are interpreted as decimal {\bfseries unless} 
they start with a zero (0).  
Numbers that start with 0 are interpreted as octal (base-8), 
numbers starting with 0x are interpreted as hexadecimal and 
numbers that start with 0b are interpreted as binary.
\end{tcolorbox}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Converting Between Bases}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{From Binary to Decimal}
\label{section:bindec}

It is occasionally necessary to convert between decimal,
binary and/or hex.

To convert from binary to decimal, put the decimal value of the \gls{place-value}s 
{\ldots8, 4, 2, 1} over the binary digits like this:

\begin{verbatim}
Base-2 place values: 128 64 32 16  8  4  2  1
Binary:                0  0  0  1  1  0  1  1
Decimal:                       16 +8    +2 +1 = 27
\end{verbatim}

Now sum the place-values that are expressed in decimal for each 
bit with the value of 1: $16+8+2+1$.  The integer binary value
$00011011_2$ represents the decimal value $27_{10}$.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{From Binary to Hexadecimal}
\label{section:binhex}

Conversion from binary to hex involves grouping the bits into
sets of four and then performing the same summing process as 
shown above.  If there is not a multiple of four bits then
extend the binary to the left with zeros to make it so.

Grouping the bits into sets of four and summing:

\begin{verbatim}
Base-2 place values:   8 4 2 1     8 4 2 1     8 4 2 1     8 4 2 1
Binary:                0 1 1 0     1 1 0 1     1 0 1 0     1 1 1 0
Decimal:                 4+2  =6   8+4+  1=13  8+  2  =10  8+4+2  =14
\end{verbatim}

After the summing, convert each decimal value to hex.  The decimal
values from 0--9 are the same values in hex.  Because we don't have any
more numerals to represent the values from 10-15, we use the first 6
letters (See the right-most column of \autoref{Figure:integers}.)
Fortunately there are only six hex mappings involving letters.  Thus 
it is reasonable to memorize them.

Continuing this example:

\begin{verbatim}
Decimal:               6           13          10          14
Hex:                   6           D           A           E
\end{verbatim}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{From Hexadecimal to Binary}

The four-bit mapping between binary and hex makes this
task as straight forward as using a look-up table to 
translate each \gls{hit} (Hex digIT) it to its unique 
four-bit pattern.

Perform this task either by memorizing each of the 16 patterns 
or by converting each hit to decimal first and then converting
each four-bit binary value to decimal using the place-value summing 
method discussed in \autoref{section:bindec}.

For example:

\begin{verbatim}
Hex:                     7          C
Decimal Sum:       4+2+1=7  8+4    =12
Binary:          0 1 1 1    1 1 0 0
\end{verbatim}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{From Decimal to Binary}

To convert arbitrary decimal numbers to binary, extend the list 
of binary place values until it exceeds the value of the decimal 
number being converted.  Then make successive subtractions of each 
of the place values that would yield a non-negative result.

For example, to convert $1234_{10}$ to binary:


\begin{verbatim}
Base-2 place values: 2048-1024-512-256-128-64-32-16-8-4-2-1

   0          2048      (too big)
   1   1234 - 1024 = 210
   0          512       (too big)
   0          256       (too big)
   1    210 - 128  = 82
   1     82 - 64   = 18
   0          32        (too big)
   1     18 - 16   = 2
   0          8         (too big)
   0          4         (too big)
   1      2 - 2    = 0
   0          1         (too big)
\end{verbatim}

The answer using this notation is listed vertically
in the left column with the \acrshort{msb} on the top and 
the \acrshort{lsb} on the bottom line: $010011010010_2$.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{From Decimal to Hex}

Conversion from decimal to hex can be done by using the place
values for base-16 and the same math as from decimal to binary
or by first converting the decimal value to binary and then
from binary to hex by using the methods discussed above.

Because binary and hex are so closely related, performing
a conversion by way of binary is straight forward.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Addition of Binary Numbers}

The addition of binary numbers can be performed long-hand the
same way decimal addition is taught in grade school.  In fact binary
addition is easier since it only involves adding 0 or 1.

The first thing to note that in any number base $0+0=0$, $0+1=1$, and 
$1+0=1$.  Since there is no ``two'' in binary (just like there is 
no ``ten'' decimal) adding $1+1$ results in a zero with a carry as
in: $1+1=10_2$ and in: $1+1+1=11_2$.  Using these five sums, any two
binary integers can be added.

\index{Full Adder}%
This truth table shows what is called a {\em full adder}.
A full adder is a function that can add three input bits 
(the two addends and a carry value from a ``prior column'')
and produce the sum and carry output values.\footnote{
Note that the sum could be expressed in Boolean Algebra as:
$sum = ci \oplus{} a \oplus{} b$}

\begin{center}
\begin{tabular}{|ccc|cc|}
\hline
%\multicolumn{3}{c}{input} & \multicolumn{2}{c}{output}\\
$ci$ & $a$ & $b$ & $co$ & $sum$\\
\hline
 0 & 0 & 0 &   0 & 0 \\
 0 & 0 & 1 &   0 & 1 \\
 0 & 1 & 0 &   0 & 1 \\
 0 & 1 & 1 &   1 & 0 \\
 1 & 0 & 0 &   0 & 1 \\
 1 & 0 & 1 &   1 & 0 \\
 1 & 1 & 0 &   1 & 0 \\
 1 & 1 & 1 &   1 & 1 \\
\hline
\end{tabular}
\end{center}

Adding two unsigned binary numbers using 16 full adders:

\begin{verbatim}
        111111  1111  <== carries
     0110101111001111 <== addend
   + 0000011101100011 <== addend
   ------------------
     0111001100110010 <== sum
\end{verbatim}

Note that the carry ``into'' the LSB is zero.



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Signed Numbers}

There are multiple methods used to represent signed binary integers.
The method used by most modern computers is called {\em two's complement}.

A two's complement number is encoded in such a manner as to simplify
the hardware used to add, subtract and compare integers.  

A simple method of thinking about two's complement numbers is to
negate the place value of the \acrshort{msb}.  For example, the 
number one is represented the same as discussed before:

\begin{verbatim}
Base-2 place values:  -128 64 32 16  8  4  2  1
Binary:                  0  0  0  0  0  0  0  1
\end{verbatim}

The \acrshort{msb} of any negative number in this format will always
be 1.  For example the value $-1_{10}$ is:

\begin{verbatim}
Base-2 place values:  -128 64 32 16  8  4  2  1
Binary:                  1  1  1  1  1  1  1  1
\end{verbatim}

\ldots because: $-128+64+32+16+8+4+2+1=-1$.

This format has the virtue of allowing the same addition logic discussed above to be 
used to calculate the sums of signed numbers as unsigned numbers.

Calculating the signed addition: $4+5 = 9$

\begin{verbatim}
       1    <== carries
     000100 <== 4 = 0 + 0 + 0 + 4 + 0 + 0
    +000101 <== 5 = 0 + 0 + 0 + 4 + 0 + 1
    -------
     001001 <== 9 = 0 + 0 + 8 + 0 + 0 + 1
\end{verbatim}

Calculating the signed addition: $-4+ -5 = -9$

\begin{verbatim}
    1 11     <== carries
      111100 <== -4 = -32 + 16 + 8 + 4 + 0 + 0
     +111011 <== -5 = -32 + 16 + 8 + 0 + 2 + 1
   ---------
    1 110111 <== -9 (with a truncation) = -32 + 16 + 4 + 2 + 1 = -9
\end{verbatim}


Calculating the signed addition: $-1+1=0$

\begin{verbatim}
   -128 64 32 16  8  4  2  1 <== place value
   1  1  1  1  1  1  1  1    <== carries
      1  1  1  1  1  1  1  1 <== addend (-1)
    + 0  0  0  0  0  0  0  1 <== addend (1)
      ----------------------
   1  0  0  0  0  0  0  0  0 <== sum (0 with a truncation)
\end{verbatim}

{\em In order for this to work, the carry out of the sum of the MSBs {\bfseries must} be discarded.}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Converting between Positive and Negative}

Changing the sign on two's complement numbers can be described as
inverting all of the bits (which is also known as the {\em one's complement})
and then add one.

For example, negating the number four:

\begin{minipage}{\textwidth}
\begin{verbatim}
   -128 64 32 16  8  4  2  1
      0  0  0  0  0  1  0  0 <== 4

                     1  1    <== carries
      1  1  1  1  1  0  1  1 <== one's complement of 4
    + 0  0  0  0  0  0  0  1 <== plus 1
      ----------------------
      1  1  1  1  1  1  0  0 <== -4
\end{verbatim}
\end{minipage}

This can be verified by adding 5 to the result and observe that
the sum is 1:

\begin{verbatim}
   -128 64 32 16  8  4  2  1
  1   1  1  1  1  1          <== carries
      1  1  1  1  1  1  0  0 <== -4
    + 0  0  0  0  0  1  0  1 <== 5
      ----------------------
  1   0  0  0  0  0  0  0  1 <== 1 (with a truncation)
\end{verbatim}

Note that the changing of the sign using this method is symmetric
in that it is identical when converting from negative to positive
and when converting from positive to negative: {\em flip the bits and
add 1.}

For example, changing the value -4 to 4 to illustrate the
reverse of the conversion above:

\begin{verbatim}
   -128 64 32 16  8  4  2  1
      1  1  1  1  1  1  0  0 <== -4

                     1  1    <== carries
      0  0  0  0  0  0  1  1 <== one's complement of -4
    + 0  0  0  0  0  0  0  1 <== plus 1
      ----------------------
      0  0  0  0  0  1  0  0 <== 4
\end{verbatim}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Subtraction of Binary Numbers}


Subtraction%
\enote{This section needs more examples of subtracting 
signed an unsigned numbers and a discussion on how 
signedness is not relevant until the results are interpreted. 
For example adding $-4+ -8=-12$ using two 8-bit numbers 
is the same as adding $252+248=500$ and truncating the result 
to 244.}
of binary numbers is performed by first negating
the subtrahend and then adding the two numbers.  Due to the
nature of two's complement numbers this method will work for both 
signed and unsigned numbers!

Observation: Since we always have a carry-in of zero into the LSB when
adding, we can take advantage of that fact by (ab)using that carry input
to perform that adding the extra 1 to the subtrahend as part of
changing its sign in the examples below. 

An example showing the subtraction of two {\em signed} binary numbers: $-4-8 = -12$

\begin{verbatim}
   -128 64 32 16  8  4  2  1
      1  1  1  1  1  1  0  0 <== -4  (minuend)
    - 0  0  0  0  1  0  0  0 <== 8   (subtrahend)
    ------------------------


  1   1  1  1  1  1  1  1  1 <== carries
      1  1  1  1  1  1  0  0 <== -4
    + 1  1  1  1  0  1  1  1 <== one's complement of 8
    ------------------------
  1   1  1  1  1  0  1  0  0 <== -12
\end{verbatim}


%An example showing the subtraction of two {\em unsigned} binary numbers: $252+248=500$
%
%\begin{verbatim}
%    128 64 32 16  8  4  2  1
%
%  1   1  1  1  1             <== carries
%      1  1  1  1  1  1  0  0 <== 252
%    + 1  1  1  1  1  0  0  0 <== 248
%      ----------------------
%  1   1  1  1  1  0  1  0  0 < == 500 (if we do NOT truncate the MSB)
%\end{verbatim}
%
%An example showing the subtraction of two {\em unsigned} binary numbers: $252+248=500$



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Truncation}
\index{truncation}
\index{overflow}
\index{carry}

Discarding the carry bit that can be generated from the MSB is called {\em truncation}.

So far we have been ignoring the carries that can come from the MSBs when adding and subtracting.  
We have also been ignoring the potential impact of a carry causing a signed number to change 
its sign in an unexpected way.

In the examples above, truncating the results either had 1) no impact on the calculated sums
or 2) was absolutely necessary to correct the sum in cases such as: $-4 + 5$.

For example, note what happens when we try to subtract 1 from the most 
negative value that we can represent in a 4 bit two's complement number:

\begin{verbatim}
     -8  4  2  1
      1  0  0  0 <== -8  (minuend)
    - 0  0  0  1 <==  1  (subtrahend)
    ------------


   1           1 <== carries
      1  0  0  0 <== -8
    + 1  1  1  0 <== one's complement of 1
      ----------
   1  0  1  1  1 <== this SHOULD be -9 but with truncation it is 7 
\end{verbatim}

The problem with this example is that we can not represent $-9_{10}$ using a 4-bit 
two's complement number.  

Granted, if we would have used 5 bit numbers, then the ``answer'' would have fit OK.
But the same problem would return when trying to calculate $-16 - 1$. 
So simply ``making more room'' does not solve this problem.

%However, as calculating $-1+1=0$ has demonmstrated above, it was necessary for that
%case to discard the carry out of the MSB to get the correct result.

%In the case of calculating $-1+1=0$ the addends and result all fit into same-sized
%(8-bit) values. When calculating $-8-1=-9$ the addends each can fit into 4-bit
%two's complement numbers but the result would require a 5-bit number.

This is not just a problem when subtracting, nor is it just a problem with
signed numbers.

The same situation can happen {\em unsigned} numbers. 
For example:

\begin{verbatim}
      8  4  2  1
  1   1  1  0  0 <== carries
      1  1  1  0 <== 14  (addend)
    + 0  0  1  1 <==  3  (addend)
    ------------
  1   0  0  0  1 <== this SHOULD be 17 but with truncation it is 1
\end{verbatim}


How to handle such a truncation depends on whether the {\em original} values 
being added are signed or unsigned.

The RV ISA refers to the discarding the carry out of the MSB after an 
add (or subtract) of two {\em unsigned} numbers as an {\em unsigned overflow}%
\footnote{Most microprocessors refer to {\em unsigned overflow} simply as a 
{\em carry} condition.}
and the situation where carries create an incorrect sign in the
result of adding (or subtracting) two {\em signed} numbers as a
{\em signed overflow}.~\cite[p.~13]{rvismv1v22:2017}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Unsigned Overflow}
\index{overflow!unsigned}

When adding {\em unsigned} numbers, an overflow only occurs when there 
is a carry out of the MSB resulting in a sum that is truncated to fit 
into the number of bits allocated to contain the result.

\autoref{sum:240+17} illustrates an unsigned overflow during addition:

\begin{figure}[H]
\centering
\begin{BVerbatim}
   1  1 1 1 0 0 0 0 0 <== carries
      1 1 1 1 0 0 0 0 <== 240
 +    0 0 0 1 0 0 0 1 <== 17
---------------------
   1  0 0 0 0 0 0 0 1 <== sum = 1
\end{BVerbatim}
%{\captionof{figure}{$240+16=0$ (overflow)}\label{sum:240+17}}
\caption{$240+17=1$ (overflow)}
\label{sum:240+17}
\end{figure}

Some times an overflow like this is referred to as a {\em wrap around}
because of the way that successive additions will result in a value that
increases until it {\em wraps} back {\em around} to zero and then 
returns to increasing in value until it, again, wraps around again.

\begin{tcolorbox}
When adding, {\em unsigned overflow} occurs when ever there is a carry
{\em out of} the most significant bit.
\end{tcolorbox}



When subtracting {\em unsigned} numbers, an overflow only occurs when the
subtrahend is greater than the minuend (because in those cases the 
difference would be negative but no negative values 
can be represented with an unsigned binary number.)

\autoref{sum:3-4} illustrates an unsigned overflow during subtraction:

\begin{figure}[H]
\centering
\begin{BVerbatim}
     0 0 0 0 0 0 1 1 <== 3 (minuend)
   - 0 0 0 0 0 1 0 0 <== 4 (subtrahend)
   -----------------


  0  0 0 0 0 0 1 1 1 <== carries
     0 0 0 0 0 0 1 1 <== 3
   + 1 1 1 1 1 0 1 1 <== one's complement of 4
   -----------------
     1 1 1 1 1 1 1 1 <== 255 (overflow)
\end{BVerbatim}
\caption{$3-4=255$ (overflow)}
\label{sum:3-4}
\end{figure}

\begin{tcolorbox}
When subtracting, {\em unsigned overflow} occurs when ever there is {\em not} a carry
{\em out of} the most significant bit (IFF the carry-in on the LSB is used to add the
extra 1 to the subtrahend when changing its sign.)
\end{tcolorbox}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Signed Overflow}
\index{overflow!signed}

When adding {\em signed} numbers, an overflow only occurs when the two 
addends are positive and sum is negative or the addends are both negative 
and the sum is positive.  

When subtracting {\em signed} numbers, an overflow only occurs when the
minuend is positive and the subtrahend is negative and difference is negative
or when the minuend is negative and the subtrahend is positive and the 
difference is positive.%
\footnote{I had to look it up to remember which were which 
too\ldots\ it is: minuend - subtrahend = difference.\cite{subtrahend}}

Consider the results of the addition of two {\em signed} numbers
while looking more closely at the carry values.

\begin{figure}[H]
\centering
\begin{BVerbatim}
   0 1 0 0 0 0 0 0 0 <== carries
     0 1 0 0 0 0 0 0 <== 64
 +   0 1 0 0 0 0 0 0 <== 64
---------------------
     1 0 0 0 0 0 0 0 <== sum = -128
\end{BVerbatim}
\caption{$64+64 = -128$ (overflow)}
\label{sum:64+64}
\end{figure}



\autoref{sum:64+64} is an example of {\em signed overflow}.  As shown, the problem is 
that the sum of two positive numbers has resulted in an obviously incorrect
negative result due to a carry flowing into the sign-bit in the MSB.

Granted, if the same values were added using values larger than 8-bits 
then the sum would have been correct.  However, these examples assume that 
all the operations are performed on (and results stored into) 8-bit values.  
Given any finite-number of bits, there are values that could be added such that
an overflow occurs.

\index{truncation}
\autoref{sum:-128+-128} shows another overflow situation that is caused 
by the fact that there is nowhere for the carry out of the sign-bit to go.  
We say that this result has been {\em truncated}.

\begin{figure}[H]
\centering
\begin{BVerbatim}
   1 0 0 0 0 0 0 0 0 <== carries
     1 0 0 0 0 0 0 0 <== -128
 +   1 0 0 0 0 0 0 0 <== -128
---------------------
     0 0 0 0 0 0 0 0 <== sum = 0 
\end{BVerbatim}
\caption{$-128+-128 = 0$ (overflow)}
\label{sum:-128+-128}
\end{figure}

Truncation is not necessarily a problem.  Consider the truncations in
figures \ref{sum:-3+-5} and \ref{sum:-2+10}.  
\autoref{sum:-2+10} demonstrates the importance of discarding 
the carry from the sum of the MSBs of signed numbers when addends
do not have the same sign.

\begin{figure}[H]
\centering
\begin{BVerbatim}
   1 1 1 1 1 1 1 1 0 <== carries
     1 1 1 1 1 1 0 1 <== -3
 +   1 1 1 1 1 0 1 1 <== -5
---------------------
     1 1 1 1 1 0 0 0  <== sum = -8
\end{BVerbatim}
\captionof{figure}{$-3+-5 = -8$}
\label{sum:-3+-5}
\end{figure}

\begin{figure}[H]
\centering
\begin{BVerbatim}
   1 1 1 1 1 1 1 0 0 <== carries
     1 1 1 1 1 1 1 0 <== -2
 +   0 0 0 0 1 0 1 0 <== 10
---------------------
     0 0 0 0 1 0 0 0 <== sum = 8
\end{BVerbatim}
\captionof{figure}{$-2+10 = 8$}
\label{sum:-2+10}
\end{figure}

Just like an unsigned number can wrap around as a result of
successive additions, a signed number can so the same thing.  The
only difference is that signed numbers won't wrap from the maximum 
value back to zero, instead it will wrap from the most positive to 
the most negative value as shown in \autoref{sum:127+1}.
 
\begin{figure}[H]
\centering
\begin{BVerbatim}
   0 1 1 1 1 1 1 1 0 <== carries
     0 1 1 1 1 1 1 1 <== 127
 +   0 0 0 0 0 0 0 1 <== 1
---------------------
     1 0 0 0 0 0 0 0 <== sum = -128
\end{BVerbatim}
\captionof{figure}{$127+1 = -128$}
\label{sum:127+1}
\end{figure}

\begin{tcolorbox}
Formally, a {\em signed overflow} occurs when ever the carry
{\em into} the most significant bit is not the same as the 
carry {\em out of} the most significant bit.  
\end{tcolorbox}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Sign and Zero Extension}

\index{sign extension}
\label{SignExtension}
Due to the nature of the two's complement encoding scheme, the following 
numbers all represent the same value:
\begin{verbatim}
                                   1111 <== -1
                               11111111 <== -1
                   11111111111111111111 <== -1
           1111111111111111111111111111 <== -1
\end{verbatim}
As do these:
\begin{verbatim}
                                  01100 <== 12
                             0000001100 <== 12
    00000000000000000000000000000001100 <== 12
\end{verbatim}

The lengthening of these numbers by replicating the digits on the left
is what is called {\em sign extension}.  

\begin{tcolorbox}
Any signed number can have any quantity of additional MSBs added to it,
provided that they repeat the value of the sign bit.
\end{tcolorbox}

\autoref{Figure:SignExtendNegative} illustrates extending the negative sign
bit to the left by replicating it.
A negative number will have its \acrshort{msb} (bit 19 in this example)
set to 1.   Extending this value to the left will set all the new bits
to the left of it to 1 as well.

\begin{figure}[ht]
\centering
\DrawBitBoxSignExtendedPicture{32}{10100000000000000010}
\captionof{figure}{Sign-extending a negative integer from 20 bits to 32 bits.}
\label{Figure:SignExtendNegative}
\end{figure}

\autoref{Figure:SignExtendPositive} illustrates extending the sign bit of a
positive number to the left by replicating it.
A positive number will have its \acrshort{msb} set to 0.  Extending this
value to the left will set all the new bits to the left of it to 0 as well.

\begin{figure}[ht]
\centering
\DrawBitBoxSignExtendedPicture{32}{01000000000000000010}
\captionof{figure}{Sign-extending a positive integer from 20 bits to 32 bits.}
\label{Figure:SignExtendPositive}
\end{figure}


\label{ZeroExtension}
In a similar vein, any unsigned number also may have any quantity of 
additional MSBs added to it provided that they are all zero.  This is
called {\em zero extension}.  For example,
the following all represent the same value:
\begin{verbatim}
                                   1111 <== 15
                                  01111 <== 15
          00000000000000000000000001111 <== 15
\end{verbatim}

\begin{tcolorbox}
Any {\em unsigned} number may be {\em zero extended} to any size.
\end{tcolorbox}

\enote{Remove the sign-bit boxes from this figure?}%
\autoref{Figure:ZeroExtend} illustrates zero-extending a 20-bit number to the
left to form a 32-bit number.

\begin{figure}[ht]
\centering
\DrawBitBoxZeroExtendedPicture{32}{10000000000000000010}
\captionof{figure}{Zero-extending an unsigned integer from 20 bits to 32 bits.}
\label{Figure:ZeroExtend}
\end{figure}

%Sign- and zero-extending binary numbers are common operations used to 
%fit a byte or halfword into a fullword.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Shifting}
\label{shifting}

We were all taught how to multiply and divide decimal numbers by ten
by moving (or {\em shifting}) the decimal point to the right or left 
respectively.  Doing the same in any other base has the same effect 
in that it will multiply or divide the number by its base.

\enote{Include decimal values in the shift diagrams.}%
Multiplication and division are only two reasons for shifting.  There
can be other occasions where doing so is useful.

As implemented by a CPU, shifting applies to the value in a register
and the results stored back into a register of finite size.  Therefore
a shift result will always be truncated to fit into a register.

\enote{Add some examples showing the rounding of positive and negative values.}%
Note that when dealing with numeric values, any truncation performed 
during a right-shift will manifest itself as rounding toward zero.

\subsection{Logical Shifting}

Shifting {\em logically} to the left or right is a matter of re-aligning
the bits in a register and truncating the result.

\enote{Redraw these with arrows tracking the shifted bits and the truncated values}%
To shift left two positions:

\DrawBitBoxUnsignedPicture{10111000000000000010}\\
\DrawBitBoxUnsignedPicture{11100000000000001000}

To shift right one position:

\DrawBitBoxUnsignedPicture{10111000000000000010}\\
\DrawBitBoxUnsignedPicture{01011100000000000001}

\begin{tcolorbox}
Note that the vacated bit positions are always filled with zero.
\end{tcolorbox}

\subsection{Arithmetic Shifting}

Some times it is desirable to retain the value of the sign bit when
shifting.  The RISC-V ISA provides an arithmetic right shift 
instruction for this purpose (there is no arithmetic left shift for 
this ISA.)

\begin{tcolorbox}
When shifting to the right {\em arithmetically}, vacated bit positions are
filled by replicating the value of the sign bit. 
\end{tcolorbox}

An arithmetic right shift of a negative number by 4 bit positions:

\DrawBitBoxSignedPicture{10111000000000000010}\\
\DrawBitBoxSignedPicture{11111011100000000000}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Main Memory Storage}

As mentioned in \autoref{VolatileStorage}, the main memory in a RISC-V 
system is byte-addressable.  For that reason we will visualize it by 
displaying ranges of bytes displayed in hex and in \gls{ascii}.  As will 
become obvious, the ASCII part makes it easier to find text messages.%
\footnote{Most of the memory dumps in this text are generated by \gls{rvddt}
and are shown on a per-byte basis without any attempt to reorder their
values. Some other applications used to dump memory do not dump the bytes
in address-order!  It is important to know how your software tools operate
when using them to dump the contents of memory and/or files.}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Memory Dump}

\listingRef{rvddt_memdump.out} shows a {\em memory dump} from the rvddt
`d' command requesting a dump starting at address \hex{00002600}
for the default quantity (\hex{100}) of bytes.

\listing{rvddt_memdump.out}{{\tt rvddt} memory dump}

\begin{itemize}
\item [$\ell$ 1] The rvddt prompt showing the dump command.
\item [$\ell$ 2] From left to right. the dump is presented as the address 
	of the first byte (\hex{00002600}) followed by a colon, the value
	of the byte at address \hex{00002600} expressed in hex, the next byte
	(at address \hex{00002601}) and so on for 16 bytes. There is a 
	double-space
	between the 7th and 8th bytes to help provide a visual reference for
	the center to make it easy to locate bytes on the right end.  For 
	example, the byte at address \hex{0000260c} is four bytes to the 
	right of byte number eight (at the gap) and contains \hex{13}.
	To the right of the 16-bytes is an asterisk-enclosed set of 16 columns
	showing the ASCII characters that each byte represents.  If a byte
	has a value that corresponds to a printable character code, the character
	will be displayed.  For any illegal/un-displayable byte values, a dot 
	is shown to make it easier to count the columns.
\item [$\ell$ 3-17] More of the same as seen on $\ell$ 2.  The address
	at the left can be seen to advance by $16_{10}$ (or $10_{16}$) 
	for each line shown.
\end{itemize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Endianness}

The choice of which end of a multi-byte value is to be stored at the
lowest byte address is referred to as {\em endianness.}  For example,
if a CPU were to store a \gls{halfword} into memory, should the byte 
containing the \acrfull{msb} (the {\em big} end) go first or does 
the byte with the \acrfull{lsb} (the {\em little} end) go first? 

On the one hand the choice is arbitrary.  On the other hand, it is 
possible that the choice could impact the performance of the system.%
\footnote{See\cite{IEN137} for some history of the big/little-endian ``controversy.''}

IBM mainframe CPUs and the 68000 family store their bytes in big-endian 
order.  While the Intel Pentium and most embedded processors use
little-endian order.  
Some CPUs are even {\em bi-endian} in that they have instructions that
can change their order on the fly. 

The RISC-V system uses the little-endian byte order.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Big-Endian}
\label{BigEndian}
\index{big-endian}

Using the contents of \listingRef{rvddt_memdump.out}, a \gls{bigendian}
CPU would interpret the contents as follows:

\begin{itemize}
\item The 8-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x@{\color{red}\verb@76@}.
\item The 8-bit value read from address \hex{00002659} would be \hex{61}.
\item The 8-bit value read from address \hex{0000265a} would be \hex{6c}.
\item The 8-bit value read from address \hex{0000265b} would be \hex{3d}.
\item The 16-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x@{\color{red}\verb@76@}\verb@61@.
\item The 16-bit value read from address \hex{0000265a} would be \hex{6c3d}.
\item The 32-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x@{\color{red}\verb@76@}\verb@616c3d@.
\end{itemize}

Notice that in a big-endian system, the {\em\gls{place-value}s} of the bits 
comprising the \verb@0x@{\color{red}\verb@76@}
(located at memory address \colorbox{c_lightblue}{\hex{00002658}}) are 
{\em different} depending on the number of bytes representing the value that is being read.

For example, when a 16-bit value is read from \colorbox{c_lightblue}{\hex{00002658}}
then the {\color{red}\verb@76@} represents 
the binary place values: $2^{15}$ to $2^8$.
When a 32-bit value is read then the {\color{red}\verb@76@} represents
the binary place values: $2^{31}$ to $2^{24}$.  
In other words the value read from the first memory location (with the 
lowest address), of the plurality of addresses containing the complete 
value being read, is always placed on the {\em left end}, into the 
Most Significant Bits.  One might dare say that the {\color{red}\verb@76@} 
is placed at the end with the {\em big} place values.

More examples:

\begin{itemize}
\item An 8-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x@{\color{red}\verb@23@}.
\item An 8-bit value read from address \hex{00002625} would be \hex{24}.
\item An 8-bit value read from address \hex{00002626} would be \hex{81}.
\item An 8-bit value read from address \hex{00002627} would be \hex{00}.
\item A 16-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x@{\color{red}\verb@23@}\verb@24@.
\item A 16-bit value read from address \hex{00002626} would be \hex{8100}.
\item A 32-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x@{\color{red}\verb@23@}\verb@248100@.
\end{itemize}

Again, notice that the byte from memory address \colorbox{c_lightgreen}{\hex{00002624}}, 
regardless of the {\em number} of bytes comprising the complete value being 
fetched, will always appear on the left/{\em big} end of the final value.


\begin{tcolorbox}
On a big-endian system, the bytes in the dump are in the same order as 
they would be used by the CPU if it were to read them as a multi-byte 
value.
\end{tcolorbox}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Little-Endian}
\label{LittleEndian}
\index{little-endian}

Using the contents of \listingRef{rvddt_memdump.out}, a \gls{littleendian}
CPU would interpret the contents as follows:

\begin{itemize}
\item An 8-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x@{\color{red}\verb@76@}.
\item An 8-bit value read from address \hex{00002659} would be \hex{61}.
\item An 8-bit value read from address \hex{0000265a} would be \hex{6c}.
\item An 8-bit value read from address \hex{0000265b} would be \hex{3d}.
\item A 16-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x61@{\color{red}\verb@76@}.
\item A 16-bit value read from address \hex{0000265a} would be \hex{3d6c}.
\item A 32-bit value read from address \colorbox{c_lightblue}{\hex{00002658}} would be \verb@0x3d6c61@{\color{red}\verb@76@}.
\end{itemize}

Notice that in a little-endian system, the {\em\gls{place-value}s} of the bits 
comprising the \verb@0x@{\color{red}\verb@76@}
(located at memory address \colorbox{c_lightblue}{\hex{00002658}})
are the {\em same} regardless of the the number of bytes representing the value that is being read.

Unlike the behavior of a big-endian machine, when little-endian machine 
reads a 16-bit value from \colorbox{c_lightblue}{\hex{00002658}} the 
{\color{red}\verb@76@} represents the binary place values from $2^{7}$ to $2^0$.
When a 32-bit value is read then the {\color{red}\verb@76@} (still) represents
the binary place values from $2^{7}$ to $2^{0}$.  
In other words the value read from the first memory location (with the 
lowest address), of the plurality of addresses containing the complete 
value being read, is always placed on the {\em right end}, into the 
Least Significant Bits.  One might say that the {\color{red}\verb@76@} 
is placed at the end with the {\em little} place values.

Also notice that it is the {\em bytes} are what are ``reversed'' in a little-endian
system ({\em not} the hex digits.)

More examples:

\begin{itemize}
\item The 8-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x@{\color{red}\verb@23@}.
\item The 8-bit value read from address \hex{00002625} would be \hex{24}.
\item The 8-bit value read from address \hex{00002626} would be \hex{81}.
\item The 8-bit value read from address \hex{00002627} would be \hex{00}.
\item The 16-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x24@{\color{red}\verb@23@}.
\item The 16-bit value read from address \hex{00002626} would be \hex{0081}.
\item The 32-bit value read from address \colorbox{c_lightgreen}{\hex{00002624}} would be \verb@0x008124@{\color{red}\verb@23@}.
\end{itemize}

As above, notice that the byte from memory address \colorbox{c_lightgreen}{\hex{00002624}}, 
regardless of the {\em number} of bytes comprising the complete value being 
fetched, will always appear on the right/{\em little} end of the final value.



\begin{tcolorbox}
On a little-endian system, the bytes in the dump are in reverse order as 
they would be used by the CPU if it were to read them as a multi-byte value.
\end{tcolorbox}


In the RISC-V ISA it is noted that 
\begin{quote}
A minor point is that we have also found 
little-endian memory systems to be more natural for hardware 
designers. However, certain application areas, such as IP networking, operate
on big-endian data structures, and so we leave open the possibility of 
non-standard big-endian or bi-endian systems.''\cite[p.~6]{rvismv1v22:2017}
\end{quote}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Arrays and Character Strings}

While Endianness defines how single values are stored in memory,
the {\em array} defines how multiple values are stored.

An array is a data structure comprised of an ordered set of elements.
This text will limit its definition of array to a plurality of
elements that are all of the same type.  Where type
refers to the size (number of bytes) and representation (signed,
unsigned,\ldots) of each element.

In an array, the elements are stored adjacent to one another such that the
address $e$ of any element $x[n]$ is:

\begin{equation}
e = a + n * s
\end{equation}

Where $x$ is the name of the array, $n$ is the element number of interest, 
$e$ is the address of interest, $a$ is the address of the first element in 
the array and $s$ is the size (in bytes) of each element.

Given an array $x$ containing $m$ elements, $x[0]$ is the first element of 
the array and $x[m-1]$ is the last element of the array.%
\footnote{Some computing languages (C, C++, Java, C\#, Python, Perl,\ldots) 
define an array such that the first element is indexed as $x[0]$.  
While others (FORTRAN, MATLAB) define the first element of an 
array to be $x[1]$.}

Using this definition, and the memory dump shown in 
\listingRef{rvddt_memdump.out}, and the knowledge that 
we are using a little-endian machine and given that
$a = $ \hex{00002656} and $s = 2$, the values of the first 8 elements 
of array $x$ are:

\begin{itemize}
\item $x[0]$ is \hex{0000} and is stored at \hex{00002656}.
\item $x[1]$ is \hex{6176} and is stored at \hex{00002658}.
\item $x[2]$ is \hex{3d6c} and is stored at \hex{0000265a}.
\item $x[3]$ is \hex{0000} and is stored at \hex{0000265c}.
\item $x[4]$ is \hex{0000} and is stored at \hex{00002660}.
\item $x[5]$ is \hex{0000} and is stored at \hex{00002662}.
\item $x[6]$ is \hex{8480} and is stored at \hex{00002664}.
\item $x[7]$ is \hex{412e} and is stored at \hex{00002666}.
\end{itemize}

\begin{tcolorbox}
In general, there is no fixed rule nor notion as to how many 
elements an array has.  It is up to the programmer to ensure that
the starting address and the number of elements in any given array
(its size) are used properly so that data bytes outside an array
are not accidentally used as elements.
\end{tcolorbox}

There is, however, a common convention used for an array of 
characters that is used to hold a text message 
(called a {\em character string} or just {\em string}).

When an array is used to hold a string the element past the last
character in the string is set to zero.  This is because 1) zero 
is not a valid printable ASCII character and 2) it simplifies
software in that knowing no more than the starting address of a
string is all that is needed to processes it.  Without this zero
{\em sentinel} value (called a {\em null} terminator), some knowledge
of the number of characters in the string would have to otherwise 
be conveyed to any code needing to consume or process the string.

In \listingRef{rvddt_memdump.out}, the 5-byte long array starting 
at address \hex{00002658} contains a string whose value can be
expressed as either: % \verb@76 61 6c 3d 00@ or \verb@"val="@.

\verb@76 61 6c 3d 00@

or

\verb@"val="@

%\begin{itemize}
%\item \verb@76 61 6c 3d 00@
%\item \verb@"val="@
%\end{itemize}

\index{ASCII}
\index{ASCIIZ}
When the double-quoted text form is used, the GNU assembler used in 
this text differentiates between {\em ascii} and {\em asciiz} strings
such that an {\em ascii} string is {\bf not} null terminated and an
{\em asciiz} string {\bf is} null terminated.  

The value of providing a method to create a string that is not
null terminated is that a program may define a large string by 
concatenating a number of {\em ascii} strings together and following the 
last with a byte of zero to null-terminate it.

It is a common mistake to create a string with a missing
null terminator.  The result of printing such a string is that
the string will be printed as well as whatever random data bytes in 
memory follow it until a byte whose value is zero is encountered 
by chance.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Context is Important!}

Data values can be interpreted differently depending on the context in 
which they are used.  Assuming what a set of bytes is used for based on 
their contents can be very misleading!  For example, there is a 0x76 at 
address 0x00002658.  This is a `v' is you use it as an ASCII 
(see~\autoref{chapter:ascii}) character, a $118_{10}$ if it is an integer 
value and TRUE if it is a conditional.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Alignment}

\enote{Include the obligatory diagram showing the overlapping data types 
when they are all aligned.}%
With respect to memory and storage, {\em \gls{alignment}} refers to the 
{\em location} of a data element when the address that it is stored is 
a precise multiple of a power-of-2. 

The primary alignments of concern are typically 2 (a halfword), 
4 (a fullword), 8 (a double word) and 16 (a quad-word) bytes.

For example, any data element that is aligned to 2-byte boundary
must have an (hex) address that ends in any of: 0, 2, 4, 6, 8, A, 
C or E.
Any 4-byte aligned element must be located at an address ending
in 0, 4, 8 or C.  An 8-byte aligned element at an address ending
with 0 or 8, and 16-byte aligned elements must be located at
addresses ending in zero.

Such alignments are important when exchanging data between the CPU 
and memory because the hardware implementations are optimized to
transfer aligned data.  Therefore, aligning data used by any program
will reap the benefit of running faster.%
\footnote{Alignment of data, while important for efficient performance, 
is not mandatory for RISC-V systems.\cite[p.~19]{rvismv1v22:2017}}

An element of data is considered to be {\em aligned to its natural size}
when its address is an exact multiple of the number of bytes used to 
represent the data.  Note that the ISA we are concerned with {\em only}
operates on elements that have sizes that are powers of two.

For example, a 32-bit integer consumes one full word.  If the four bytes
are stored in main memory at an address than is a multiple of 4 then
the integer is considered to naturally aligned.  

The same would apply to 16-bit, 64-bit, 128-bit and other such values 
as they fit into 2, 8 and 16 byte elements respectively.

Some CPUs can deliver four (or more) bytes at the same time while others 
might only be capable of delivering one or two bytes at a time.  Such 
differences in hardware typically impact the cost and performance of a 
system.%
\footnote{The design and implementation
choices that determine how any given system operates are part of what is
called a system's {\em organization} and is beyond the scope of this text.
See~\cite{codriscv:2017} for more information on computer organization.}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Instruction Alignment}

The RISC-V ISA requires that all instructions be aligned to their
natural boundaries.

Every possible instruction that an RV32I CPU can execute contains
exactly 32 bits.  Therefore they are always stored on a full word
boundary.  Any {\em unaligned} instruction is {\em illegal}.%
\footnote{This rule is relaxed by the C extension to allow an 
instruction to start at any even address.\cite[p.~5]{rvismv1v22:2017}}

An attempt to fetch an instruction from an unaligned address
will result in an error referred to as an alignment {\em \gls{exception}}.
This and other exceptions cause the CPU to stop executing the
current instruction and start executing a different set of instructions
that are prepared to handle the problem.  Often an exception is
handled by completely stopping the program in a way that is commonly
referred to as a system or application {\em crash}.


================================================
FILE: book/binary/rvddt_memdump.out
================================================
ddt> d 0x00002600
 00002600: 93 05 00 00 13 06 00 00  93 06 00 00 13 07 00 00 *................*
 00002610: 93 07 00 00 93 08 d0 05  73 00 00 00 63 54 05 02 *........s...cT..*
 00002620: 13 01 01 ff 23 24 81 00  13 04 05 00 23 26 11 00 *....#$......#&..*
 00002630: 33 04 80 40 97 00 00 00  e7 80 40 01 23 20 85 00 *3..@......@.# ..*
 00002640: 6f 00 00 00 6f 00 00 00  b7 87 00 00 03 a5 07 43 *o...o..........C*
 00002650: 67 80 00 00 00 00 00 00  76 61 6c 3d 00 00 00 00 *g.......val=....*
 00002660: 00 00 00 00 80 84 2e 41  1f 85 45 41 80 40 9a 44 *.......A..EA.@.D*
 00002670: 4f 11 f3 c3 6e 8a 67 41  20 1b 00 00 20 1b 00 00 *O...n.gA ... ...*
 00002680: 44 1b 00 00 14 1b 00 00  14 1b 00 00 04 1c 00 00 *D...............*
 00002690: 44 1b 00 00 14 1b 00 00  04 1c 00 00 14 1b 00 00 *D...............*
 000026a0: 44 1b 00 00 10 1b 00 00  10 1b 00 00 10 1b 00 00 *D...............*
 000026b0: 04 1c 00 00 54 1f 00 00  54 1f 00 00 d4 1f 00 00 *....T...T.......*
 000026c0: 4c 1f 00 00 4c 1f 00 00  34 20 00 00 d4 1f 00 00 *L...L...4 ......*
 000026d0: 4c 1f 00 00 34 20 00 00  4c 1f 00 00 d4 1f 00 00 *L...4 ..L.......*
 000026e0: 48 1f 00 00 48 1f 00 00  48 1f 00 00 34 20 00 00 *H...H...H...4 ..*
 000026f0: 00 01 02 02 03 03 03 03  04 04 04 04 04 04 04 04 *................*


================================================
FILE: book/colors.tex
================================================
% These are color styles used in the figures in this book.
\definecolor{c_lightblue}{HTML}{B0E0FF}
\definecolor{c_lightred}{HTML}{FFE0E0}
\definecolor{c_lightyellow}{HTML}{FFE060}
\definecolor{c_lightgreen}{HTML}{C0FFC0}


================================================
FILE: book/copyright/chapter.tex
================================================
\thispagestyle{plain}

Copyright \copyright\ 2018, 2019, 2020 John Winans 

This document is made available under a Creative Commons Attribution 4.0 
International License.  See \autoref{license} for more information.

Download your own copy of this book from github here: 
\url{https://github.com/johnwinans/rvalp}.

This document may contain inaccuracies or errors.  The author provides no 
guarantee regarding the accuracy of this document's contents.  If you 
discover that this document contains errors, please notify the author.

\enote{Need to say something about trademarks for things mentioned in this
text}


ARM\rtm{} is a registered trademark of ARM Limited in the 
EU and other countries.

IBM\rtm{} is a trademarks or registered trademark of International Business Machines 
Corporation in the United States, other countries, or both.

Intel\rtm{} and Pentium\rtm{} are trademarks of Intel Corporation or its subsidiaries 
in the U.S. and/or other countries.


================================================
FILE: book/elements/chapter.tex
================================================
\chapter{The Elements of a Assembly Language Program}
\label{chapter:elements}

\section{Assembly Language Statements}

Introduce the assembly language grammar. 
\begin{itemize}
\item Statement = 1 line of text containing an instruction or directive.
\item Instruction = label, mnemonic, operands, comment.
\item Directive = Used to control the operation of the assembler.
\end{itemize}

\section{Memory Layout}

Is this a good place to introduce the text, data, bss, heap and stack regions?

Or does that belong in a new section/chapter that discusses addressing modes?


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{A Sample Program Source Listing}

A simple program that illustrates how this text presents 
program source code is seen in \listingRef{zero4regs.S}.
This program will place a zero in each of the 4 registers 
named x28, x29, x30 and x31.

\listing{zero4regs.S}{Setting four registers to zero.}

This program listing illustrates a number of things: 
\begin{itemize}
\item Listings are identified by the name of the file within which
	they are stored.  This listing is from a file named: \verb@zero4regs.S@.
\item The assembly language programs discussed in this text will be saved
	in files that end with: \verb@.S@  (Alternately you can use \verb@.sx@ 
	on systems that don't understand the difference between upper and 
	lowercase letters.\footnote{The author of this text prefers to avoid
	using such systems.})
\item A description of the listing's purpose appears under the name of the
	file.  The description of \listingRef{zero4regs.S} is 
	{\em Setting four registers to zero.}
\item The lines of the listing are numbered on the left margin for
	easy reference.
\item An assembly program consists of lines of plain text.
\item The RISC-V ISA does not provide an operation that will simply 
	set a register to a numeric value.  To accomplish our goal this
	program will add zero to zero and place the sum in in each of the
	four registers.
\item The lines that start with a dot `.' (on lines 1, 2 and 3) are 
	called {\em assembler directives} as they tell the assembler itself
	how we want it to translate the following {\em assembly language instructions} 
	into {\em machine language instructions.}  
\item Line 4 shows a {\em label} named {\em \_start}.  The colon
	at the end is the indicator to the assembler that causes it to
	recognize the preceding characters as a label.
\item Lines 5-8 are the four assembly language instructions that
	make up the program.  Each instruction in this program
	consists of four {\em fields}.  (Different instructions can have 
	a different number of fields.)  The fields on line 5 are:

	\begin{itemize}
	\item [addi] The instruction mnemonic.  It indicates the operation 
		that the CPU will perform.
	\item [x28] The {\em destination} register that will receive the 
		sum when the {\em addi} instruction is finished.  The names of
		the 32 registers are expressed as x0 -- x31.
	\item [x0] One of the addends of the sum operation.  (The x0 register
		will always contain the value zero.  It can never be changed.)
	\item [0] The second addend is the number zero.
		\item [\# set \ldots] Any text anywhere in a RISC-V assembly language
	program that starts with the pound-sign is ignored by the assembler.
			They are used to place a {\em comment} in the program to help
	the reader better understand the motive of the programmer.
	\end{itemize}
\end{itemize}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Running a Program With rvddt}
\index{rvddt}

To illustrate what a CPU does when it executes instructions this text
will use the \gls{rvddt} simulator to display shows sequence of events 
and the binary values involved.  This simulator supports the RV32I ISA 
and has a configurable amount of memory.%
\footnote{The {\em rvddt} simulator was written to generate the listings for 
this text.  It is similar to the fancier {\em spike} simulator.  
Given the simplicity of the RV32I ISA, rvddt is less than 1700 lines of C++ 
and was written in one (long) afternoon.}

\listingRef{zero4regs.out} shows the operation of the four 
{\em addi} instructions from \listingRef{zero4regs.S} when it is executed
in trace-mode.

\listing{zero4regs.out}{Running a program with the rvddt simulator}

\begin{itemize}
\item [$\ell$ 1] This listing includes the command-line that shows how the simulator
	was executed to load a file containing the machine instructions (aka
	machine code) from the assembler.
\item [$\ell$ 2] A message from the simulator indicating that it loaded the machine
	code into simulated memory at address 0.
\item [$\ell$ 3] This line shows the prompt from the debugger and the command
	\verb@t4@ that the user entered to request that the simulator trace 
	the execution of four instructions.
\item [$\ell$ 4-8] Prior to executing the first instruction, the state of the
	CPU registers is displayed.  
\item [$\ell$ 4] The values in registers 0, 1, 2, 3, 4, 5, 6 and 7 are printed 
	from left to right in \gls{bigendian}, \gls{hexadecimal} form.  
	The double-space gap in the middle of the line is a reference 
	to make it easier to visually navigate across the line without being
	forced to count the values from the far left when seeking the value 
	of, say, x5.
\item [$\ell$ 5-7] The values of registers 8--31 are printed.
\item [$\ell$ 8] The {\em program counter} (\reg{pc}) register is printed.  
	It contains the address of the instruction that the CPU will execute.  
	After each instruction, the \reg{pc} will either advance four bytes 
	ahead or be set to another value by a branch instruction as discussed above.
\item [$\ell$ 9] A four-byte instruction is fetched from memory at the address
	in the \reg{pc} register, is decoded and printed.  From left to right
	the fields shown on this line are:

	\begin{itemize}

	\item [00000000] The memory address from which the instruction was
		fetched.  This address is displayed in \gls{bigendian},
		\gls{hexadecimal} form.
	\item [00000e13] The machine code of the instruction displayed in 
		\gls{bigendian}, \gls{hexadecimal} form.
	\item [addi] The mnemonic for the machine instruction.
	\item [x28] The \reg{rd} field of the addi instruction.  
	\item [x0] The \reg{rs1} field of the addi instruction that
		holds one of the two addends of the operation.
	\item [0] The \reg{imm} field of the addi instruction that
		holds the second of the two addends of the operation.
	\item [\# \ldots] A simulator-generated comment that explains
		what the instruction is doing.  For this instruction it indicates 
		that \reg{x28} will have the value zero stored into it as a result 
		of performing the addition: $0+0$.
	\end{itemize}

\item [$\ell$ 10-14] These lines are printed as the prelude while tracing the
	second instruction. Lines 7 and 13 show that \reg{x28} has changed
	from \verb@f0f0f0f0@ to \verb@00000000@ as a result of executing the
	first instruction and lines 8 and 14 show that the \reg{pc} has 
	advanced from zero (the location of the first instruction) to 
	four, where the second instruction will be fetched.  None of the
	rest of the registers have changed values.
\item [$\ell$ 15] The second instruction decoded executed and described.  
	This time register \reg{x29} will be assigned a value.
\item [$\ell$ 16-27] The third and fourth instructions are traced.
\item [$\ell$ 28] Tracing has completed. The simulator prints its prompt
	and the user enters the `r' command to see the register state
	after the fourth instruction has completed executing.
\item [$\ell$ 29-33] Following the fourth instruction it can be observed
	that registers \reg{x28}, \reg{x29}, \reg{x30} and \reg{x31} 
	have been set to zero and that the \reg{pc} has advanced from
	zero to four, then eight, then 12 (the hex value for 12 is c)
	and then to 16 (which, in hex, is 10). 
\item [$\ell$ 34] The simulator exit command `x' is entered by the user and
	the terminal displays the shell prompt.

\end{itemize}


================================================
FILE: book/elements/zero4regs.S
================================================
	.text					# put this into the text section
	.align	2				# align to 2^2
	.globl	_start
_start:
	addi    x28, x0, 0		# set register x28 to zero
	addi    x29, x0, 0		# set register x29 to zero
	addi    x30, x0, 0		# set register x30 to zero
	addi    x31, x0, 0		# set register x31 to zero


================================================
FILE: book/elements/zero4regs.out
================================================
[winans@w510 src]$ ./rvddt -f ../examples/load4regs.bin
Loading '../examples/load4regs.bin' to 0x0
ddt> t4
   x0: 00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   x8: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x16: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x24: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   pc: 00000000
00000000: 00000e13  addi    x28, x0, 0    # x28 = 0x00000000 = 0x00000000 + 0x00000000
   x0: 00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   x8: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x16: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x24: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0
   pc: 00000004
00000004: 00000e93  addi    x29, x0, 0    # x29 = 0x00000000 = 0x00000000 + 0x00000000
   x0: 00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   x8: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x16: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x24: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  00000000 00000000 f0f0f0f0 f0f0f0f0
   pc: 00000008
00000008: 00000f13  addi    x30, x0, 0    # x30 = 0x00000000 = 0x00000000 + 0x00000000
   x0: 00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   x8: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x16: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x24: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  00000000 00000000 00000000 f0f0f0f0
   pc: 0000000c
0000000c: 00000f93  addi    x31, x0, 0    # x31 = 0x00000000 = 0x00000000 + 0x00000000
ddt> r
   x0: 00000000 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
   x8: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x16: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0
  x24: f0f0f0f0 f0f0f0f0 f0f0f0f0 f0f0f0f0  00000000 00000000 00000000 00000000
   pc: 00000010
ddt> x
[winans@w510 src]$ 


================================================
FILE: book/float/chapter.tex
================================================
\chapter{Floating Point Numbers}
\label{chapter:floatingpoint}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{IEEE-754 Floating Point Number Representation}
\label{chapter::floatingpoint}

This section provides an overview of the IEEE-754 32-bit binary floating 
point format.\cite{ieee:754}

\begin{itemize}
\item Recall that the place values for integer binary numbers are:
\begin{verbatim}
   ... 128 64 32 16 8 4 2 1
\end{verbatim}
\item We can extend this to the right in binary similar to the way we do for 
decimal numbers:
\begin{verbatim}
   ... 128 64 32 16 8 4 2 1 . 1/2 1/4 1/8 1/16 1/32 1/64 1/128 ...
\end{verbatim}
The `.' in a binary number is a binary point, not a decimal point.

\item We use scientific notation as in $2.7 \times 10^{-47}$ to express either 
small fractions or large numbers when we are not concerned every last digit 
needed to represent the entire, exact, value of a number.

\item The format of a number in scientific notation is $mantissa \times base^{exponent}$

\item In binary we have $mantissa \times 2^{exponent}$

\item IEEE-754 format requires binary numbers to be {\em normalized} to 
$1.significand \times 2^{exponent}$ where the {\em significand}
is the portion of the {\em mantissa} that is to the right of the binary-point.

\begin{itemize}
\item The unnormalized binary value of $-2.625$ is $-10.101$
\item The normalized value of $-2.625$ is $-1.0101 \times 2^1$
\end{itemize}

\item We need not store the `1.' part because {\em all} normalized floating 
point numbers will start that way.  Thus we can save memory when storing
normalized values by inserting a `1.' to the left of significand.



\DrawBitBoxIEEEFloat{11000000001010000000000000000000}


%{
%\small
%\setlength{\unitlength}{.15in}
%\begin{picture}(32,4)(0,0)
%	\put(0,1){\line(1,0){32}}		% bottom line
%	\put(0,2){\line(1,0){32}}		% top line
%
%	\put(0,1){\line(0,1){2}}		% left vertical
%	\put(0,2){\makebox(1,1){\tiny 31}}	% left end bit number marker 
%
%	\put(32,1){\line(0,1){2}}		% vertical right end 
%	\put(31,2){\makebox(1,1){\tiny 0}}	% right end bit number marker
%
%	\put(0,0){\makebox(1,1){\small sign}}
%	\put(1,0){\makebox(8,1){\small exponent}}
%	\put(9,0){\makebox(23,1){\small significand}}
%
%    \put(0,1){\makebox(1,1){1}}		% sign
%
%	\put(1,1){\line(0,1){2}}		% seperator
%	\put(1,2){\makebox(1,1){\tiny 30}}	% bit marker
%
%    \put(1,1){\makebox(1,1){1}}		% exponent
%    \put(2,1){\makebox(1,1){0}}
%    \put(3,1){\makebox(1,1){0}}
%    \put(4,1){\makebox(1,1){0}}
%    \put(5,1){\makebox(1,1){0}}
%    \put(6,1){\makebox(1,1){0}}
%    \put(7,1){\makebox(1,1){0}}
%    \put(8,1){\makebox(1,1){0}}
%
%	\put(8,2){\makebox(1,1){\tiny 23}}	% bit marker
%	\put(9,1){\line(0,1){2}}		% seperator
%	\put(9,2){\makebox(1,1){\tiny 22}}	% bit marker
%
%    \put(9,1){\makebox(1,1){0}}
%    \put(10,1){\makebox(1,1){1}}
%    \put(11,1){\makebox(1,1){0}}
%    \put(12,1){\makebox(1,1){1}}
%    \put(13,1){\makebox(1,1){0}}
%    \put(14,1){\makebox(1,1){0}}
%    \put(15,1){\makebox(1,1){0}}
%    \put(16,1){\makebox(1,1){0}}
%    \put(17,1){\makebox(1,1){0}}
%    \put(18,1){\makebox(1,1){0}}
%    \put(19,1){\makebox(1,1){0}}
%    \put(20,1){\makebox(1,1){0}}
%    \put(21,1){\makebox(1,1){0}}
%    \put(22,1){\makebox(1,1){0}}
%    \put(23,1){\makebox(1,1){0}}
%    \put(24,1){\makebox(1,1){0}}
%    \put(25,1){\makebox(1,1){0}}
%    \put(26,1){\makebox(1,1){0}}
%    \put(27,1){\makebox(1,1){0}}
%    \put(28,1){\makebox(1,1){0}}
%    \put(29,1){\makebox(1,1){0}}
%    \put(30,1){\makebox(1,1){0}}
%    \put(31,1){\makebox(1,1){0}}
%\end{picture}
%}

%\item $-((1 + \frac{1}{4} + \frac{1}{16}) \times 2^{128-127}) = -(1 \frac{5}{16} \times 2^{1}) = -(1.3125 \times 2^{1}) = -2.625$
\item $-((1 + \frac{1}{4} + \frac{1}{16}) \times 2^{128-127}) = -((1 + \frac{1}{4} + \frac{1}{16}) \times 2^1) = -(2 + \frac{1}{2} + \frac{1}{8}) = -(2 + .5 + .125) = -2.625$

\item IEEE-754 formats: 

\begin{tabular}{|l|l|l|}
\hline
				& IEEE-754 32-bit	& IEEE-754 64-bit	\\
\hline
sign			& 1 bit				& 1 bit			\\
exponent		& 8 bits (excess-127)			& 11 bits (excess-1023)		\\
mantissa		& 23 bits			& 52 bits		\\
max exponent	& 127				& 1023			\\
min exponent	& -126				& -1022			\\
\hline
\end{tabular}

\item When the exponent is all ones, the significand is all zeros, and
the sign is zero, the number represents positive infinity.

\item When the exponent is all ones, the significand is all zeros, and
the sign is one, the number represents negative infinity.

\item Observe that the binary representation of a pair of IEEE-754 numbers
(when one or both are positive) can be compared for magnitude 
by treating them as if they are two's complement signed integers.  
This is because an IEEE number is stored in {\em signed magnitude} format and 
therefore positive floating point values will grow upward and downward in the 
same fashion as for unsigned integers and that since negative floating point 
values will have its MSB set, they will `appear` to be less than a positive 
floating point value.  

When comparing two negative IEEE float values by treating them both as two's
complement signed integers, the order will be reversed because IEEE float values 
with larger (that is, increasingly negative) magnitudes will appear to decrease 
in value when interpreted as signed integers.

This works this way because excess notation is used in the format of the 
exponent and why the significand's sign bit is located on the left of 
the exponent.\footnote{I know this is true and was done on purpose because
Bill Cody, chairman of IEEE committee P754 that designed the IEEE-754 standard, 
told me so personally circa 1991.}

\item Note that zero is a special case number.  Recall that a normalized
number has an implied 1-bit to the left of the significand\ldots\ which
means that there is no way to represent zero!
Zero is represented by an exponent of all-zeros and a significand of 
all-zeros.  This definition allows for a positive and a negative zero 
if we observe that the sign can be either 1 or 0.

\item On the number-line, numbers between zero and the smallest fraction in 
either direction are in the {\em \gls{underflow}} areas.
\enote{Need to add the standard lecture number-line diagram showing
where the over/under-flow areas are and why.}

\item On the number line, numbers greater than the mantissa of all-ones and the 
largest exponent allowed are in the {\em \gls{overflow}} areas.

\item Note that numbers have a higher resolution on the number line when the 
exponent is smaller.

\item The largest and smallest possible exponent values are reserved to represent
things requiring special cases. For example, the infinities, values representing
``not a number'' (such as the result of dividing by zero), and for a way to represent
values that are not normalized. For more information on special cases see \cite{ieee:754}.

\end{itemize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Floating Point Number Accuracy}
Due to the finite number of bits used to store the value of a floating point
number, it is not possible to represent every one of the infinite values
on the real number line.  The following C programs illustrate this point.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Powers Of Two}
Just like the integer numbers, the powers of two that have bits to represent 
them can be represented perfectly\ldots\ as can their sums (provided that the
significand requires no more than 23 bits.)

\listing{powersoftwo.c}{Precise Powers of Two} 
\listing{powersoftwo.out}{Output from {\tt powersoftwo.c}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Clean Decimal Numbers}
When dealing with decimal values, you will find that they don't map simply
into binary floating point values.
% (the same holds true for binary integer numbers).  

Note how the decimal numbers are not accurately represented as they get larger.
The decimal number on line 10 of \listingRef{cleandecimal.out}
can be perfectly represented in IEEE format.  However, a problem arises in 
the 11Th loop iteration.  It is due to the fact that the
binary number can not be represented accurately in IEEE format.  Its least
significant bits were truncated in a best-effort attempt at rounding the value
off in order to fit the value into the bits provided.  This is an example of
{\em low order truncation}.  Once this happens, the value of \verb@x.f@ is
no longer as precise as it could be given more bits in which to save its value.

\listing{cleandecimal.c}{Print Clean Decimal Numbers} 
\listing{cleandecimal.out}{Output from {\tt cleandecimal.c}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Accumulation of Error}
These  rounding errors can be exaggerated when the number we multiply 
the \verb@x.f@ value by is, itself, something that can not be accurately 
represented in IEEE 
form.\footnote{Applications requiring accurate decimal values, such as 
financial accounting systems, can use a packed-decimal numeric format
to avoid unexpected oddities caused by the use of binary numbers.}
\enote{In a lecture one would show that one tenth is a repeating 
non-terminating binary number that gets truncated.  This discussion 
should be reproduced here in text form.}

For example, if we multiply our \verb@x.f@ value by $\frac{1}{10}$ each time, 
we can never be accurate and we start accumulating errors immediately.

\listing{erroraccumulation.c}{Accumulation of Error} 
\listing{erroraccumulation.out}{Output from {\tt erroraccumulation.c}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Reducing Error Accumulation} 
In order to use floating point numbers in a program without causing 
excessive rounding problems an algorithm can be redesigned such that the 
accumulation is eliminated.  
This example is similar to the previous one, but this time we recalculate the 
desired value from a known-accurate integer value.  
Some rounding errors remain present, but they can not accumulate.

\listing{errorcompensation.c}{Accumulation of Error} 
\listing{errorcompensation.out}{Output from {\tt erroraccumulation.c}}


================================================
FILE: book/float/cleandecimal.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

union floatbin
{
    unsigned int    i;
    float           f;
};
int main()
{
    union floatbin  x, y;
    int             i;

    x.f = 10;
    while (x.f <= 10000000000000.0)
    {
        y.f = -x.f;
        printf("%25.10f = %08x     %25.10f = %08x\n", x.f, x.i, y.f, y.i);
        x.f = x.f*10.0;
    }
}


================================================
FILE: book/float/cleandecimal.out
================================================
            10.0000000000 = 41200000                -10.0000000000 = c1200000
           100.0000000000 = 42c80000               -100.0000000000 = c2c80000
          1000.0000000000 = 447a0000              -1000.0000000000 = c47a0000
         10000.0000000000 = 461c4000             -10000.0000000000 = c61c4000
        100000.0000000000 = 47c35000            -100000.0000000000 = c7c35000
       1000000.0000000000 = 49742400           -1000000.0000000000 = c9742400
      10000000.0000000000 = 4b189680          -10000000.0000000000 = cb189680
     100000000.0000000000 = 4cbebc20         -100000000.0000000000 = ccbebc20
    1000000000.0000000000 = 4e6e6b28        -1000000000.0000000000 = ce6e6b28
   10000000000.0000000000 = 501502f9       -10000000000.0000000000 = d01502f9
   99999997952.0000000000 = 51ba43b7       -99999997952.0000000000 = d1ba43b7
  999999995904.0000000000 = 5368d4a5      -999999995904.0000000000 = d368d4a5
 9999999827968.0000000000 = 551184e7     -9999999827968.0000000000 = d51184e7


================================================
FILE: book/float/erroraccumulation.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

union floatbin
{
    unsigned int    i;
    float           f;
};
int main()
{
    union floatbin  x, y;
    int             i;

    x.f = .1;
    while (x.f <= 2.0)
    {
        y.f = -x.f;
        printf("%25.10f = %08x     %25.10f = %08x\n", x.f, x.i, y.f, y.i);
        x.f += .1;
    }
}


================================================
FILE: book/float/erroraccumulation.out
================================================
0.1000000015 = 3dcccccd                 -0.1000000015 = bdcccccd
0.2000000030 = 3e4ccccd                 -0.2000000030 = be4ccccd
0.3000000119 = 3e99999a                 -0.3000000119 = be99999a
0.4000000060 = 3ecccccd                 -0.4000000060 = becccccd
0.5000000000 = 3f000000                 -0.5000000000 = bf000000
0.6000000238 = 3f19999a                 -0.6000000238 = bf19999a
0.7000000477 = 3f333334                 -0.7000000477 = bf333334
0.8000000715 = 3f4cccce                 -0.8000000715 = bf4cccce
0.9000000954 = 3f666668                 -0.9000000954 = bf666668
1.0000001192 = 3f800001                 -1.0000001192 = bf800001
1.1000001431 = 3f8cccce                 -1.1000001431 = bf8cccce
1.2000001669 = 3f99999b                 -1.2000001669 = bf99999b
1.3000001907 = 3fa66668                 -1.3000001907 = bfa66668
1.4000002146 = 3fb33335                 -1.4000002146 = bfb33335
1.5000002384 = 3fc00002                 -1.5000002384 = bfc00002
1.6000002623 = 3fcccccf                 -1.6000002623 = bfcccccf
1.7000002861 = 3fd9999c                 -1.7000002861 = bfd9999c
1.8000003099 = 3fe66669                 -1.8000003099 = bfe66669
1.9000003338 = 3ff33336                 -1.9000003338 = bff33336


================================================
FILE: book/float/errorcompensation.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

union floatbin 
{
    unsigned int    i;
    float           f;
};
int main()
{
    union floatbin  x, y;               
    int             i;

    i = 1;
    while (i <= 20)
    {
        x.f = i/10.0;
        y.f = -x.f;
        printf("%25.10f = %08x     %25.10f = %08x\n", x.f, x.i, y.f, y.i);
        i++; 
    }
    return(0); 
}


================================================
FILE: book/float/errorcompensation.out
================================================
0.1000000015 = 3dcccccd                 -0.1000000015 = bdcccccd
0.2000000030 = 3e4ccccd                 -0.2000000030 = be4ccccd
0.3000000119 = 3e99999a                 -0.3000000119 = be99999a
0.4000000060 = 3ecccccd                 -0.4000000060 = becccccd
0.5000000000 = 3f000000                 -0.5000000000 = bf000000
0.6000000238 = 3f19999a                 -0.6000000238 = bf19999a
0.6999999881 = 3f333333                 -0.6999999881 = bf333333
0.8000000119 = 3f4ccccd                 -0.8000000119 = bf4ccccd
0.8999999762 = 3f666666                 -0.8999999762 = bf666666
1.0000000000 = 3f800000                 -1.0000000000 = bf800000
1.1000000238 = 3f8ccccd                 -1.1000000238 = bf8ccccd
1.2000000477 = 3f99999a                 -1.2000000477 = bf99999a
1.2999999523 = 3fa66666                 -1.2999999523 = bfa66666
1.3999999762 = 3fb33333                 -1.3999999762 = bfb33333
1.5000000000 = 3fc00000                 -1.5000000000 = bfc00000
1.6000000238 = 3fcccccd                 -1.6000000238 = bfcccccd
1.7000000477 = 3fd9999a                 -1.7000000477 = bfd9999a
1.7999999523 = 3fe66666                 -1.7999999523 = bfe66666
1.8999999762 = 3ff33333                 -1.8999999762 = bff33333
2.0000000000 = 40000000                 -2.0000000000 = c0000000


================================================
FILE: book/float/powersoftwo.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

union floatbin
{
    unsigned int    i;
    float           f;
};
int main()
{
    union floatbin  x;
	union floatbin	y;
    int             i;
    x.f = 1.0;
    while (x.f > 1.0/1024.0)
    {
        y.f = -x.f;
        printf("%25.10f = %08x     %25.10f = %08x\n", x.f, x.i, y.f, y.i);
        x.f = x.f/2.0;
    }
}


================================================
FILE: book/float/powersoftwo.out
================================================
1.0000000000 = 3f800000                 -1.0000000000 = bf800000
0.5000000000 = 3f000000                 -0.5000000000 = bf000000
0.2500000000 = 3e800000                 -0.2500000000 = be800000
0.1250000000 = 3e000000                 -0.1250000000 = be000000
0.0625000000 = 3d800000                 -0.0625000000 = bd800000
0.0312500000 = 3d000000                 -0.0312500000 = bd000000
0.0156250000 = 3c800000                 -0.0156250000 = bc800000
0.0078125000 = 3c000000                 -0.0078125000 = bc000000
0.0039062500 = 3b800000                 -0.0039062500 = bb800000
0.0019531250 = 3b000000                 -0.0019531250 = bb000000


================================================
FILE: book/glossary.tex
================================================
\newglossaryentry{latex}
{
    name=LaTeX,
    description={Is a mark up language specially suited
    	for scientific documents}
}

\newglossaryentry{binary}
{
	name=binary,
	description={Something that has two parts or states.  In computing
		these two states are represented by the numbers one and zero or
		by the conditions true and false and can be stored in one \gls{bit}}
}
\newglossaryentry{hexadecimal}
{
	name=hexadecimal,
	description={A base-16 numbering system whose digits are 0123456789abcdef.  
		The hex digits (\gls{hit}s) are not case-sensitive}
}
\newglossaryentry{bit}
{
	name=bit,
	description={One binary digit}
}
\newglossaryentry{hit}
{
	name={hit},
	description={One \gls{hexadecimal} digit}
}
\newglossaryentry{nybble}
{
	name={nybble},
	description={Half of a {\em \gls{byte}} is a {\em nybble}
		(sometimes spelled nibble.)  Another word for {\em \gls{hit}}}
}
\newglossaryentry{byte}
{
	name=byte,
	description={A \gls{binary} value represented by 8 \gls{bit}s}
}
\newglossaryentry{halfword}
{
	name={halfword},
	description={A \gls{binary} value represented by 16 \gls{bit}s}
}
\newglossaryentry{fullword}
{
	name={fullword},
	description={A \gls{binary} value represented by 32 \gls{bit}s}
}
\newglossaryentry{doubleword}
{
	name={doubleword},
	description={A \gls{binary} value represented by 64 \gls{bit}s}
}
\newglossaryentry{quadword}
{
	name={quadword},
	description={A \gls{binary} value represented by 128 \gls{bit}s}
}
\newglossaryentry{HighOrderBits}
{
	name={high order bits},
	description={Some number of \acrshort{msb}s}
}
\newglossaryentry{LowOrderBits}
{
    name={low order bits},
    description={Some number of \acrshort{lsb}s}
}

\newglossaryentry{xlen}
{
	name=XLEN,
	description={The number of bits a RISC-V x integer \gls{register}
		(such as x0).  For RV32 XLEN=32, RV64 XLEN=64 and so on}
}
\newglossaryentry{rv32}
{
	name=RV32,
	description={Short for RISC-V 32.  The number 32 refers to the \gls{xlen}}
}
\newglossaryentry{rv64}
{
	name=RV64,
	description={Short for RISC-V 64.  The number 64 refers to the \gls{xlen}}
}
\newglossaryentry{overflow}
{
	name=overflow,
	description={The situation where the result of an addition or 
		subtraction operation is approaching positive or negative 
		infinity and exceeds the number of bits allotted to contain 
		the result.  This is typically caused by high-order truncation}
}
\newglossaryentry{underflow}
{
	name=underflow,
	description={The situation where the result of an addition or 
		subtraction operation is approaching zero and exceeds the number 
		of bits allotted to contain the result.  This is typically
        caused by low-order truncation}
}

\newglossaryentry{MachineLanguage}
{
	name={machine language},
	description={The instructions that are executed by a CPU that are expressed
		in the form of \gls{binary} values}
}
\newglossaryentry{register}
{
	name={register},
	description={A unit of storage inside a CPU with the capacity of \gls{xlen} \gls{bit}s}
}
\newglossaryentry{program}
{
	name={program},
	description={A ordered list of one or more instructions}
}
\newglossaryentry{address}
{
	name={address},
	description={A numeric value used to uniquely identify each \gls{byte} of main memory}
}
\newglossaryentry{alignment}
{
	name={alignment},
	description={Refers to a range of numeric values that begin 
		at a multiple of some number.  Primarily used when referring to
		a memory address.  For example an alignment of two refers to one
		or more addresses starting at even address and continuing onto
		subsequent adjacent, increasing memory addresses}
}
\newglossaryentry{exception}
{
	name={exception},
	description={An error encountered by the CPU while executing an instruction
		that can not be completed}
}

\newglossaryentry{bigendian}
{
	name={big-endian},
	description={A number format where the most significant values are 
	printed to the left of the lesser significant values.  This is the
	method that everyone uses to write decimal numbers every day}
}
\newglossaryentry{littleendian}
{
	name={little-endian},
	description={A number format where the least significant values are 
		printed to the left of the more significant values.  This is the
		opposite ordering that everyone learns in grade school when learning
		how to count.  For example, the \gls{bigendian} number written as ``1234''
		would be written in little endian form as ``4321''}
}
\newglossaryentry{rvddt}
{
	name={rvddt},
	description={A RV32I simulator and debugging tool inspired by the 
		simplicity of the Dynamic Debugging Tool (ddt) that was part of 
		the CP/M operating system}
}
\newglossaryentry{mnemonic}
{
	name={mnemonic},
	description={A method used to remember something.  In the case of
		assembly language, each machine instruction is given a name
		so the programmer need not memorize the binary values of each
		machine instruction}
}
\newglossaryentry{thread}
{
	name={thread},
	description={An stream of instructions.  When plural, it is
		used to refer to the ability of a CPU to execute multiple 
		instruction streams at the same time}
}
\newglossaryentry{ascii}
{
	name={ASCII},
	description={American Standard Code for Information Interchange.
		See \autoref{chapter:ascii}}
}
\newglossaryentry{place-value}
{
	name={place value},
	description={the numerical value that a digit has as a result of its {\em position} within a number.
	For example, the digit 2 in the decimal number 123 is in the ten's place and its place value is 20}
}


\newacronym{hart}{hart}{Hardware Thread}
\newacronym{msb}{MSB}{Most Significant Bit}
\newacronym{lsb}{LSB}{Least Significant Bit}
\newacronym{isa}{ISA}{Instruction Set Architecture}
\newacronym{cpu}{CPU}{Central Processing Unit}
\newacronym{ram}{RAM}{Random Access Memory}
\newacronym{rom}{ROM}{Read Only Memory}
%\newacronym{ascii}{ASCII}{American Standard Code for Information Interchange}


================================================
FILE: book/insnformats.tex
================================================

\def\SignBoxCornerRadius{.75mm}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\BeginTikzPicture{
    %\begin{tikzpicture}[x=.4cm,y=.3cm]
    \begin{tikzpicture}[x=.35cm,y=.3cm]
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\EndTikzPicture{
    \end{tikzpicture}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Print the characters within a string evenly spaced at integral node positions
%
% #1 The number of characters in the string
% #2 The string to print
\newcommand\DrawBitstring[2]{
\foreach \x in {1,...,#1}%
	\draw(\x,0) node{\substring{#2}{\x}{\x}};%
%	\draw(\x,.5) node[text width = 10, text height = 1]{\substring{#2}{\x}{\x}};%	Improve vertical text alignment
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 The total size
% #2 The string to print
% #3 The value to use when extending to left
\newcommand\DrawLeftExtendedBitstring[3]{
	\StrLen{#2}[\numchars]

	\pgfmathsetmacro\leftpadd{int(#1-\numchars)}
	\foreach \x in {1,...,\leftpadd}
    	\draw(\x,0) node{#3};

	\pgfmathsetmacro\leftpadd{int(\leftpadd+1)}
	\foreach \x in {\leftpadd,...,#1}
		\pgfmathsetmacro\ix{int(\x-\leftpadd+1)}
		\draw(\x,0) node{\substring{#2}{\ix}{\ix}};
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the string is shorter than expected, extend with #5 to the right.
%
% #1 The total size
% #2 Num chars to extend on the right
% #3 The string to print
% #4 The value to use when extending to left
% #5 The value to use when extending to right
\newcommand\DrawDoubleExtendedBitstring[5]{
	\StrLen{#3}[\numchars]

	\pgfmathsetmacro\leftpadd{int(#1-#2-\numchars)}
	\ifthenelse{1 > \leftpadd}
	{}
	{
		\foreach \x in {1,...,\leftpadd}
    		\draw(\x,0) node{#4};
	}

	\pgfmathsetmacro\leftpadd{int(\leftpadd+1)}
	\pgfmathsetmacro\rightpadd{int(\leftpadd+\numchars)}
	\foreach \x in {\leftpadd,...,\rightpadd}
		\pgfmathsetmacro\ix{int(\x-\leftpadd+1)}
		\draw(\x,0) node{\substring{#3}{\ix}{\ix}};


	%\pgfmathsetmacro\rightpadd{int(\rightpadd+1)}
	\ifthenelse{\rightpadd > #1}	
	{}
	{
		\foreach \x in {\rightpadd,...,#1}
			\draw(\x,0) node{#5};
	}
}




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a box suitable to show the given number of bits in a 
% labeled box suitable for showing expanded binary numbers.
%
% #1 The number of characters to display
\newcommand\DrawBitBox[1]{
    \draw (.5,-.75) -- (#1+.5,-.75);		% box bottom
    \draw (.5,.75) -- (#1+.5,.75);			% box top
    \draw (.5,-.75) -- (.5, 1.5);			% left end
    \draw (#1+.5,-.75) -- (#1+.5, 1.5);		% right end
    \pgfmathsetmacro\result{int(#1-1)}		% calc high bit 
    \node at (1,1.2) {\tiny\result};		% high bit label
    \draw(#1,1.2) node{\tiny0};				% low bit label

    \pgfmathsetmacro\result{#1/2}
    \node at (\result,-1.2) {\tiny#1};		% size below the box

    \pgfmathsetmacro\result{#1/2}
    \draw[->] (\result+.6,-1.2) -- (#1+.5,-1.2);
    \draw[->] (\result-.6,-1.2) -- (.5,-1.2);
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawBitBoxUnsigned[1]{
	\StrLen{#1}[\numchars]
	\DrawBitBox{\numchars}
	\DrawBitstring{\numchars}{#1}		% show the bits
}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawBitBoxUnsignedPicture[1]{
	\BeginTikzPicture
	\DrawBitBoxUnsigned{#1}
	\EndTikzPicture
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawBitBoxSignedPicture[1]{
    \BeginTikzPicture
    \DrawBitBoxUnsigned{#1}
	% draw a box around the sign bit
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};
    \EndTikzPicture
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 The total (extended) size
% #2 The value to use for left-side padding
% #3 The string to extend
\newcommand\DrawBitBoxLeftExtended[3]{
	\StrLen{#3}[\numchars]
	\pgfmathsetmacro\fill{int(#1-\numchars)}
	\begin{scope}[shift={(\fill,3.5)}]
    \DrawBitBoxUnsigned{#3}

   	% XXX IFF not zero-extending then draw a box around the sign bit
   	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};
	\end{scope}

	\DrawBitBox{#1}
	\DrawDoubleExtendedBitstring{#1}{0}{#3}{#2}{x}
	
   	% XXX IFF not zero-extending then draw a box around the sign bit
   	\draw {[rounded corners=\SignBoxCornerRadius] (\fill+1.35, -.6) -- (\fill+1.35, .6) -- (\fill+.65, .6) -- (\fill+.65, -.6) -- cycle};
    % draw a box around the extended sign bits
    \draw (.65, -.6) -- (.65, .6) -- (\fill+.35, .6) -- (\fill+.35, -.6) -- cycle;


}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawBitBoxSignExtendedPicture[2]{
	\BeginTikzPicture
	\DrawBitBoxLeftExtended{#1}{\substring{#2}{1}{1}}{#2}
    \EndTikzPicture
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawBitBoxZeroExtendedPicture[2]{
	\BeginTikzPicture
	\DrawBitBoxLeftExtended{#1}{0}{#2}
    \EndTikzPicture
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 Total bit length
% #2 The string to print
% #3 Right-side padding length
\newcommand\DrawBitBoxSignLeftZeroRightExtendedPicture[3]{
	\BeginTikzPicture

	\StrLen{#2}[\numchars]
	\pgfmathsetmacro\fill{int(#1-\numchars-#3)}
	\begin{scope}[shift={(\fill,3.5)}]
    \DrawBitBoxUnsigned{#2}
    % draw a box around the sign bit
    %\draw (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle;
    \draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};
	\end{scope}

	\DrawBitBox{#1}
	\DrawDoubleExtendedBitstring{#1}{#3}{#2}{\substring{#2}{1}{1}}{0}

	% Box the sign bit
    \draw {[rounded corners=\SignBoxCornerRadius] (\fill+1.35, -.6) -- (\fill+1.35, .6) -- (\fill+.65, .6) -- (\fill+.65, -.6) -- cycle};

	\ifthenelse{\fill > 0}
	{
    	% Box the left-extended sign bits
    	\draw (.65, -.6) -- (.65, .6) -- (\fill+.35, .6) -- (\fill+.35, -.6) -- cycle;
		% \fill[blue!40!white] (.65, -.6) rectangle (\fill-.25, 1.2);
	}
	{}
	\ifthenelse{#3 > 0}
	{
    	% Box the right-extended sign bits
		\pgfmathsetmacro\posn{int(\numchars+\fill)}
    	\draw (\posn+.65, -.6) -- (\posn+.65, .6) -- (\posn+#3+.35, .6) -- (\posn+#3+.35, -.6) -- cycle;
	}
	{}
	

    \EndTikzPicture
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Draw hex markers
% #1 The number of bits in the box
\newcommand\DrawHexMarkers[1]{
	\pgfmathsetmacro\num{int(#1-1)}
	\foreach \x in {4,8,...,\num}
		\draw [line width=.5mm] (\x+.5,-.75) -- (\x+.5, -.3);
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Print the characters within a string evenly spaced at integral node positions
%
% #1 The number of characters in the string
% #2 The string of characters to plot
% #3 Right-side label
\newcommand\DrawInsnBitstring[3]{
	\pgfmathsetmacro\num{int(#1-1)}
	\foreach \x in {1,2,...,#1}
    	\draw(\x+.25,-.3) node[text width = 10, text height = 1]{\substring{#2}{\x}{\x}};
	\draw(#1+1,0) node[right]{#3};
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a bit-separator line with labels at the given bit-offset (from the right)
%
% #1 Total box width
% #2 The position that the separator will be drawn to the left.
\newcommand\DrawInsnBoxSep[2]{
	\draw (#1-#2-.5,-.75) -- (#1-#2-.5, 1.5);
	\node at (#1-#2,1.2) {\tiny#2};
	\pgfmathsetmacro\result{int(#2+1)}
	\node at (#1-#2-1,1.2) {\tiny\result};
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 total characters/width
% #2 MSB position
% #3 LSB position
% #4 the segment label
\newcommand\DrawInsnBoxSeg[4]{
	\pgfmathsetmacro\leftpos{int(#1-#2)}
	\pgfmathsetmacro\rightpos{int(#1-#3)}

	\draw (\leftpos-.5,-.75) -- (\rightpos+.5,-.75);	% box bottom
	\draw (\leftpos-.5,1.75) -- (\rightpos+.5,1.75);	% box top
	\draw (\leftpos-.5,-.75) -- (\leftpos-.5, 2.5);		% left end
	\draw (\rightpos+.5,-.75) -- (\rightpos+.5, 2.5);	% right end
	\node at (\leftpos,2.2) {\tiny#2};
	\draw(\rightpos,2.2) node{\tiny#3};

	\pgfmathsetmacro\posn{#1-#2+(#2-#3)/2}
	\pgfmathsetmacro\range{int(#2-#3+1)}
	\node at (\posn,1.2) {\small#4};			% the field label

%	\node at (\posn,-1.4) {\small\range};		% the field width
	\begin{scope}[shift={(0,-.7)}]\InsnBoxFieldWidthArrow{#2}{#3}\end{scope}

%	% arrows showing the span of the bits... meh
%    \draw[->] (\posn+.5,-1.4) -- (\rightpos+.2,-1.4);
%    \draw[->] (\posn-.5,-1.4) -- (\leftpos-.2,-1.4);
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\InsnStatement[1]{
%	\textbf{\large #1}\\
%	\textbf{#1}\\
	{\large #1}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\DrawInsnTypeB[1]{
	\StrLen{#1}[\numchars]
	\begin{scope}[shift={(0,.75)}]	
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:btype]{B-type}}
	\DrawInsnBoxSeg{\numchars}{31}{25}{imm[12\textbar10:5]}
	\DrawInsnBoxSeg{\numchars}{24}{20}{rs2}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{imm[4:1\textbar11]}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	% add some hint bits in for imm fields
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};	% sign bit
	\draw (32-7-.5, -.75) -- (32-7-.5, .1);		% imm[11]
	\draw (32-30-.5, -.75) -- (32-30.5, .1);	% imm[12]

	\end{scope}

	\DrawHexMarkersRel{\numchars}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeBTikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeB{#1}
	\EndTikzPicture
}

\newcommand\DrawInsnTypeBPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeBTikz{#2}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeU[1]{
	\StrLen{#1}[\numchars]
	\begin{scope}[shift={(0,.75)}]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:utype]{U-type}}
	\DrawInsnBoxSeg{\numchars}{31}{12}{imm[31:12]}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	% add some hint bits in for imm fields
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};	% sign bit
	\end{scope}

	\DrawHexMarkersRel{\numchars}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeUTikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeU{#1}
	\EndTikzPicture
}

\newcommand\DrawInsnTypeUPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeUTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeJ[1]{
	\StrLen{#1}[\numchars]
	\begin{scope}[shift={(0,.75)}]	
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:jtype]{J-type}}

	\DrawInsnBoxSeg{\numchars}{31}{12}{imm[20\textbar10:1\textbar11\textbar19:12]}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}
%	\DrawHexMarkers{\numchars}
	\end{scope}

	% add some hint bits in for imm fields
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, .15) -- (1.35, 1.35) -- (.65, 1.35) -- (.65, .15) -- cycle};	% sign bit
	\draw (32-19-.5, 0) -- (32-19.5, .85);		% imm[19:12]
	\draw (32-20-.5, 0) -- (32-20.5, .85);		% imm[11]
	\draw (32-30-.5, 0) -- (32-30.5, .85);		% imm[1:10]
	\DrawHexMarkersRel{\numchars}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeJTikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeJ{#1}
%	\StrLen{#1}[\numchars]
%	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:jtype]{J-type}}
%	\DrawInsnBoxSeg{\numchars}{31}{12}{imm[20\textbar10:1\textbar11\textbar19:12]}
%	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
%	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}
%
%	% add some hint bits in for imm fields
%	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};	% sign bit
%	\draw (32-19-.5, -.75) -- (32-19.5, .1);		% imm[19:12]
%	\draw (32-20-.5, -.75) -- (32-20.5, .1);		% imm[11]
%	\DrawHexMarkers{\numchars}

	\EndTikzPicture
}

\newcommand\DrawInsnTypeJPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeJTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeI[1]{
	\StrLen{#1}[\numchars]
	\begin{scope}[shift={(0,.75)}]	
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:itype]{I-type}}
	\DrawInsnBoxSeg{\numchars}{31}{20}{imm[11:0]}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	% add some hint bits in for imm fields
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};	% sign bit
	\end{scope}
	\DrawHexMarkersRel{\numchars}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeITikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeI{#1}
%	\DrawHexMarkers{\numchars}
	\EndTikzPicture
}
\newcommand\DrawInsnTypeIPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeITikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeS[1]{
	\StrLen{#1}[\numchars]
	\begin{scope}[shift={(0,.75)}]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:stype]{S-type}}
	\DrawInsnBoxSeg{\numchars}{31}{25}{imm[11:5]}
	\DrawInsnBoxSeg{\numchars}{24}{20}{rs2}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{imm[4:0]}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	% add some hint bits in for imm fields
	\draw {[rounded corners=\SignBoxCornerRadius] (1.35, -.6) -- (1.35, .6) -- (.65, .6) -- (.65, -.6) -- cycle};	% sign bit
	\end{scope}

	\DrawHexMarkersRel{\numchars}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeSTikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeS{#1}
	\EndTikzPicture
}

\newcommand\DrawInsnTypeSPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeSTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeIShiftTikz[1]{
	\BeginTikzPicture
	\StrLen{#1}[\numchars]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:rtype]{I-type}}
	\DrawInsnBoxSeg{\numchars}{31}{25}{funct7}
	\DrawInsnBoxSeg{\numchars}{24}{20}{shamt}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	\DrawHexMarkers{\numchars}
	\EndTikzPicture
}

\newcommand\DrawInsnTypeRShiftPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeIShiftTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeR[1]{
	\StrLen{#1}[\numchars]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:rtype]{R-type}}
	\DrawInsnBoxSeg{\numchars}{31}{25}{funct7}
	\DrawInsnBoxSeg{\numchars}{24}{20}{rs2}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

	\DrawHexMarkers{\numchars}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeRTikz[1]{
	\BeginTikzPicture
	\DrawInsnTypeR{#1}
	\EndTikzPicture
}

\newcommand\DrawInsnTypeRPicture[2]{
	\InsnStatement{#1}\\
	\DrawInsnTypeRTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeFTikz[1]{
    \BeginTikzPicture
    \StrLen{#1}[\numchars]
    \DrawInsnBitstring{\numchars}{#1}{FENCE}
    \DrawInsnBoxSeg{\numchars}{31}{28}{}
    \DrawInsnBoxSeg{\numchars}{27}{24}{pred}
    \DrawInsnBoxSeg{\numchars}{23}{20}{succ}
    \DrawInsnBoxSeg{\numchars}{19}{15}{}
    \DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
    \DrawInsnBoxSeg{\numchars}{11}{7}{}
    \DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

    \DrawHexMarkers{\numchars}
    \EndTikzPicture
}

\newcommand\DrawInsnTypeFPicture[2]{
    \InsnStatement{#1}\\
    \DrawInsnTypeFTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeETikz[1]{
    \BeginTikzPicture
	\StrLen{#1}[\numchars]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:itype]{I-type}}
	\DrawInsnBoxSeg{\numchars}{31}{20}{}
	\DrawInsnBoxSeg{\numchars}{19}{15}{}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

    \DrawHexMarkers{\numchars}
    \EndTikzPicture
}

\newcommand\DrawInsnTypeEPicture[2]{
    \InsnStatement{#1}\\
    \DrawInsnTypeETikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeCSTikz[1]{
    \BeginTikzPicture
	\StrLen{#1}[\numchars]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:itype]{I-type}}
	\DrawInsnBoxSeg{\numchars}{31}{20}{csr}
	\DrawInsnBoxSeg{\numchars}{19}{15}{rs1}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

    \DrawHexMarkers{\numchars}
    \EndTikzPicture
}

\newcommand\DrawInsnTypeCSPicture[2]{
    \InsnStatement{#1}\\
    \DrawInsnTypeCSTikz{#2}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 the binary encoding
\newcommand\DrawInsnTypeCSITikz[1]{
    \BeginTikzPicture
	\StrLen{#1}[\numchars]
	\DrawInsnBitstring{\numchars}{#1}{\hyperref[insnformat:itype]{I-type}}
	\DrawInsnBoxSeg{\numchars}{31}{20}{csr}
	\DrawInsnBoxSeg{\numchars}{19}{15}{zimm}
	\DrawInsnBoxSeg{\numchars}{14}{12}{funct3}
	\DrawInsnBoxSeg{\numchars}{11}{7}{rd}
	\DrawInsnBoxSeg{\numchars}{6}{0}{opcode}

    \DrawHexMarkers{\numchars}
    \EndTikzPicture
}

\newcommand\DrawInsnTypeCSIPicture[2]{
    \InsnStatement{#1}\\
    \DrawInsnTypeCSITikz{#2}
}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\newcommand\xTInsnStatement[4]{%
	\parbox{3.5cm}{{\sffamily\large\bfseries #2}\\
	\tt#3}\hspace{5mm}\parbox{5cm}{\bfseries#1}\parbox{12cm}{#4}%
}

\newcommand\TInsnStatement[4]{%
	\begin{tabular}{lll}
	\parbox[t]{3.5cm}{{\sffamily\large\bfseries #2}\\
	\tt#3} & \parbox[t]{5cm}{\bfseries #1} & \parbox[t]{12cm}{#4}\\
	\end{tabular}
}

\newcommand\TDrawInsnTypeUPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeUTikz{#5}%
}

\newcommand\TDrawInsnTypeJPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeJTikz{#5}%
}

\newcommand\TDrawInsnTypeBPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeBTikz{#5}%
}

\newcommand\TDrawInsnTypeIPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeITikz{#5}%
}
\newcommand\TDrawInsnTypeSPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeSTikz{#5}%
}
\newcommand\TDrawInsnTypeRPicture[5]{%
	\TInsnStatement{#1}{#2}{#3}{#4}\\
    \DrawInsnTypeRTikz{#5}%
}

\newcommand\TDrawInsnTypeRShiftPicture[5]{
	\TInsnStatement{#1}{#2}{#3}{#4}\\
	\DrawInsnTypeIShiftTikz{#5}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw hex markers with a baseline at zero
% #1 The number of bits in the box
\newcommand\TheHexMark[1]{
	\draw [line width=.5mm] (#1+.5,0) -- (#1+.5, .4);
}

\newcommand\DrawHexMarkersRel[1]{
	\pgfmathsetmacro\num{int(#1-1)}
	\foreach \x in {4,8,...,\num}
		\draw [line width=.5mm] (\x+.5,0) -- (\x+.5, .4);
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw an instruction box with a baseline at zero
% #1 MSB position
% #2 LSB position
% #3 the segment label
\newcommand\DrawInsnBoxRelTop[3]{
	\pgfmathsetmacro\leftpos{int(32-#1)}
	\pgfmathsetmacro\rightpos{int(32-#2)}
	\draw (\leftpos-.5,1.5) -- (\rightpos+.5,1.5);	% box top
	\draw (\leftpos-.5,0) -- (\leftpos-.5, 1.5);	% left end
	\draw (\rightpos+.5,0) -- (\rightpos+.5, 1.5);	% right end
	\pgfmathsetmacro\posn{32-#1+(#1-#2)/2}
	\node at (\posn,.75) {\small#3};				% the field label
}

% Draw only the bottom line of an instruction box with a baseline at zero
% #1 MSB position
% #2 LSB position
\newcommand\DrawInsnBoxRelBottom[2]{
	\pgfmathsetmacro\leftpos{int(32-#1)}
	\pgfmathsetmacro\rightpos{int(32-#2)}
	\draw (\leftpos-.5,0) -- (\rightpos+.5,0);		% box bottom
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw an instruction box with a baseline at zero
% #1 MSB position
% #2 LSB position
% #3 the segment label
\newcommand\DrawInsnBoxRel[3]{
	\DrawInsnBoxRelTop{#1}{#2}{#3}
	\DrawInsnBoxRelBottom{#1}{#2}
}

%\newcommand\DrawInsnBoxRel[3]{
%	\pgfmathsetmacro\leftpos{int(32-#1)}
%	\pgfmathsetmacro\rightpos{int(32-#2)}
%
%	\draw (\leftpos-.5,0) -- (\rightpos+.5,0);	% box bottom
%	\draw (\leftpos-.5,1.5) -- (\rightpos+.5,1.5);	% box top
%	\draw (\leftpos-.5,0) -- (\leftpos-.5, 1.5);		% left end
%	\draw (\rightpos+.5,0) -- (\rightpos+.5, 1.5);	% right end
%
%    \pgfmathsetmacro\posn{32-#1+(#1-#2)/2}
%    \node at (\posn,.75) {\small#3};            % the field label
%}

% #1 MSB position
% #2 LSB position
\newcommand\DrawInsnBoxCastle[2]{
	\pgfmathsetmacro\leftpos{int(32-#1)}
	\pgfmathsetmacro\rightpos{int(32-#2)}
	\draw (\leftpos-.5,0) -- (\leftpos-.5, .75);		% left end
	\draw (\rightpos+.5,0) -- (\rightpos+.5, .75);	% right end
	\node at (\leftpos,.5) {\tiny#1};
	\ifthenelse{\equal{#1}{#2}}
	{}
	{ \draw(\rightpos,.5) node{\tiny#2}; }
}
\newcommand\DrawInsnBoxCastleRtype{
	\DrawInsnBoxCastle{31}{25}
	\DrawInsnBoxCastle{24}{20}
	\DrawInsnBoxCastle{19}{15}
	\DrawInsnBoxCastle{14}{12}
	\DrawInsnBoxCastle{11}{7}
	\DrawInsnBoxCastle{6}{0}
}

\newcommand\DrawInsnBoxCastleJtype{
	\DrawInsnBoxCastle{31}{31}
	\DrawInsnBoxCastle{30}{21}
	\DrawInsnBoxCastle{20}{20}
	\DrawInsnBoxCastle{19}{12}
	\DrawInsnBoxCastle{11}{7}
	\DrawInsnBoxCastle{6}{0}
}



%% Draw a B-Type instruction box
%% #1 label
%% #2 ...
%\newcommand\DrawInsnBoxBType[6]{
%	\DrawInsnBoxRel{31}{25}{#1}
%	\DrawInsnBoxRel{24}{20}{#2}
%	\DrawInsnBoxRel{19}{15}{#3}
%	\DrawInsnBoxRel{14}{12}{#4}
%	\DrawInsnBoxRel{11}{7}{#5}
%	\DrawInsnBoxRel{6}{0}{#6}
%}
%
%
%\newcommand\DrawInsnBoxLabelsBtype{
%	\DrawInsnBoxBType{imm[12\textbar10:5]}{rs2}{rs1}{funct3}{imm[4:1\textbar11]}{opcode}
%%	\DrawInsnBoxRel{31}{25}{imm[12\textbar10:5]}
%%	\DrawInsnBoxRel{24}{20}{rs2}
%%	\DrawInsnBoxRel{19}{15}{rs1}
%%	\DrawInsnBoxRel{14}{12}{funct3}
%%	\DrawInsnBoxRel{11}{7}{imm[4:1\textbar11]}
%%	\DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:btype]{B-type}};
%}
%\newcommand\DrawInsnBoxLabelsRtype{
%	\DrawInsnBoxRel{31}{25}{funct7}
%	\DrawInsnBoxRel{24}{20}{rs2}
%	\DrawInsnBoxRel{19}{15}{rs1}
%	\DrawInsnBoxRel{14}{12}{funct3}
%	\DrawInsnBoxRel{11}{7}{rd}
%	\DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:rtype]{R-type}};
%}
%\newcommand\DrawInsnBoxLabelsItype{
%	\DrawInsnBoxRel{31}{20}{imm[11:0]}
%	\DrawInsnBoxRel{19}{15}{rs1}
%	\DrawInsnBoxRel{14}{12}{funct3}
%	\DrawInsnBoxRel{11}{7}{rd}
%	\DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:itype]{I-type}};
%}
%\newcommand\DrawInsnBoxLabelsStype{
%    \DrawInsnBoxRel{31}{25}{imm[11:5]}
%    \DrawInsnBoxRel{24}{20}{rs2}
%    \DrawInsnBoxRel{19}{15}{rs1}
%    \DrawInsnBoxRel{14}{12}{funct3}
%    \DrawInsnBoxRel{11}{7}{imm[4:0]}
%    \DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:stype]{S-type}};
%}
%\newcommand\DrawInsnBoxLabelsUtype{
%	\DrawInsnBoxRel{31}{12}{imm[31:12]}
%	\DrawInsnBoxRel{11}{7}{rd}
%	\DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:utype]{U-type}};
%}
%\newcommand\DrawInsnBoxLabelsJtype{
%	\DrawInsnBoxRel{31}{12}{imm[20\textbar10:1\textbar11\textbar19:12]}
%	\DrawInsnBoxRel{11}{7}{rd}
%	\DrawInsnBoxRel{6}{0}{opcode}
%	\draw(33,.75) node[right]{\hyperref[insnformat:jtype]{J-type}};
%}
%
%\newcommand\XXXDrawAllInsnTypes{
%	\BeginTikzPicture
%	\DrawInsnBoxLabelsRtype
%	\begin{scope}[shift={(0,-1.5)}]\DrawInsnBoxLabelsItype\end{scope}
%	\begin{scope}[shift={(0,-3)}]\DrawInsnBoxLabelsStype\end{scope}
%	\begin{scope}[shift={(0,-4.5)}]\DrawInsnBoxLabelsBtype\end{scope}
%	\begin{scope}[shift={(0,-6)}]\DrawInsnBoxLabelsUtype\end{scope}
%	\begin{scope}[shift={(0,-7.5)}]\DrawInsnBoxLabelsJtype\DrawHexMarkersRel{32}\end{scope}
%
%	\begin{scope}[shift={(0,1.5)}]
%		\DrawInsnBoxCastleRtype
%	\end{scope}
%
%	\EndTikzPicture
%}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Print the characters within a string evenly spaced at integral node positions
% #1 The string of characters to plot
\newcommand\DrawBitstringX[1]{
	\StrLen{#1}[\numchars]
	\pgfmathsetmacro\num{int(\numchars-1)}
	\foreach \x in {1,2,...,\numchars}
%    	\draw(\x,0) node{\substring{\strut #1}{\x}{\x}};
		\draw(\x+.25,.5) node[text width = 10, text height = 1]{\substring{#1}{\x}{\x}};
}




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% REFERENCE CARD DRAWINGS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\InsnSrcArgPosX{4}	% relative to the position of the mnemonic

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% draw the instruction mnemonic and its args
% #1 mnemonic
% #2 args
\newcommand\DrawInsnSrc[2]{
	\draw node[right]{\tt #1};
	\draw(\InsnSrcArgPosX,0) node[right]{\tt #2};
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a I-type instruction box with the given labels
\newcommand\DrawInsnOpIBox[5]{
	\DrawInsnBoxRel{31}{20}{#1}
	\DrawInsnBoxRel{19}{15}{#2}
	\DrawInsnBoxRel{14}{12}{}
	\DrawInsnBoxRel{11}{7}{#4}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#3}\end{scope}
	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#5}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a I-type instruction box with a 32-bit binary value
\newcommand\DrawInsnOpIBinBox[1]{
	\DrawInsnBoxRel{31}{20}{}
	\DrawInsnBoxRel{19}{15}{}
	\DrawInsnBoxRel{14}{12}{}
	\DrawInsnBoxRel{11}{7}{}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-31,0)}]\DrawBitstringX{#1}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a I-type w/funct7 instruction box with the given labels
\newcommand\DrawInsnOpIFunctBox[6]{
    \DrawInsnBoxRel{31}{25}{}
    \DrawInsnBoxRel{24}{20}{#2}
    \DrawInsnBoxRel{19}{15}{#3}
    \DrawInsnBoxRel{14}{12}{}
    \DrawInsnBoxRel{11}{7}{#5}
    \DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#1}\end{scope}
	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#4}\end{scope}
	\begin{scope}[shift={(31-31,0)}]\DrawBitstringX{#6}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a I-type instruction box with the given labels
\newcommand\DrawInsnOpBBox[6]{
	\DrawInsnBoxRel{31}{25}{#1}
	\DrawInsnBoxRel{24}{20}{#2}
	\DrawInsnBoxRel{19}{15}{#3}
	\DrawInsnBoxRel{14}{12}{}
	\DrawInsnBoxRel{11}{7}{#5}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#4}\end{scope}
	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#6}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a S-type instruction box with the given labels
\newcommand\DrawInsnOpSBox[6]{
    \DrawInsnBoxRel{31}{25}{#1}
    \DrawInsnBoxRel{24}{20}{#2}
    \DrawInsnBoxRel{19}{15}{#3}
    \DrawInsnBoxRel{14}{12}{}
    \DrawInsnBoxRel{11}{7}{#5}
    \DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#6}\end{scope}
	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#4}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a R-type instruction box with the given labels
\newcommand\DrawInsnOpRBox[6]{
	\DrawInsnBoxRel{31}{25}{}
	\DrawInsnBoxRel{24}{20}{#2}
	\DrawInsnBoxRel{19}{15}{#3}
	\DrawInsnBoxRel{14}{12}{}
	\DrawInsnBoxRel{11}{7}{#5}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#6}\end{scope}
	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#4}\end{scope}
	\begin{scope}[shift={(31-31,0)}]\DrawBitstringX{#1}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a U-type instruction box with the given labels
\newcommand\DrawInsnOpUBox[3]{
	\DrawInsnBoxRel{31}{12}{#1}
	\DrawInsnBoxRel{11}{7}{#2}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#3}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw a J-type instruction box with the given labels
\newcommand\DrawInsnOpJBox[3]{
	\DrawInsnBoxRel{31}{12}{#1}
	\DrawInsnBoxRel{11}{7}{#2}
	\DrawInsnBoxRel{6}{0}{}

	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#3}\end{scope}
}




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\InsnBoxTypePosX{32.5}
\newcommand\InsnBoxMnemonicPosX{36.5}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 mnemonic
% #4 args
\newcommand\DrawInsnOpBType[4]{
	\DrawInsnOpBBox{imm[12\textbar10:5]}{rs2}{rs1}{#1}{imm[4:1\textbar11]}{#2}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:btype]{B-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#3}{#4}\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 mnemonic
% #4 args
\newcommand\DrawInsnOpIType[4]{
	\DrawInsnOpIBox{imm[11:0]}{rs1}{#1}{rd}{#2}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:itype]{I-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#3}{#4}\end{scope}

}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 mnemonic
% #4 args
% #5 rs1/zimm
\newcommand\DrawInsnOpITypeSystem[5]{
	\DrawInsnOpIBox{csr[11:0]}{#5}{#1}{rd}{#2}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:itype]{I-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#3}{#4}\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 func7
% #4 mnemonic
% #5 args
\newcommand\DrawInsnOpITypeShift[5]{
	\DrawInsnOpIFunctBox{#1}{shamt}{rs1}{#2}{rd}{#3}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:itype]{I-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#4}{#5}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 mnemonic
% #4 args
\newcommand\DrawInsnOpSType[4]{
	\DrawInsnOpSBox{imm[11:5]}{rs2}{rs1}{#2}{imm[4:0]}{#1}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:stype]{S-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#3}{#4}\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 func7
% #4 mnemonic
% #5 args
\newcommand\DrawInsnOpRType[5]{
	\DrawInsnOpRBox{#3}{rs2}{rs1}{#2}{rd}{#1}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:rtype]{R-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#4}{#5}\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func3
% #3 mnemonic
% #4 args
%\newcommand\DrawInsnOpFenceType[4]{
%	\DrawInsnBoxRel{31}{28}{}
%	\DrawInsnBoxRel{27}{24}{pred}
%	\DrawInsnBoxRel{23}{20}{succ}
%	\DrawInsnBoxRel{19}{15}{}
%	\DrawInsnBoxRel{14}{12}{}
%	\DrawInsnBoxRel{11}{7}{}
%	\DrawInsnBoxRel{6}{0}{}
%	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#3}{#4}\end{scope}
%
%	\begin{scope}[shift={(31-6,0)}]\DrawBitstringX{#1}\end{scope}
%	\begin{scope}[shift={(31-14,0)}]\DrawBitstringX{#2}\end{scope}
%	\begin{scope}[shift={(31-31,0)}]\DrawBitstringX{0000}\end{scope}
%
%	\begin{scope}[shift={(31-19,0)}]\DrawBitstringX{00000}\end{scope}
%	\begin{scope}[shift={(31-11,0)}]\DrawBitstringX{00000}\end{scope}
%}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 func12
% #3 mnemonic
% #4 args
\newcommand\DrawInsnOpSysType[3]{
	\DrawInsnOpIBinBox{#20000000000000#1}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:itype]{I-type}};
	\draw(\InsnBoxMnemonicPosX,.75) node[right]{\tt #3};
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 mnemonic
% #4 args
\newcommand\DrawInsnOpUType[3]{
	\DrawInsnOpUBox{imm[31:12]}{rd}{#1}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:utype]{U-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#2}{#3}\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% #1 opcode
% #2 mnemonic
% #4 args
\newcommand\DrawInsnOpJType[3]{
	\DrawInsnOpJBox{imm[20\textbar10:1\textbar11\textbar19:12]}{rd}{#1}
	\draw(\InsnBoxTypePosX,.75) node[right]{\hyperref[insnformat:jtype]{J-type}};
	\begin{scope}[shift={(\InsnBoxMnemonicPosX,.75)}]\DrawInsnSrc{#2}{#3}\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\DrawAllInsnOpsU{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpUType{0110111}{\hyperref[insn:lui]{lui}}{rd,\hyperref[imm.u:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpUType{0010111}{\hyperref[insn:auipc]{auipc}}{rd,\hyperref[imm.u:decode]{imm}}\end{scope}
%	\begin{scope}[shift={(0,-1.5)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsJAL{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpJType{1101111}{\hyperref[insn:jal]{jal}}{rd,\hyperref[pcrel.21]{pcrel\_21}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpIType{1100111}{000}{\hyperref[insn:jalr]{jalr}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsBranch{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpBType{1100011}{000}{\hyperref[insn:beq]{beq}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpBType{1100011}{001}{\hyperref[insn:bne]{bne}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}
	\begin{scope}[shift={(0,-3)}]\DrawInsnOpBType{1100011}{100}{\hyperref[insn:blt]{blt}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawInsnOpBType{1100011}{101}{\hyperref[insn:bge]{bge}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}
	\begin{scope}[shift={(0,-6)}]\DrawInsnOpBType{1100011}{110}{\hyperref[insn:bltu]{bltu}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawInsnOpBType{1100011}{111}{\hyperref[insn:bgeu]{bgeu}}{rs1,rs2,\hyperref[pcrel.13]{pcrel\_13}}\end{scope}

	\begin{scope}[shift={(0,-7.5)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsLoad{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpIType{0000011}{000}{\hyperref[insn:lb]{lb}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpIType{0000011}{001}{\hyperref[insn:lh]{lh}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpIType{0000011}{010}{\hyperref[insn:lw]{lw}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawInsnOpIType{0000011}{100}{\hyperref[insn:lbu]{lbu}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawInsnOpIType{0000011}{101}{\hyperref[insn:lhu]{lhu}}{rd,\hyperref[imm.i:decode]{imm}(rs1)}\end{scope}

	\begin{scope}[shift={(0,-6.0)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsStore{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpSType{0100011}{000}{\hyperref[insn:sb]{sb}}{rs2,\hyperref[imm.s:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpSType{0100011}{001}{\hyperref[insn:sh]{sh}}{rs2,\hyperref[imm.s:decode]{imm}(rs1)}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpSType{0100011}{010}{\hyperref[insn:sw]{sw}}{rs2,\hyperref[imm.s:decode]{imm}(rs1)}\end{scope}

	\begin{scope}[shift={(0,-3.0)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsALUImm{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpIType{0010011}{000}{\hyperref[insn:addi]{addi}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpIType{0010011}{010}{\hyperref[insn:slti]{slti}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpIType{0010011}{011}{\hyperref[insn:sltiu]{sltiu}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawInsnOpIType{0010011}{100}{\hyperref[insn:xori]{xori}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawInsnOpIType{0010011}{110}{\hyperref[insn:ori]{ori}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawInsnOpIType{0010011}{111}{\hyperref[insn:andi]{andi}}{rd,rs1,\hyperref[imm.i:decode]{imm}}\end{scope}

	\begin{scope}[shift={(0,-7.5)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsShiftImm{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpITypeShift{0010011}{001}{0000000}{\hyperref[insn:slli]{slli}}{rd,rs1,\hyperref[shamt.i:decode]{shamt}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpITypeShift{0010011}{101}{0000000}{\hyperref[insn:srli]{srli}}{rd,rs1,\hyperref[shamt.i:decode]{shamt}}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpITypeShift{0010011}{101}{0100000}{\hyperref[insn:srai]{srai}}{rd,rs1,\hyperref[shamt.i:decode]{shamt}}\end{scope}

	\begin{scope}[shift={(0,-3.0)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsALUR{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpRType{0110011}{000}{0000000}{\hyperref[insn:add]{add}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpRType{0110011}{000}{0100000}{\hyperref[insn:sub]{sub}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpRType{0110011}{001}{0000000}{\hyperref[insn:sll]{sll}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawInsnOpRType{0110011}{010}{0000000}{\hyperref[insn:slt]{slt}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawInsnOpRType{0110011}{011}{0000000}{\hyperref[insn:sltu]{sltu}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawInsnOpRType{0110011}{100}{0000000}{\hyperref[insn:xor]{xor}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-9.0)}]\DrawInsnOpRType{0110011}{101}{0000000}{\hyperref[insn:srl]{srl}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-10.5)}]\DrawInsnOpRType{0110011}{101}{0100000}{\hyperref[insn:sra]{sra}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-12.0)}]\DrawInsnOpRType{0110011}{110}{0000000}{\hyperref[insn:or]{or}}{rd,rs1,rs2}\end{scope}
	\begin{scope}[shift={(0,-13.5)}]\DrawInsnOpRType{0110011}{111}{0000000}{\hyperref[insn:and]{and}}{rd,rs1,rs2}\end{scope}

	\begin{scope}[shift={(0,-13.5)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsFence{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpFenceType{0001111}{000}{\hyperref[insn:fence]{fence}}{pred,succ}\end{scope}
	%\begin{scope}[shift={(0,0)}]\DrawHexMarkersRel{32}\end{scope}
}
\newcommand\DrawAllInsnOpsSim{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpSysType{1110011}{000000000000}{\hyperref[insn:ecall]{ecall}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpSysType{1110011}{000000000001}{\hyperref[insn:ebreak]{ebreak}}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawHexMarkersRel{32}\end{scope}
}

\newcommand\DrawAllInsnOpsSystem{
	\begin{scope}[shift={(0,0)}]\DrawInsnOpITypeSystem{1110011}{001}{\hyperref[insn:csrrw]{csrrw}}{rd,\hyperref[csr.i:decode]{csr},rs1}{rs1}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawInsnOpITypeSystem{1110011}{010}{\hyperref[insn:csrrs]{csrrs}}{rd,\hyperref[csr.i:decode]{csr},rs1}{rs1}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawInsnOpITypeSystem{1110011}{011}{\hyperref[insn:csrrc]{csrrc}}{rd,\hyperref[csr.i:decode]{csr},rs1}{rs1}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawInsnOpITypeSystem{1110011}{101}{\hyperref[insn:csrrwi]{csrrwi}}{rd,\hyperref[csr.i:decode]{csr},zimm}{zimm[4:0]}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawInsnOpITypeSystem{1110011}{110}{\hyperref[insn:csrrsi]{csrrsi}}{rd,\hyperref[csr.i:decode]{csr},zimm}{zimm[4:0]}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawInsnOpITypeSystem{1110011}{111}{\hyperref[insn:csrrci]{csrrci}}{rd,\hyperref[csr.i:decode]{csr},zimm}{zimm[4:0]}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawHexMarkersRel{32}\end{scope}
}

\newcommand\DrawAllInsnOps{
	\BeginTikzPicture
	\begin{scope}[shift={(0,1.5)}]\DrawInsnBoxCastleRtype\end{scope}
	\begin{scope}[shift={(0,0)}]\DrawAllInsnOpsU\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawAllInsnOpsJAL\end{scope}
	\begin{scope}[shift={(0,-6.2)}]\DrawAllInsnOpsBranch\end{scope}
	\begin{scope}[shift={(0,-15.4)}]\DrawAllInsnOpsLoad\end{scope}
	\begin{scope}[shift={(0,-23.1)}]\DrawAllInsnOpsStore\end{scope}
	\begin{scope}[shift={(0,-27.8)}]\DrawAllInsnOpsALUImm\end{scope}
	\begin{scope}[shift={(0,-37.0)}]\DrawAllInsnOpsShiftImm\end{scope}
	\begin{scope}[shift={(0,-41.7)}]\DrawAllInsnOpsALUR\end{scope}
	\begin{scope}[shift={(0,-57.4)}]\DrawAllInsnOpsSim\end{scope}
	\begin{scope}[shift={(0,-60.6)}]\DrawAllInsnOpsSystem\end{scope}

	\EndTikzPicture
}



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GREEN CARD VERSION OF INSN DIAGRAMS


\newcommand\GCPageWidth{85.8}
%\newcommand\GCPageWidth{86}

% box, insn, desc, rtl
%\newcommand\GCInsnEncodingPosX{0}		% the box, sans-castle
%\newcommand\GCInsnTypePosX{32.6}			% R,I,U,B,...
%\newcommand\GCInsnMnemonicPosX{34}		% the template instruction source
%\newcommand\GCInsnDescriptionPosX{47}	% the long-form description
%\newcommand\GCInsnRTLPosX{64}			% the detailed RTL description

% insn, desc, rtl, box
\newcommand\GCInsnMnemonicPosX{0}		% the template instruction source
\newcommand\GCInsnDescriptionPosX{13}	% the long-form description
\newcommand\GCInsnRTLPosX{29.7}			% the detailed RTL description
\newcommand\GCInsnTypePosX{52.5}			% R,I,U,B,...
\newcommand\GCInsnEncodingPosX{53}		% the box, sans-castle

% #1 opcode
% #2 mnemonic
% #3 args
% #4 description
% #5 RTL
\newcommand\DrawGCInsnOpU[5]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#2}{#3}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {U};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#4};
	\draw(\GCInsnRTLPosX,.6) node[right]{#5};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpUBox{imm[31:12]}{rd}{#1}\end{scope}
}

% #1 opcode
% #2 mnemonic
% #3 args
% #4 description
% #5 RTL
\newcommand\DrawGCInsnOpJ[5]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#2}{#3}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {J};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#4};
	\draw(\GCInsnRTLPosX,.6) node[right]{#5};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpJBox{imm[20\textbar10:1\textbar11\textbar19:12]}{rd}{#1}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 mnemonic
% #4 args
% #5 description
% #6 RTL
\newcommand\DrawGCInsnOpI[6]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#3}{#4}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {I};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#5};
	\draw(\GCInsnRTLPosX,.6) node[right]{#6};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpIBox{imm[11:0]}{rs1}{#1}{rd}{#2}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 funct7
% #4 mnemonic
% #5 args
% #6 description
% #7 RTL
\newcommand\DrawGCInsnOpIShift[7]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#4}{#5}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {I};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#6};
	\draw(\GCInsnRTLPosX,.6) node[right]{#7};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpIFunctBox{#1}{shamt}{rs1}{#2}{rd}{#3}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 mnemonic
% #4 args
% #5 csr
% #6 description
% #7 RTL
\newcommand\DrawGCInsnOpICSR[7]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#3}{#4}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {I};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#6};
	\draw(\GCInsnRTLPosX,.6) node[right]{#7};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpIBox{csr[11:0]}{#5}{#1}{rd}{#2}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 mnemonic
% #4 args
% #5 description
% #6 RTL
\newcommand\DrawGCInsnOpB[6]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#3}{#4}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {B};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#5};
	\draw(\GCInsnRTLPosX,.6) node[right]{#6};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpBBox{imm[12\textbar10:5]}{rs2}{rs1}{#1}{imm[4:1\textbar11]}{#2}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 mnemonic
% #4 args
% #5 description
% #6 RTL
\newcommand\DrawGCInsnOpS[6]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#3}{#4}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {S};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#5};
	\draw(\GCInsnRTLPosX,.6) node[right]{#6};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpBBox{imm[11:5]}{rs2}{rs1}{#1}{imm[4:0]}{#2}\end{scope}
}

% #1 opcode
% #2 funct3
% #3 funct7
% #4 mnemonic
% #5 args
% #6 description
% #7 RTL
\newcommand\DrawGCInsnOpR[7]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#4}{#5}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {R};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#6};
	\draw(\GCInsnRTLPosX,.6) node[right]{#7};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpRBox{#3}{rs2}{rs1}{#2}{rd}{#1}\end{scope}
}

% #1 opcode
% #2 funct7
% #3 mnemonic
% #4 description
\newcommand\DrawGCInsnOpSys[4]{
	\begin{scope}[shift={(\GCInsnMnemonicPosX,.6)}]\DrawInsnSrc{#3}{}\end{scope}
	\draw(\GCInsnTypePosX,.75) node {I};
	\draw(\GCInsnDescriptionPosX,.6) node[right]{#4};
%	\draw(\GCInsnRTLPosX,.6) node[right]{#4};
	\begin{scope}[shift={(\GCInsnEncodingPosX,0)}]\DrawInsnOpIBinBox{#20000000000000#1}\end{scope}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\newcommand\DrawGCAllInsnOpsU{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpU{0110111}{lui}{rd,imm}{Load Upper Immediate}{\tt rd $\leftarrow$ imm\_u, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpU{0010111}{auipc}{rd,imm}{Add Upper Immediate to PC}{\tt rd $\leftarrow$ pc + imm\_u, pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsJAL{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpJ{1101111}{jal}{rd,pcrel\_21}{Jump And Link}{\tt rd $\leftarrow$ pc+4, pc $\leftarrow$ pc+imm\_j}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpI{1100111}{000}{jalr}{rd,imm(rs1)}{Jump And Link Register}{\tt rd $\leftarrow$ pc+4, pc $\leftarrow$ (rs1+imm\_i) $\land$ $\sim$1}\end{scope}
}

\newcommand\DrawGCAllInsnOpsBranch{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpB{1100011}{000}{beq}{rs1,rs2,pcrel\_13}{Branch Equal}{\tt pc $\leftarrow$ pc + ((rs1==rs2) ?\ imm\_b :\ 4)}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpB{1100011}{001}{bne}{rs1,rs2,pcrel\_13}{Branch Not Equal}{\tt pc $\leftarrow$ pc + ((rs1!=rs2) ?\ imm\_b :\ 4)}\end{scope}
	\begin{scope}[shift={(0,-3)}]\DrawGCInsnOpB{1100011}{100}{blt}{rs1,rs2,pcrel\_13}{Branch Less Than}{\tt pc $\leftarrow$ pc + ((rs1<rs2) ?\ imm\_b :\ 4)}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawGCInsnOpB{1100011}{101}{bge}{rs1,rs2,pcrel\_13}{Branch Greater or Equal}{\tt pc $\leftarrow$ pc + ((rs1>=rs2) ?\ imm\_b :\ 4)}\end{scope}
	\begin{scope}[shift={(0,-6)}]\DrawGCInsnOpB{1100011}{110}{bltu}{rs1,rs2,pcrel\_13}{Branch Less Than Unsigned}{\tt pc $\leftarrow$ pc + ((rs1<rs2) ?\ imm\_b :\ 4)}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawGCInsnOpB{1100011}{111}{bgeu}{rs1,rs2,pcrel\_13}{Branch Greater or Equal Unsigned}{\tt pc $\leftarrow$ pc + ((rs1>=rs2) ?\ imm\_b :\ 4)}\end{scope}
}
\newcommand\DrawGCAllInsnOpsLoad{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpI{0000011}{000}{lb}{rd,imm(rs1)}{Load Byte}{\tt rd $\leftarrow$ sx(m8(rs1+imm\_i)), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpI{0000011}{001}{lh}{rd,imm(rs1)}{Load Halfword}{\tt rd $\leftarrow$ sx(m16(rs1+imm\_i)), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpI{0000011}{010}{lw}{rd,imm(rs1)}{Load Word}{\tt rd $\leftarrow$ sx(m32(rs1+imm\_i)), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawGCInsnOpI{0000011}{100}{lbu}{rd,imm(rs1)}{Load Byte Unsigned}{\tt rd $\leftarrow$ zx(m8(rs1+imm\_i)), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawGCInsnOpI{0000011}{101}{lhu}{rd,imm(rs1)}{Load Halfword Unsigned}{\tt rd $\leftarrow$ zx(m16(rs1+imm\_i)), pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsALUImm{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpI{0010011}{000}{addi}{rd,rs1,imm}{Add Immediate}{\tt rd $\leftarrow$ rs1 + imm\_i, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpI{0010011}{010}{slti}{rd,rs1,imm}{Set Less Than Immediate}{\tt rd $\leftarrow$ (rs1 < imm\_i) ?\ 1 :\ 0, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpI{0010011}{011}{sltiu}{rd,rs1,imm}{Set Less Than Immediate Unsigned}{\tt rd $\leftarrow$ (rs1 < imm\_i) ?\ 1 :\ 0, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawGCInsnOpI{0010011}{100}{xori}{rd,rs1,imm}{Exclusive Or Immediate}{\tt rd $\leftarrow$ rs1 $\oplus$ imm\_i, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawGCInsnOpI{0010011}{110}{ori}{rd,rs1,imm}{Or Immediate}{\tt rd $\leftarrow$ rs1 $\lor$ imm\_i, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawGCInsnOpI{0010011}{111}{andi}{rd,rs1,imm}{And Immediate}{\tt rd $\leftarrow$ rs1 $\land$ imm\_i, pc $\leftarrow$ pc+4}\end{scope}
}

% note that the S-Type insns have the same field-format as the B-type
\newcommand\DrawGCAllInsnOpsStore{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpS{0100011}{000}{sb}{rs2,imm(rs1)}{Store Byte}{\tt m8(rs1+imm\_s) $\leftarrow$ rs2[7:0], pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpS{0100011}{001}{sh}{rs2,imm(rs1)}{Store Halfword}{\tt m16(rs1+imm\_s) $\leftarrow$ rs2[15:0], pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpS{0100011}{010}{sw}{rs2,imm(rs1)}{Store Word}{\tt m32(rs1+imm\_s) $\leftarrow$ rs2[31:0], pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsALUR{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpR{0110011}{000}{0000000}{add}{rd,rs1,rs2}{Add}{\tt rd $\leftarrow$ rs1 + rs2, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpR{0110011}{000}{0100000}{sub}{rd,rs1,rs2}{Subtract}{\tt rd $\leftarrow$ rs1 - rs2, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpR{0110011}{001}{0000000}{sll}{rd,rs1,rs2}{Shift Left Logical}{\tt rd $\leftarrow$ rs1 << (rs2\%XLEN), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawGCInsnOpR{0110011}{010}{0000000}{slt}{rd,rs1,rs2}{Set Less Than}{\tt rd $\leftarrow$ (rs1 < rs2) ?\ 1 :\ 0, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawGCInsnOpR{0110011}{011}{0000000}{sltu}{rd,rs1,rs2}{Set Less Than Unsigned}{\tt rd $\leftarrow$ (rs1 < rs2) ?\ 1 :\ 0, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawGCInsnOpR{0110011}{100}{0000000}{xor}{rd,rs1,rs2}{Exclusive Or}{\tt rd $\leftarrow$ rs1 $\oplus$ rs2, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-9.0)}]\DrawGCInsnOpR{0110011}{101}{0000000}{srl}{rd,rs1,rs2}{Shift Right Logical}{\tt rd $\leftarrow$ rs1 >> (rs2\%XLEN), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-10.5)}]\DrawGCInsnOpR{0110011}{101}{0100000}{sra}{rd,rs1,rs2}{Shift Right Arithmetic}{\tt rd $\leftarrow$ rs1 >> (rs2\%XLEN), pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-12.0)}]\DrawGCInsnOpR{0110011}{110}{0000000}{or}{rd,rs1,rs2}{Or}{\tt rd $\leftarrow$ rs1 $\lor$ rs2, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-13.5)}]\DrawGCInsnOpR{0110011}{111}{0000000}{and}{rd,rs1,rs2}{And}{\tt rd $\leftarrow$ rs1 $\land$ rs2, pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsSystem{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpICSR{1110011}{001}{csrrw}{rd,csr,rs1}{rs1}{Atomic Read/Write}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ rs1, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpICSR{1110011}{010}{csrrs}{rd,csr,rs1}{rs1}{Atomic Read and Set}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ csr $\lor$ rs1, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpICSR{1110011}{011}{csrrc}{rd,csr,rs1}{rs1}{Atomic Read and Clear}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ csr $\land$ $\sim$rs1, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-4.5)}]\DrawGCInsnOpICSR{1110011}{101}{csrrwi}{rd,csr,zimm}{zimm[4:0]}{Atomic Read/Write Immediate}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ zimm, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-6.0)}]\DrawGCInsnOpICSR{1110011}{110}{csrrsi}{rd,csr,zimm}{zimm[4:0]}{Atomic Read and Set Immediate}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ csr $\lor$ zimm, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-7.5)}]\DrawGCInsnOpICSR{1110011}{111}{csrrci}{rd,csr,zimm}{zimm[4:0]}{Atomic Read and Clear Immediate}{\tt rd $\leftarrow$ csr, csr $\leftarrow$ csr $\land$ $\sim$zimm, pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsSim{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpSys{1110011}{000000000000}{ecall}{Trap to Debugger}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpSys{1110011}{000000000001}{ebreak}{Trap to Operating System}\end{scope}
}

\newcommand\DrawGCAllInsnOpsShiftImm{
	\begin{scope}[shift={(0,0)}]\DrawGCInsnOpIShift{0010011}{001}{0000000}{slli}{rd,rs1,shamt}{Shift Left Logical Immediate}{\tt rd $\leftarrow$ rs1 << shamt\_i, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-1.5)}]\DrawGCInsnOpIShift{0010011}{101}{0000000}{srli}{rd,rs1,shamt}{Shift Right Logical Immediate}{\tt rd $\leftarrow$ rs1 >> shamt\_i, pc $\leftarrow$ pc+4}\end{scope}
	\begin{scope}[shift={(0,-3.0)}]\DrawGCInsnOpIShift{0010011}{101}{0100000}{srai}{rd,rs1,shamt}{Shift Right Arithmetic Immediate}{\tt rd $\leftarrow$ rs1 >> shamt\_i, pc $\leftarrow$ pc+4}\end{scope}
}

\newcommand\DrawGCAllInsnOpsPseudo{
	\draw(0,    0) node[right]{p1};
	\draw(0, -1.5) node[right]{p1};
	\draw(0, -3.0) node[right]{p1};
	\draw(0, -4.5) node[right]{p1};
	\draw(0, -6.0) node[right]{p1};
	\draw(0, -7.5) node[right]{p1};
	\draw(0, -9.0) node[right]{p1};
	\draw(0,-10.5) node[right]{p1};
	\draw(0,-12.0) node[right]{p1};
	\draw(0,-13.5) node[right]{p1};
	\draw(0,-15.0) node[right]{p1};
	\draw(0,-16.5) node[right]{p1};
	\draw(0,-18.0) node[right]{p1};
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% a color to hilight the rows on the card
\definecolor{GCBarColorBG}{RGB}{200,255,200}
\definecolor{GCBarColorFG}{RGB}{128,220,128}
\definecolor{GCSlugColorFG}{RGB}{20,100,20}

\newcommand\DrawGCAllInsnOps{
	\BeginTikzPicture

	% draw color graybars
	\foreach \y in {1.5,-7.5,...,-66}%
		\draw [draw=GCBarColorFG,fill=GCBarColorBG,thick] (0,\y) rectangle (\GCPageWidth,\y-4.5);

	% draw some nybble-slugs
	\foreach \y in {-3,-7.5,...,-66}%
		\foreach \x in {4,8,...,30}%
			\draw [line width=.5mm,draw=GCSlugColorFG] (\x+.5+\GCInsnEncodingPosX,\y) -- (\x+.5+\GCInsnEncodingPosX, \y+.3);%

	\begin{scope}[shift={(\GCInsnEncodingPosX,1.5)}]\DrawInsnBoxCastleRtype\end{scope}

	% add some field names in the castle
	\begin{scope}[shift={(\GCInsnEncodingPosX,1.5)}]
		\node at (4,1.25) {\small funct7};
		\node at (19,1.25) {\small funct3};
		\node at (29,1.25) {\small opcode};
	\end{scope}

	\draw node at (\GCInsnMnemonicPosX+6,2.75) {\small Instruction};
	\draw node at (\GCInsnDescriptionPosX+8,2.75) {\small Description};
	\draw node at (\GCInsnRTLPosX+12,2.75) {\small Operation};
	\draw node at (\GCInsnTypePosX,2.75) {\small Type};

	%\node [draw, rotate=90] at (0,60) {\small RV32I Reference Card (\href{https://github.com/johnwinans/rvalp}{https://github.com/johnwinans/rvalp})};
	%\draw node[rotate=90,right] at (\GCPageWidth+.7,-66) {\small RV32I Reference Card};
	%\draw node[rotate=90,left] at (\GCPageWidth+.7,1.5) {\small https://github.com/johnwinans/rvalp};
	\draw node[rotate=90,right] at (-.7,-66) {\small RV32I Reference Card};
	\draw node[rotate=90,left] at (-.7,1.5) {\small https://github.com/johnwinans/rvalp};


	\begin{scope}[shift={(0,0)}]\DrawGCAllInsnOpsU\end{scope}
	\begin{scope}[shift={(0,-3)}]\DrawGCAllInsnOpsJAL\end{scope}
	\begin{scope}[shift={(0,-6)}]\DrawGCAllInsnOpsBranch\end{scope}
	\begin{scope}[shift={(0,-15)}]\DrawGCAllInsnOpsLoad\end{scope}
	\begin{scope}[shift={(0,-22.5)}]\DrawGCAllInsnOpsStore\end{scope}
	\begin{scope}[shift={(0,-27)}]\DrawGCAllInsnOpsALUImm\end{scope}
	\begin{scope}[shift={(0,-36)}]\DrawGCAllInsnOpsShiftImm\end{scope}
	\begin{scope}[shift={(0,-40.5)}]\DrawGCAllInsnOpsALUR\end{scope}
	\begin{scope}[shift={(0,-55.5)}]\DrawGCAllInsnOpsSim\end{scope}
	\begin{scope}[shift={(0,-58.5)}]\DrawGCAllInsnOpsSystem\end{scope}

	% stub in some space for pseudo-instruictions to see what it might look like
	%\begin{scope}[shift={(0,-67)}]\DrawGCAllInsnOpsPseudo\end{scope}

	% show markers to indicate where to fold it  
	\draw [line width=.1mm,draw=GCSlugColorFG] (29.5,1) -- (29.5, 1.5);
	\draw [line width=.1mm,draw=GCSlugColorFG] (29.5,-65.5) -- (29.5, -66);

	\EndTikzPicture
}





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\InsnBoxFieldWidthArrowVskip{.5}
\newcommand\InsnBoxFieldWidthArrowHskip{.05}

% #1 MSB position
% #2 LSB position
\newcommand\InsnBoxFieldWidthArrow[2]{
	\pgfmathsetmacro\leftpos{int(31-#1)}		% Calculate the left end position
	\pgfmathsetmacro\wid{int(#1-#2+1)}			% calculate the width
	\begin{scope}[shift={(\leftpos,-\InsnBoxFieldWidthArrowVskip)}]	% Move to left end of arrow & below origin
    	\pgfmathsetmacro\result{\wid*.5+.5}		% the center position
    	\node at (\result,0) {\tiny\wid};		% draw the size number below the box

		\ifthenelse{\wid > 9}					% make 1-9 narrower than 10-99
		{ \pgfmathsetmacro\Inset{0.4} }
		{ 
			\ifthenelse{\wid > 1} 				% make 1 narrower than 2-9
			{ \pgfmathsetmacro\Inset{0.25} }
			{ \pgfmathsetmacro\Inset{0.15} }
		}

		% arrowsInsnBoxFieldWidthArrowHskip
    	\draw[->] (\result+\Inset,0) -- (\wid+.5-\InsnBoxFieldWidthArrowHskip,0);	% arrow to the right
    	\draw[->] (\result-\Inset,0) -- (.5+\InsnBoxFieldWidthArrowHskip,0);		% arrow to the left

		\pgfmathsetmacro\x{.5}
		\pgfmathsetmacro\y{\InsnBoxFieldWidthArrowVskip}
		% vertical bars at the ends of the arrows
    	\draw[-] (\x,\y) -- (\x,-\y*.5);	
		\pgfmathsetmacro\x{(\wid+.5}
    	\draw[-] (\x,\y) -- (\x,-\y*.5);	

	\end{scope}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\BitBoxArrowTailInset{-.9}
\newcommand\BitBoxArrowHeadInset{-16.7-\BitBoxArrowTailInset}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% special case for R type instructions for consistency
\newcommand\InsnOpRTypeDecoding{

	\begin{scope}[shift={(0,-1.5)}]
	\DrawInsnTypeR{abcdefghijklmnopqrstuvwxy1101111}
	\end{scope}
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand\InsnOpJTypeDecoding{

	\begin{scope}[shift={(0,-1.5)}]

	\DrawInsnTypeJ{abcdefghijklmnopqrst001111101111}

	\pgfmathsetmacro\ArrowNorth{\BitBoxArrowTailInset}
	\pgfmathsetmacro\ArrowSouth{\BitBoxArrowHeadInset}

	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](1,\ArrowSouth);	% 20
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](2,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](3,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](4,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](5,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](6,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](7,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](8,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](9,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](10,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](11,\ArrowSouth);	% sign extend

	\draw[blue,->](1,\ArrowNorth)to[out=270,in=90](12,\ArrowSouth);		% 20
	\draw[blue,->](13,\ArrowNorth)to[out=270,in=90](13,\ArrowSouth);	% 19
	\draw[blue,->](14,\ArrowNorth)to[out=270,in=90](14,\ArrowSouth);	% 18
	\draw[blue,->](15,\ArrowNorth)to[out=270,in=90](15,\ArrowSouth);	% 17
	\draw[blue,->](16,\ArrowNorth)to[out=270,in=90](16,\ArrowSouth);	% 16
	\draw[blue,->](17,\ArrowNorth)to[out=270,in=90](17,\ArrowSouth);	% 15
	\draw[blue,->](18,\ArrowNorth)to[out=270,in=90](18,\ArrowSouth);	% 14
	\draw[blue,->](19,\ArrowNorth)to[out=270,in=90](19,\ArrowSouth);	% 13
	\draw[blue,->](20,\ArrowNorth)to[out=270,in=90](20,\ArrowSouth);	% 12

	\draw[blue,->](12,\ArrowNorth)to[out=270,in=90](21,\ArrowSouth);	% 11

	\draw[blue,->](2,\ArrowNorth)to[out=270,in=90](22,\ArrowSouth);		% 10
	\draw[blue,->](3,\ArrowNorth)to[out=270,in=90](23,\ArrowSouth);		% 9
	\draw[blue,->](4,\ArrowNorth)to[out=270,in=90](24,\ArrowSouth);		% 8
	\draw[blue,->](5,\ArrowNorth)to[out=270,in=90](25,\ArrowSouth);		% 7
	\draw[blue,->](6,\ArrowNorth)to[out=270,in=90](26,\ArrowSouth);		% 6
	\draw[blue,->](7,\ArrowNorth)to[out=270,in=90](27,\ArrowSouth);		% 5
	\draw[blue,->](8,\ArrowNorth)to[out=270,in=90](28,\ArrowSouth);		% 4
	\draw[blue,->](9,\ArrowNorth)to[out=270,in=90](29,\ArrowSouth);		% 3
	\draw[blue,->](10,\ArrowNorth)to[out=270,in=90](30,\ArrowSouth);	% 2
	\draw[blue,->](11,\ArrowNorth)to[out=270,in=90](31,\ArrowSouth);	% 1

	\draw[red,->](34,\ArrowSouth+5)to[out=180,in=90](32,\ArrowSouth);	% 0 (special case)
	\node at (34.5,\ArrowSouth+5) {0};
%	\draw[blue,->](32,\ArrowSouth+1)to[out=270,in=90](32,\ArrowSouth);	% 0 (special case)
%	\node at (32,\ArrowSouth+2) {0};

	\begin{scope}[shift={(0,0)}]\DrawHexMarkersRel{32}\end{scope}
	\end{scope}

	\begin{scope}[shift={(0,-19.75)}]
		\begin{scope}[shift={(0,1.5)}]
			\DrawInsnBoxCastle{31}{21}
			\DrawInsnBoxCastle{20}{20}
			\DrawInsnBoxCastle{19}{12}
			\DrawInsnBoxCastle{11}{11}
			\DrawInsnBoxCastle{10}{1}
			\DrawInsnBoxCastle{0}{0}
		\end{scope}
		\DrawInsnBoxRel{31}{0}{}
		\draw(33,.5) node[text width = 10, text height = 1, right]{imm\_j};

		\begin{scope}[shift={(0,0)}]\DrawBitstringX{aaaaaaaaaaaamnopqrstlbcdefghijk0}\end{scope}
		\begin{scope}[shift={(0,0)}]\DrawHexMarkersRel{32}\end{scope}

		\InsnBoxFieldWidthArrow{31}{21}
		\InsnBoxFieldWidthArrow{20}{20}
		\InsnBoxFieldWidthArrow{19}{12}
		\InsnBoxFieldWidthArrow{11}{11}
		\InsnBoxFieldWidthArrow{10}{1}
		\InsnBoxFieldWidthArrow{0}{0}
	\end{scope}
}

\newcommand\DrawInsnOpJTypeDecoding{
	\BeginTikzPicture
	\InsnOpJTypeDecoding
	\EndTikzPicture
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand\InsnOpBTypeDecoding{

	\begin{scope}[shift={(0,-1.5)}]

	\DrawInsnTypeB{abcdefg0111100011000uvwxy1100011}

	\pgfmathsetmacro\ArrowNorth{\BitBoxArrowTailInset}
	\pgfmathsetmacro\ArrowSouth{\BitBoxArrowHeadInset}

	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](1,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](2,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](3,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](4,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](5,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](6,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](7,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](8,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](9,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](10,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](11,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](12,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](13,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](14,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](15,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](16,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](17,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](18,\ArrowSouth);	% sign extend
	\draw[red,->](1,\ArrowNorth)to[out=270,in=90](19,\ArrowSouth);	% sign extend

	\draw[blue,->](1,\ArrowNorth)to[out=270,in=90](20,\ArrowSouth);		% 12

	\draw[blue,->](25,\ArrowNorth)to[out=270,in=90](21,\ArrowSouth);	% 11

	\draw[blue,->](2,\ArrowNorth)to[out=270,in=90](22,\ArrowSouth);		% 10
	\draw[blue,->](3,\ArrowNorth)to[out=270,in=90](23,\ArrowSouth);		% 9
	\draw[blue,->](4,\ArrowNorth)to[out=270,in=90](24,\ArrowSouth);		% 8
	\draw[blue,->](5,\ArrowNorth)to[out=270,in=90](25,\ArrowSouth);		% 7
	\draw[blue,->](6,\ArrowNorth)to[out=270,in=90](26,\ArrowSouth);		% 6
	\draw[blue,->](7,\ArrowNorth)to[out=270,in=90](27,\ArrowSouth);		% 5

	\draw[blue,->](21,\ArrowNorth)to[out=270,in=90](28,\ArrowSouth);	% 4
	\draw[blue,->](22,\ArrowNorth)to[out=270,in=90](29,\ArrowSouth);	% 3
	\draw[blue,->](23,\ArrowNorth)to[out=270,in=90](30,\ArrowSouth);	% 2
	\draw[blue,->](24,\ArrowNorth)to[out=270,in=90](31,\ArrowSouth);	% 1

	\draw[red,->](34,\ArrowSouth+5)to[out=180,in=90](32,\ArrowSouth);	% 0 (special case)
	\node at (34.5,\ArrowSouth+5) {0};
%	\draw[blue,->](32,\ArrowSouth+1)to[out=270,in=90](32,\ArrowSouth);	% 0 (special case)
%	\node at (32,\ArrowSouth+2) {0};

	\begin{scope}[shift={(0,0)}]\DrawHexMarkersRel{32}\end{scope}
	\end{scope}

	\begin{scope}[shift={(0,-19.75)}]
		\begin{scope}[shift={(0,1.5)}]
		
Download .txt
gitextract_vt1ez9jz/

├── .gitignore
├── LICENSE
├── Make.rules
├── Makefile
├── README.md
├── book/
│   ├── .gitignore
│   ├── Makefile
│   ├── amodes/
│   │   └── chapter.tex
│   ├── ascii/
│   │   └── chapter.tex
│   ├── bibliography.bib
│   ├── binary/
│   │   ├── chapter.tex
│   │   └── rvddt_memdump.out
│   ├── colors.tex
│   ├── copyright/
│   │   └── chapter.tex
│   ├── elements/
│   │   ├── chapter.tex
│   │   ├── zero4regs.S
│   │   └── zero4regs.out
│   ├── float/
│   │   ├── chapter.tex
│   │   ├── cleandecimal.c
│   │   ├── cleandecimal.out
│   │   ├── erroraccumulation.c
│   │   ├── erroraccumulation.out
│   │   ├── errorcompensation.c
│   │   ├── errorcompensation.out
│   │   ├── powersoftwo.c
│   │   └── powersoftwo.out
│   ├── glossary.tex
│   ├── insnformats.tex
│   ├── insnsummary/
│   │   └── chapter.tex
│   ├── install/
│   │   └── chapter.tex
│   ├── intro/
│   │   └── chapter.tex
│   ├── license/
│   │   └── chapter.tex
│   ├── preamble.tex
│   ├── preface/
│   │   └── chapter.tex
│   ├── priv/
│   │   └── chapter.tex
│   ├── programs/
│   │   ├── chapter.tex
│   │   └── src/
│   │       ├── .gitignore
│   │       ├── Make.rules
│   │       ├── Makefile
│   │       └── mvzero/
│   │           ├── .gitignore
│   │           ├── Makefile
│   │           ├── mv.S
│   │           ├── mv.lst
│   │           ├── mv.out
│   │           └── run.sh
│   ├── refcard/
│   │   └── chapter.tex
│   ├── rv32/
│   │   ├── base.tex
│   │   ├── chapter.tex
│   │   └── insn/
│   │       └── lui.tex
│   ├── rv32m/
│   │   └── chapter.tex
│   ├── rvalp.tex
│   └── toolchain/
│       └── chapter.tex
└── texlib/
    ├── ENote.sty
    ├── MyFigs.sty
    ├── MyVerbatim.sty
    └── index.ist
Download .txt
SYMBOL INDEX (4 symbols across 4 files)

FILE: book/float/cleandecimal.c
  function main (line 10) | int main()

FILE: book/float/erroraccumulation.c
  function main (line 10) | int main()

FILE: book/float/errorcompensation.c
  function main (line 10) | int main()

FILE: book/float/powersoftwo.c
  function main (line 10) | int main()
Condensed preview — 56 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (425K chars).
[
  {
    "path": ".gitignore",
    "chars": 6,
    "preview": "*.swp\n"
  },
  {
    "path": "LICENSE",
    "chars": 18647,
    "preview": "Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons"
  },
  {
    "path": "Make.rules",
    "chars": 1614,
    "preview": "TEXLIB=$(TOP)/texlib\n\n# BEFORE including this file, you must define: TEXPATH\n\n\n# This only works if there is at least on"
  },
  {
    "path": "Makefile",
    "chars": 47,
    "preview": "TOP=.\n\nSUBDIRS=book\n\ninclude $(TOP)/Make.rules\n"
  },
  {
    "path": "README.md",
    "chars": 1847,
    "preview": "# rvalp\n\nRISC-V Assembly Language Programming\n\nThis is an attempt to create a book on RISC-V programming in assembly lan"
  },
  {
    "path": "book/.gitignore",
    "chars": 200,
    "preview": "rvalp.aux\nrvalp.brf\nrvalp.idx\nrvalp.ilg\nrvalp.ind\nrvalp.lof\nrvalp.log\nrvalp.pdf\nrvalp.toc\nrvalp.bbl\nrvalp.blg\nrvalp.out\n"
  },
  {
    "path": "book/Makefile",
    "chars": 377,
    "preview": "SUBDIRS=\n#\tprograms/src\n\nTOP=..\ninclude $(TOP)/Make.rules\n\nTEXPATH=float:intro:rv32:copyright:license:elements:binary:pr"
  },
  {
    "path": "book/amodes/chapter.tex",
    "chars": 542,
    "preview": "\\chapter{Addressing Modes}\n\n\nA box showing +/- 2KB regions for \\reg{gp} addressing with \nLB, LBU, SB, LH, LHU, SH, LW, a"
  },
  {
    "path": "book/ascii/chapter.tex",
    "chars": 7504,
    "preview": "\\chapter{The ASCII Character Set}\n\\label{chapter:ascii}\n\\index{ASCII}\n\nA slightly abridged version of the Linux ``ASCII'"
  },
  {
    "path": "book/bibliography.bib",
    "chars": 5595,
    "preview": "@string{IETF=\"Internet Engineering Task Force\"}\n\n@manual{rvismv1v22:2017,\n\ttitle        = \"\\href{https://github.com/risc"
  },
  {
    "path": "book/binary/chapter.tex",
    "chars": 57471,
    "preview": "\\chapter{Numbers and Storage Systems}\n\\label{chapter:numbers}\n\nThis chapter discusses how data are represented and store"
  },
  {
    "path": "book/binary/rvddt_memdump.out",
    "chars": 1282,
    "preview": "ddt> d 0x00002600\n 00002600: 93 05 00 00 13 06 00 00  93 06 00 00 13 07 00 00 *................*\n 00002610: 93 07 00 00 "
  },
  {
    "path": "book/colors.tex",
    "chars": 221,
    "preview": "% These are color styles used in the figures in this book.\n\\definecolor{c_lightblue}{HTML}{B0E0FF}\n\\definecolor{c_lightr"
  },
  {
    "path": "book/copyright/chapter.tex",
    "chars": 973,
    "preview": "\\thispagestyle{plain}\n\nCopyright \\copyright\\ 2018, 2019, 2020 John Winans \n\nThis document is made available under a Crea"
  },
  {
    "path": "book/elements/chapter.tex",
    "chars": 8107,
    "preview": "\\chapter{The Elements of a Assembly Language Program}\n\\label{chapter:elements}\n\n\\section{Assembly Language Statements}\n\n"
  },
  {
    "path": "book/elements/zero4regs.S",
    "chars": 287,
    "preview": "\t.text\t\t\t\t\t# put this into the text section\n\t.align\t2\t\t\t\t# align to 2^2\n\t.globl\t_start\n_start:\n\taddi    x28, x0, 0\t\t# se"
  },
  {
    "path": "book/elements/zero4regs.out",
    "chars": 2169,
    "preview": "[winans@w510 src]$ ./rvddt -f ../examples/load4regs.bin\nLoading '../examples/load4regs.bin' to 0x0\nddt> t4\n   x0: 000000"
  },
  {
    "path": "book/float/chapter.tex",
    "chars": 10442,
    "preview": "\\chapter{Floating Point Numbers}\n\\label{chapter:floatingpoint}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
  },
  {
    "path": "book/float/cleandecimal.c",
    "chars": 372,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nunion floatbin\n{\n    unsigned int    i;\n    float           "
  },
  {
    "path": "book/float/cleandecimal.out",
    "chars": 1014,
    "preview": "            10.0000000000 = 41200000                -10.0000000000 = c1200000\n           100.0000000000 = 42c80000      "
  },
  {
    "path": "book/float/erroraccumulation.c",
    "chars": 354,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nunion floatbin\n{\n    unsigned int    i;\n    float           "
  },
  {
    "path": "book/float/erroraccumulation.out",
    "chars": 1235,
    "preview": "0.1000000015 = 3dcccccd                 -0.1000000015 = bdcccccd\n0.2000000030 = 3e4ccccd                 -0.2000000030 ="
  },
  {
    "path": "book/float/errorcompensation.c",
    "chars": 397,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nunion floatbin \n{\n    unsigned int    i;\n    float          "
  },
  {
    "path": "book/float/errorcompensation.out",
    "chars": 1300,
    "preview": "0.1000000015 = 3dcccccd                 -0.1000000015 = bdcccccd\n0.2000000030 = 3e4ccccd                 -0.2000000030 ="
  },
  {
    "path": "book/float/powersoftwo.c",
    "chars": 380,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nunion floatbin\n{\n    unsigned int    i;\n    float           "
  },
  {
    "path": "book/float/powersoftwo.out",
    "chars": 650,
    "preview": "1.0000000000 = 3f800000                 -1.0000000000 = bf800000\n0.5000000000 = 3f000000                 -0.5000000000 ="
  },
  {
    "path": "book/glossary.tex",
    "chars": 5876,
    "preview": "\\newglossaryentry{latex}\n{\n    name=LaTeX,\n    description={Is a mark up language specially suited\n    \tfor scientific d"
  },
  {
    "path": "book/insnformats.tex",
    "chars": 85703,
    "preview": "\n\\def\\SignBoxCornerRadius{.75mm}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand\\BeginTikzPic"
  },
  {
    "path": "book/insnsummary/chapter.tex",
    "chars": 8141,
    "preview": "\\chapter{Instruction Set Summary}\n\n\\enote{Once the RV32I section is re-factored, it may end up turning into this.}\n\n\\TDr"
  },
  {
    "path": "book/install/chapter.tex",
    "chars": 5832,
    "preview": "\\chapter{Installing a RISC-V Toolchain}\n\\label{chapter:install}\n\nAll of the software presented in this text was assemble"
  },
  {
    "path": "book/intro/chapter.tex",
    "chars": 14684,
    "preview": "\\chapter{Introduction}\n\\label{chapter:Introduction}\n\nAt its core, a digital computer has at least one \\acrfull{cpu}.  A\n"
  },
  {
    "path": "book/license/chapter.tex",
    "chars": 19550,
    "preview": "\\chapter{Attribution 4.0 International}\n\\label{license}\n\n\\begin{scriptsize}\n\nCreative Commons Corporation (\"Creative Com"
  },
  {
    "path": "book/preamble.tex",
    "chars": 8173,
    "preview": "\n\\oddsidemargin=.82in\n%\\evensidemargin=1.82in\n\\evensidemargin=1.72in\n\n%\\topmargin=-.5in\n\\headheight=12pt\n\\headsep=20pt\n\n"
  },
  {
    "path": "book/preface/chapter.tex",
    "chars": 2562,
    "preview": "\\chapter{Preface}\n\\label{chapter:Preface}\n\nI set out to write this book because I couldn't find it in a single volume el"
  },
  {
    "path": "book/priv/chapter.tex",
    "chars": 7675,
    "preview": "\\chapter{Privileged Instructions}\n\\label{chapter:privileged}\n\n\\section{Introduction}\n\n{\\em XXX NOTE: This is a first dra"
  },
  {
    "path": "book/programs/chapter.tex",
    "chars": 22093,
    "preview": "\\chapter{Writing RISC-V Programs}\n\n\\enote{Introduce the ISA register names and aliases in here?}%\nThis chapter introduce"
  },
  {
    "path": "book/programs/src/.gitignore",
    "chars": 6,
    "preview": "*.bin\n"
  },
  {
    "path": "book/programs/src/Make.rules",
    "chars": 891,
    "preview": "\nARCH=riscv32-unknown-elf\n\nCC=$(ARCH)-gcc\nAS=$(ARCH)-as\nLD=$(ARCH)-ld\nOBJCOPY=$(ARCH)-objcopy\nOBJDUMP=$(ARCH)-objdump\nSI"
  },
  {
    "path": "book/programs/src/Makefile",
    "chars": 77,
    "preview": "\nSUBDIRS=\\\n\tnop\\\n\tli\\\n\tmv\\\n\tmvzero\\\n\tebreak\n\nTOP=.\ninclude $(TOP)/Make.rules\n"
  },
  {
    "path": "book/programs/src/mvzero/.gitignore",
    "chars": 3,
    "preview": "mv\n"
  },
  {
    "path": "book/programs/src/mvzero/Makefile",
    "chars": 200,
    "preview": "\nPROG=mv\n\nall:: $(PROG).out $(PROG).lst\n\n$(PROG).out:: $(PROG).bin\n\t./run.sh > $@ 2>&1\n\n$(PROG).bin:: $(PROG)\n\nclean::\n\t"
  },
  {
    "path": "book/programs/src/mvzero/mv.S",
    "chars": 137,
    "preview": "\t.text\t\t\t\t# put this into the text section\n\t.align\t2\t\t\t# align to a multiple of 4\n\t.globl\t_start\n\n_start:\n\tmv\t\tt3, x0\t\t#"
  },
  {
    "path": "book/programs/src/mvzero/mv.lst",
    "chars": 152,
    "preview": "mv:     file format elf32-littleriscv\nDisassembly of section .text:\n00000000 <_start>:\n   0:\t00000e13          \tli\tt3,0\n"
  },
  {
    "path": "book/programs/src/mvzero/mv.out",
    "chars": 1500,
    "preview": "$ rvddt -f mv.bin\nsp initialized to top of memory: 0x0000fff0\nLoading 'mv.bin' to 0x0\nThis is rvddt.  Enter ? for help.\n"
  },
  {
    "path": "book/programs/src/mvzero/run.sh",
    "chars": 83,
    "preview": "prompt=\"$\" \ncmd=\"rvddt -f mv.bin\"\necho \"$prompt $cmd\"\n$cmd <<!\na\nd 0 16\nt 0 1000\n!\n"
  },
  {
    "path": "book/refcard/chapter.tex",
    "chars": 10162,
    "preview": "\\chapter{RV32I Reference Cards}%\n\\nolinenumbers%\n\\vspace{-1cm}\n{\\small%\n\\begin{tabular}{|ll|c|l|l|}\n\\hline\n\\multicolumn{"
  },
  {
    "path": "book/rv32/base.tex",
    "chars": 25977,
    "preview": "\n\\section{RV32I Base Instruction Set}\n\\index{RV32I}\n\n\\enote{Migrate all te details into the programming chapter and\nredu"
  },
  {
    "path": "book/rv32/chapter.tex",
    "chars": 44692,
    "preview": "\n\\newcommand\\instructionHeader[1]{{\\large\\tt \\string#1}}\n\n\\chapter{RV32 Machine Instructions}\n\\label{chapter:RV32}\n\\inde"
  },
  {
    "path": "book/rv32/insn/lui.tex",
    "chars": 1017,
    "preview": "\\DrawInsnTypeUPicture{LUI t0, 3}{00000000000000000011001010110111}\n\n\\begin{verbatim}\n00010074: 000032b7  lui     x5, 0x3"
  },
  {
    "path": "book/rv32m/chapter.tex",
    "chars": 2048,
    "preview": "\\chapter{RV32M Standard Extension}\n\\label{chapter:rv32m}\n\\index{RV32M}\n\n\\section{Introduction}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%"
  },
  {
    "path": "book/rvalp.tex",
    "chars": 2381,
    "preview": "%\\documentclass[oneside,draft,letterpaper]{book}\n%\\documentclass[letterpaper]{book}\n\\documentclass[oneside,letterpaper]{"
  },
  {
    "path": "book/toolchain/chapter.tex",
    "chars": 1115,
    "preview": "\\chapter{Using The RISC-V GNU Toolchain}\n\nThis chapter discusses using the GNU toolchain elements to\nexperiment with the"
  },
  {
    "path": "texlib/ENote.sty",
    "chars": 1449,
    "preview": "\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{ENote}\n        [2002/03/23 v1\n    John Winans's editor notes facilities%\n     "
  },
  {
    "path": "texlib/MyFigs.sty",
    "chars": 1384,
    "preview": "\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{MyFigs}\n        [2002/03/23 v1\n    John Winans's graphic figure includer facil"
  },
  {
    "path": "texlib/MyVerbatim.sty",
    "chars": 3640,
    "preview": "\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{MyVerbatim}\n        [2002/03/23 v1\n    John Winans's verbatim facilities%\n    "
  },
  {
    "path": "texlib/index.ist",
    "chars": 179,
    "preview": "% Style for makeindex\n% This style simply adds a bolded letter for each part of the alphabet\nheading_prefix\t\"{\\\\bfseries"
  }
]

About this extraction

This page contains the full source code of the johnwinans/rvalp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 56 files (391.0 KB), approximately 129.8k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!