Jump to content

Photo

GCC for the TI


302 replies to this topic

#1 insomnia OFFLINE  

insomnia

    Star Raider

  • 67 posts
  • Location:Pittsburgh, PA

Posted Wed Jun 9, 2010 11:46 PM

Hey everybody,

I've been lurking here for a while, and thought this group might be interested in a port I've made of GCC and the GNU Binutils tools (gas, ar, ln, etc.).

I've done some testing with simple programs, and things seem stable enough for other people to play with the compiler if they're interested. Since my development machine runs Linux, it seems like the best way to distribute the required patches is via source. I can provide the binaries, but since it seems like everybody here runs Windows, that might not be too useful. But if I'm wrong, let me know.

The compiler outputs are ELF format object files, so I've made tools to convert to cartridge and EA5 binary formats for the TI. The intermediary assembly files are TI compatible, so they could be fed into your assembler of choice if you prefer. GAS also uses TI compatible files, but provides some useful exensions (long label names being one of the more important ones).

I'm still putting a development site together at insomnialabs.blogspot.com, which has links to the GCC and Binutils patches, but other tools I have are not yet available for download (I'm working on it..).

I'm attaching a "hello world" program as a teaser using GCC, GAS, LN, and the elf-to-cart converter.

So, example code (included in the attachment):
 


#define VDP_READ_DATA_REG (*(volatile char*)0x8800)

#define VDP_WRITE_DATA_REG (*(volatile char*)0x8C00)

#define VDP_ADDRESS_REG (*(volatile char*)0x8C02)



#define VDP_READ_FLAG 0x00

#define VDP_WRITE_FLAG 0x40

#define VDP_REG_FLAG 0x80





static void vdp_copy_from_sys(int index, char* src, int size)

{

volatile char* end = src + size;

VDP_ADDRESS_REG = index | VDP_WRITE_FLAG;

VDP_ADDRESS_REG = (char)(index >> ;



while(src != end)

VDP_WRITE_DATA_REG = *src++;

}





void main()

{

// 12345678901234

vdp_copy_from_sys(0, "HELLO WORLD!",12);

vdp_copy_from_sys(32, "THIS IS LINE 2", 14);

while(1);

}

The resulting code after -O2 optimization:
 


pseg

LC0

text "HELLO WORLD!"

byte 0

even

LC1

text "THIS IS LINE 2"

byte 0

even



def main

main

li r1, 64 * 256

movb r1, @-29694

clr r1

movb r1, @-29694

li r1, LC0

L2

movb *r1+, r2

movb r2, @-29696

ci r1, LC0+12

jne L2

li r1, 96 * 256

movb r1, @-29694

clr r1

movb r1, @-29694

li r1, LC1

L3

movb *r1+, r2

movb r2, @-29696

ci r1, LC1+14

jne L3

L8

jmp L8

I was originally doing the port as a convenience for myself, so things may not be as well documented as they should. Let me know what you think.

 

 

--------------------------------

Updated Aug 18, 2014:

 

The build information and other handy info was scattered throughout this thread, making it hard to get the latest stuff. I'll make sure to keep this post updated to make things easier to find.

 

Manually building Binutils:

  (from top level of source tree)

  $ patch -1 < BINUTILS_PATCHFILE

  $ ./configure --target tms9900 --prefix INSTALL_DIRECTORY --disable-build-warnings
  $ make all
  $ make install
 

Manually building GCC:

  (from top level of source tree)

  $ patch -1 < GCC_PATCHFILE

  $ mkdir build
  $ cd build
  $ ../configure --prefix INSTALL_DIRECTORY --target=tms9900 --enable-languages=c
  $ make all-gcc all-target-libgcc
  $ make install
 

Building Binutils and GCC using install script:

  $ install.sh INSTALL_DIRECTORY

 

 

Binutils Changelog

-------------------------

1.5
   Released 2013-05-01
   Added more informative syntax error messages
   Fixed values like ">6000" in strings being mangled
   Confirm support for named sections

1.6
   Released 2014-10-10
   Added support for numeric registers
   Correct handling of comments
   Added support for dwarf debugging information
 

1.7

  Released 2014-12-04

  Restored ability to have label and code on same line
  Minor code cleanup
 

 

GCC Changelog

-----------------------

1.8
  Released 2013-05-01
  Fixed R11 restoration in epilogue being dropped by DCE
  Added support for named sections
  Removed support for directly zeroing byte memory, was buggy in some memories
 

1.9
  Released 2014-10-10
  Changed order of jumps for less-than-or-equal tests to improve performance
  Fixed several integer type conversion bugs
  Corrected handling of variable shift by zero bits
  Fixed signed division
  Added support for dwarf debugging information

 

1.10

  Released 2014-12-04

  Prevented use of R0 as an address base
  Moved jump tables into text segment to free up space for variables
  Fixed bug which put initialized data in bss section
  Fixed negation of byte quantities
  Minor code cleanup
 

1.11
  Released 2015-06-14
  Fixed compilation error due to missing FILE macro in tms9900.h
  Some instruction sizes were defined incorrectly, causing assembly errors
  Fixed conditional jump displacement limits, they were too small.
  Added compilation pass to add needed SWPB instructions.
 

1.12
  Released 2015-08-16
  Fixed bug when dividing by constant value
  Improved type testing for instruction arguments
  Added text to "--version" flag output to show patch version.
 

1.13

  Released 2016-11-23
  Added compilation pass to better use post-increment addressing
  Ensured word alignment for symbols
  Removed optimization of tests against zero, they emitted unnecessary opcodes
  Fixed 32-bit shift instructions
  Fixed shift instructions to handle shift by zero bits
  Fixed and instruction to use ANDI when appropriate
  Added optimizations for shift of 32-bit value by 16 bits
  Fixed multiply to prevent using MPY with an immediate operand
 

1.14

  Released 2017-02-19

  Added tail call optimization

  Confirmed C++ support

 

1.15

  Released 2017-05-29
  Added .size directive to compiled output
  Fixed several instruction lengths
  Fixed multiply bug
  Reduced patch size

Attached Files


Edited by insomnia, Mon May 29, 2017 6:55 PM.


#2 sometimes99er OFFLINE  

sometimes99er

    River Patroller

  • 3,832 posts
  • Location:Denmark

Posted Thu Jun 10, 2010 2:46 AM

Absolutely brilliant ! Marvellous !

Please use equates or something in assembler code to make it a bit more readable. Like having @VDPWA instead of @-29694.

:thumbsup:

#3 retroclouds OFFLINE  

retroclouds

    Stargunner

  • 1,521 posts
  • Location:Germany

Posted Thu Jun 10, 2010 4:31 AM

Very cool! :)

Looking forward experimenting with this :)

#4 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Thu Jun 10, 2010 5:28 AM

Absolutely brilliant ! Marvellous !

Please use equates or something in assembler code to make it a bit more readable. Like having @VDPWA instead of @-29694.

:thumbsup:


That would be tricky. By the time GCC gets to assembly output, all constant expressions are calculated out to just a number. In order to use equates, a post-processing stage would need to be run to collect commonly-used values. Tricky and potentially misleading if two constant values have an equal value, but are used for different reasons. On the other hand, hex constants would probably be easier to follow than the decimal ones which are used now.

#5 sometimes99er OFFLINE  

sometimes99er

    River Patroller

  • 3,832 posts
  • Location:Denmark

Posted Thu Jun 10, 2010 5:42 AM

On the other hand, hex constants would probably be easier to follow than the decimal ones which are used now.

That would do ! :)

#6 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Thu Jun 10, 2010 6:25 AM

Newbie mistake here. During the course of compiling build instructions, I realized that the patch files included above are no good.

I mixed source and destination while running the diff command. Sorry.

But the complete files are still valid. I'll fix this ASAP, and include patch and build instructions, as well as register usage and other helpful info.

While I'm at it, I'll convert to hex constants in the assembly.

#7 The Codex OFFLINE  

The Codex

    Dragonstomper

  • 573 posts
  • Location:Richmond, VA

Posted Thu Jun 10, 2010 6:33 AM

Wow, good work! Really looking forward to trying this out for serious development! :lust:

#8 matthew180 OFFLINE  

matthew180

    River Patroller

  • 2,353 posts
  • Location:Castaic, California

Posted Thu Jun 10, 2010 6:47 AM

Nice work! A lot of people have wanted a C compiler for the 99/4A for a long time.

It looks like your example ended up inlining the function call. Do you have an example that actually calls a function? I would be curious to see how that is handled since C relies heavily on a stack, and the 9900 does not have hardware support for a stack.

Matthew

#9 Tursi OFFLINE  

Tursi

    River Patroller

  • 4,622 posts
  • Location:BUR

Posted Sat Jun 12, 2010 3:57 PM

Very interesting! I will have to dig into this when I can, too! I took at stab at it some years ago but did not get to a working state. I'd love to be able to delete my files and say there's a good one now! ;)

#10 Willsy ONLINE  

Willsy

    River Patroller

  • 2,980 posts
  • Location:Uzbekistan (no, really!)

Posted Sun Jun 13, 2010 6:02 AM

Nice work! A lot of people have wanted a C compiler for the 99/4A for a long time.

It looks like your example ended up inlining the function call. Do you have an example that actually calls a function? I would be curious to see how that is handled since C relies heavily on a stack, and the 9900 does not have hardware support for a stack.

Matthew


I was thinking exactly the same!

This is really excellent work, I doff my cap to the author! I'm not sure how much I will use it, since, well, I really have a patholgical dislike for C and it's frankly nuts syntax. I've done some stuff in C over the years, but, well, even now, C's pointer syntax still discombobulates me!

I mean:
(*(volatile char*)0x8800)

What does that mean? :?

However, the inclusion of EA5 and Cart generators is a stroke of genius! Truly excellent work!

Maybe I'll use it to learn C properly on! :roll:

#11 unhuman OFFLINE  

unhuman

    Stargunner

  • 1,135 posts
  • Location:Vienna, VA

Posted Sun Jun 13, 2010 7:54 AM

Uhoh. If this winds up with a decent library of functions... Strawberry will be challenged.

#12 matthew180 OFFLINE  

matthew180

    River Patroller

  • 2,353 posts
  • Location:Castaic, California

Posted Sun Jun 13, 2010 10:09 AM

I mean:

(*(volatile char*)0x8800)

What does that mean? :?


The (volatile char *) part is a cast, telling the compiler that the 0x8800 is a pointer to a character (8-bit) and that it is volatile, meaning:

"Variables declared to be volatile will not be optimized by the compiler because the compiler must assume that their values can change at any time."

The final * outside the cast is saying that 0x8800 is a pointer. Basically you would want to see this:

*0x8800

But that does not tell the compiler enough to know how to use the pointer, so the cast is added, and that makes it confusing. It is a pain in the ass, and I code in C every day.

Matthew

#13 Tursi OFFLINE  

Tursi

    River Patroller

  • 4,622 posts
  • Location:BUR

Posted Sun Jun 13, 2010 6:46 PM

I mean:

(*(volatile char*)0x8800)
What does that mean? :?


It means you're a programmer who doesn't use defines, constants OR comments in his code. ;)

Usually you'd put the pointer in a define or pointer variable so could could use "*VDPRD" or just "VDPRD", depending on how you defined it.

#define VDPRD *((volatile unsigned char*)0x8800)

...

int x = VDPRD;

or

volatile unsigned char *VDPRD = 0x8800;

...

x = *VDPRD;

The nice thing is that if someone else does the headers for you, you don't have to worry about the definitions. ;)

Anyway, looking forward to trying this, but unfortunately (for me) it will probably be a few weeks. Don't drop it! :)

#14 Opry99er OFFLINE  

Opry99er

    Quadrunner

  • 8,221 posts
  • Location:Cookeville, TN

Posted Tue Jun 15, 2010 5:03 PM

Wish I knew something of "C". Right now I'm still working on learning assembly--- Hopefully this will bring some more C programmers into the mix! :)

#15 JamesD OFFLINE  

JamesD

    Quadrunner

  • 7,305 posts

Posted Tue Jun 15, 2010 7:16 PM

Wish I knew something of "C". Right now I'm still working on learning assembly--- Hopefully this will bring some more C programmers into the mix! :)

C is a great companion to assembly. You can do prototyping in C because it's usually a little easier, menus, data structure modeling (character stats for example) is easy and it is plenty fast. As things progress during development you can replace some of the most time intensive stuff (screen updates/battle logic) with assembly and then you are often good to go without spending as much time on assembly.
Memory could be an issue if the code is bloated but the 9900 looks like it could work well with a C compiler.
Stack usage might not be too efficient but I won't know till I see some generated code.
I have too many C compilers on my machine already to even think about using it for the moment.
<edit>
btw, you can take C compiler output and just hand optimize it at times rather than starting your assembly from scratch.

Edited by JamesD, Tue Jun 15, 2010 7:19 PM.


#16 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Wed Jun 16, 2010 8:31 PM

Thanks for the support everyone. Work has been eating all my time lately, so I haven't had a chance to post anything.

I've been working on notes for the GCC port, and found a few minor bugs, so no patches yet. Sorry.

I do however have some notes and more sample code that people have been asking for.

Primitive Data Types
====================
These are four primitive data types supported by the TMS9900 patch. These types may be stored in registers. Larger data types must be stored in memory, and accessed via pointer dereference.

  Name   Size in bytes
  -----  -------------
  char   1
  int    2
  short  2
  long   4

Byte quantities are stored in the high byte of a register, this is to accomodate the byte-oriented instructions. Also, this allows tests on signed quantities to behave as expected. Conversion to and from larger types should be rare, so it is best to take advantage of the mechanisms the hardware provides.

Two byte quantities are stored in a single register. This is the most convenient data type to use, as the word-oriented instructions like INC, INCT, DEC, or DECT may be used to improve size and performace of compiled code. The "int" type is intended to be the same size as the machine word, so it is defined as a two-byte quantity.

Four byte quantities are stored in consecutive registers in big-endian format. The lower numbered register contains the most significant bytes word, and the higher numbered regiter contains the least significant bytes.

It is important to realize that not all 32-bit operations are supported by the compiler. This is intentional. Some 32-bit operations, like division, are quite involved on the TMS9900, and if supported by the compiler would result in large pieces of inlined code. It is more efficient for these operations to be handled by an external library. Only simple operations, like addition, subtraction and conditional checks are inlined by the compiler.

Register Usage
==============
The registers are primarily separated into volatile and non-volatile groups. The volatile registers are not preserved when a function is called, and values stored there may be destroyed as a result. Non-volatile registers are preserved across function calls. Care must be taken to preserve and restore the values stored in non-volatile registers if they are to be used.

A certain number of registers are assigned special functions by the hardware. The volatility of these registers has been chosen to reflect the most convenient usage model.

Since the TMS9900 only support two-argument instructions, most interesting calculations will involve many intermediate registers. This has resulted in the decision to classify a large number of registers as volatile. Additionally, since the registers live in memory, non-volatile values can usually be stored in memory without much penalty.

In order to reduce the overhead of a function call, it is desired that the return values and as many arguments as possible are passed by register. These argument register must be contiguous to allow the possibility of 32-bit arguments to be used.

Finally, to better remember the volatility of each register, there should be a line with all volatile registers on one side, and all non-volatile registers on the other.

The register convention has been chosen to try to find a best fit for these constraints and desires.

R0 - Volatile, Bit shift count
R1 - Volatile, Argument 1, return value 1
R2 - Volatile, Argument 2, return value 2
R3 - Volatile, Argument 3
R4 - Volatile, Argument 4
R5 - Volatile, Argument 5
R6 - Volatile, Argument 6
R7 - Volatile, Argument pointer
R8 - Volatile, Frame pointer
R9 - Preserved across BL calls
R10 (SP) - Preserved across BL calls, Stack pointer
R11 (LR) - Preserved across BL calls, Return address after BL
R12 (CB) - Volatile, CRU base
R13 (LW) - Preserved across BL calls, Old workspace register after BLWP
R14 (LP) - Preserved across BL calls, Old program counter after BLWP
R15 (LS) - Preserved across BL calls, Old status register after BLWP

16-bit values are returned on R1, 32-bit valuesa are returned on R1,R2.

Up to six arguments may be passed by register using R1 through R6. If not used for arguments, these are available as volatile registers.

The argument pointer in R7 is not always used. If used, it points to the start of arguments passed on the stack. However, the compiler can usually calculate the location relative to the stack pointer, freeing R7 for general use.

The frame pointer in R8 is not always used. If used, it points to the start of local values stored on the stack. However, the compiler can usually calculate the location relative to the stack pointer, freeing R8 for general use.

The stack pointer is stored in R10. By definition, this is a non-volatile register. Called functions, if they manipulate the stack, must restore the stack pointer to the original value before it returns.

The use of the remaining registers all have special uses defined by the hardware.

R0 is used by the shift instructions, and my be called at any depth in the call tree. It must be volatile.

The CRU base register is assigned to R12. This is volatile since all CRU uses will have to be in an assembly module. Since CRU operations are awkward enough as it is, why compound the confusion by bringing the stack into the picture?

R11, R13, R14 and R15 store values required to return from a BL or BLWP call. These values must be preserved across function calls. If not used for a return from BL or BLWP, these are treated as non-volatile registers.

#17 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Wed Jun 16, 2010 8:38 PM

The Stack
=========
A stack is required of any C language implementation. It is used to storee local values, pass arguments, and record the position in a call tree. The current stack position is stored in R10, and grows towards zero as more stack is used. This position must be initialised before C code may be executed.


Push And Pop
------------
The TMS9900 does not have push or pop operations, but it does have post-increment MOV forms which work well for stack pop operations.

Push operations take one of two forms, depending on the amount of data to push (Remember that R10 is used for the stack pointer).

Form 1:
  Instructions            Bytes  Cycles  
  ---------------         -----  ------    
  ai r10, -regcount*2      4      14+0
  mov r0, *r10+            2      14+8
  mov r1, *r10+            2      14+8
  ...
  ai r10, -regcount*2      4      14+0

  In general: bytes = 8+2N  : 10,12,14,16, 18, 20
              cycles= 28+22N: 28,50,72,94,116,138 

Form 2:
  Instructions            Bytes  Cycles  
  ---------------         -----  ------    
  ai r10, -regcount*2      4      14+0
  mov r0, *0(r10)          4      14+8
  mov r1, *2(r10)          4      14+8
  ...

  In general: bytes = 4+4N  :  8,12,16,20, 24, 28
              cycles= 14+22N: 14,36,58,80,102,124

Form one is slightly slower, but results in smaller code when three or more registers are to be pushed. For the TMS9900 port, form two is only used when two or fewer registers are to be pushed.


Saving Non-Volatiles
--------------------
Non-volatile registers are saved by the callee as part of the function preamble. The saved value is then restored to the register before the function returns.


Local variables
---------------
Local variables are stored on the stack after the stored non-volatile registers.


Call convention
===============

Arguments In Registers
----------------------
In order to make the call overhead as low as possible, R1 through R6 are used to pass arguments to called functions. Since two registers are used for 32-bit values, this can result in three to six arguments that can be passed on registers. All additional arguments are passed on the stack.


Arguments On The Stack
----------------------
Arguments which cannot be passed by register are pushed onto the stack before the function is called.


Saved Registers
---------------
Register values which are to be saved are pushed onto the stack after the arguments.

Only R9, R11, R13, R14 and R15 are eligible to be saved. R10 (the stack pointer) is not itself saved. This is done to save stack space. Each function knows what it placed on the stack, and can unwind the stack for itself. This also saves the code that would be needed to explicitly save and restore the stack pointer.

A consequence of this design is that an external debugger cannot determine a call tree by examining the stack. Since no debuggers are in common use for this architecture, this is not seen as a major drawback.


Local Variables
---------------
If local variables are used in a function, volatile registers are first allocated for the task. Once those are depleted, non-volatile registers are used. If those are depleted as well, the stack is used. Local variables which are referenced by address are always stored on the stack.

If the stack is used for local variables, they are pushed onto the stack after the saved registers.


Return Values
-------------
Sixteen-bit values are passed on register R1. Thirty-two-bit values are returned on registers R1 and R2.

#18 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Wed Jun 16, 2010 8:50 PM

Example Code
============

/* This is some undefined function. Declared extern to prevent inlining */
extern test2(int *b2);

/* Test function called by main, uses arguments on registers and the stack */
int test(long a1, long a2, long a3, long a4)
{
  int array[10];  /* Local variable stored on the stack */
  test2(array);
  return(7);
}

main()
{
  test(1,2,3,4);
}

Output, as compiled with -O1 optimisation, comments added by hand

	pseg

	def	test
test:
        ****************************
        * Function prologue
	ai r10, -22         * Allocate space for saved regs and local vars
                            *    sizeof(array) + sizeof(R11) = 22
	mov r11, @20(r10)   * Save the link register (R11) to the stack

        ****************************
        *   test2(array);
	mov r10, r1         * Argument 1 in R1: &array[0]
	bl @test2           * Call test2

        ****************************
        * return(7)
	li r1, 7            * Return value on R1: >0007

        ****************************
        * Function epilogue
	ai r10, 20          * Free local variables from the stack 
	mov *r10+, r11      * Restore R11
	b *r11              * Return to caller

	def	main
main:
        ****************************
        * Function prologue
	ai r10, -6          * Allocate space for saved regs and arguments
                            *   sizeof(a4) + sizeof(R11) = 6
	mov r11, @4(r10)    * Save the link register (R11) to the stack

        ****************************
        *   test(1,2,3,4);
	clr *r10            * Argument 4 on stack: >0000 >0004 = 4
	li r1, 4
	mov r1, @2(r10)

	clr r1              * Argument 1 in R1, R2: >0000 >0001 = 1
	li r2, 1

	mov r1, r3          * Argument 1 in R3, R4: >0000 >0002 = 2
	li r4, 2

	mov r1, r5          * Argument 1 in R5, R6: >0000 >0003 = 3
	li r6, 3
	bl @test            * Call test

        ****************************
        * Function epilogue
	ai r10, 4           * Free local variables from the stack 
	mov *r10+, r11      * Restore R11
	b *r11              * Return to caller

        ref	test2

Stack usage for this example. Assume the stack pointer is assigned to >2000 in the initialization code.

  Usage of the stack memory:

  >2000
  ~~~~ position at start of main() ~~~~
  >1FFE  --- R11 (link pointer) from main
  >1FFC  -.- Argument 4 for test()
  >1FFA  -'

  ~~~~ position at start of test() ~~~~
  >1FF8  --- R11 (link pointer) from test
  >1FF6  -.- array from test
  >1FF4   |
  >1FF2   |
  >1FF0   |
  >1FEE   |
  >1FEC   |
  >1FEA   |
  >1FF8   |
  >1FF6   |
  >1FF4  -'  <-- array[0]
  ~~~~ position at start of test2() ~~~~


#19 retroclouds OFFLINE  

retroclouds

    Stargunner

  • 1,521 posts
  • Location:Germany

Posted Wed Jun 16, 2010 11:48 PM

Excellent stuff :)

#20 JamesD OFFLINE  

JamesD

    Quadrunner

  • 7,305 posts

Posted Thu Jun 17, 2010 10:03 AM

The compiler output looks interesting. I'd like to see how code size compares vs other CPUs.
The large number of registers works in it's favor but the way the stack is handled will offset that somewhat.

I think any code that doesn't make a lot of calls will be pretty decent, but if you use a lot of calls in your code it looks like the 9900s lack of built in stack functions will hurt it. That could present a bit of dilemma. Isolate machine specific things to make your code easier to port or make it machine specific for speed and size sake.

I'm not sure if code output would be much different than most 8 bit CPUs. The Z80 has some overhead handling the call stack as would the 6801/3. The 6502 has to handle the stack with a pointer and with it's limited registers you can count on it's code being worse. I *think* the 6809 would have an advantage on some code but I think how the compiler's code generator is implemented would have a lot to do with it. The 8088 probably has a little advantage. The 68000 is definitely better.

#21 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Mon Jun 21, 2010 9:54 PM

The big advantage that the 68000 has over the TMS9900 are the load and store multiple instructions. The post-decrement modes are handy, but clever coding can mostly compensate for that. Dedicated push and pop instructions would add no real advantage beyond a pre-decrement mode. There are MOV modes which can do the push and pop in mostly one instruction.

I've been thinking about stack-y things lately, given the comments here, and decided to second guess my earlier decisions. As a result, I came up with nine different stack call conventions. Most were pretty poor or offered no real advantage over what I already had. On the upside, I was able to squeeze out two bytes and 12 cycles from my earlier design. The four most interesting ones are listed below.

One thing I've found out is that the TMS9900 really makes you decide if you want to optimize for speed or size. Apparently, you can't have both. I recall that one of the criticisms of the TI firmware was that it was heavily optimized for size, making it a bit slow. This is a bit annoying since with RISC architectures (the TMS9900 mostly qualifies), fast and small are usually the same thing. I blame the slow-as-dirt 8-bit memory.

At any rate, I wouldn't be surprised if the TMS9900 doesn't turn out to be some kind of computing powerhouse.

So here's what I found stack-wise: (note that the form numbers here don't correspond to the ones I mentioned earlier)

This is the simplest stack setup and teardown code you can have. All this does is save R11 (the return pointer) at the start of a function, and restore it at the end.

Form 0 (the simplest R11 save possible)

code                 bytes  cycles
------------         -----  ------
dect sp              2      10+8     = 18
mov r11, *sp         2      14+8+4+8 = 34
...
(function goes here)
...
mov *sp+, r11        2      14+8+8+8 = 38

Totals              =6               = 90


These forms assume local variables in a stack frame, and non-volatile register values stored on the stack

Form 1
code                        bytes  cycles
------------                -----  ------
ai sp, -regsize-framesize   4      14+8+8   = 30
mov r11, *sp                2      14+8+4+8 = 34
mov r9,  @2(sp)             4      14+8+8+8 = 38
mov r13, @4(sp)             4      14+8+8+8 = 38
mov r14, @6(sp)             4      14+8+8+8 = 38
mov r15, @8(sp)             4      14+8+8+8 = 38
...
(function goes here)
...
mov r11, *sp+               2      14+8+8+8 = 38
mov r9,  *sp+               2      14+8+8+8 = 38
mov r13, *sp+               2      14+8+8+8 = 38
mov r14, *sp+               2      14+8+8+8 = 38
mov r15, *sp+               2      14+8+8+8 = 38
ai sp framesize             4      14+8+8   = 30

Totals                    =36               =436



Form 2
code                        bytes  cycles
------------                -----  ------
ai sp, -regsize-framesize   4      14+8+8   = 30
mov sp, r0                  2      14+8     = 22
mov r11, *r0+               2      14+8+8+8 = 38
mov r9 , *r0+               2      14+8+8+8 = 38
mov r13, *r0+               2      14+8+8+8 = 38
mov r14, *r0+               2      14+8+8+8 = 38
mov r15, *r0                2      14+8+8+8 = 34
...
(function goes here)
...
mov *sp+, r11               2      14+8+8+8 = 38
mov *sp+, r9                2      14+8+8+8 = 38
mov *sp+, r13               2      14+8+8+8 = 38
mov *sp+, r14               2      14+8+8+8 = 38
mov *sp+, r15               2      14+8+8+8 = 38
ai sp, framesize            4      14+8+8   = 30


Totals                    =30               =458



Form 2a (requires a stack frame)
code                        bytes  cycles
------------                -----  ------
ai sp, -regsize-framesize   4      14+8+8   = 30
mov sp, r0                  2      14+8     = 22
mov r11, *r0+               2      14+8+8+8 = 38
mov r9 , *r0+               2      14+8+8+8 = 38
mov r13, *r0+               2      14+8+8+8 = 38
mov r14, *r0+               2      14+8+8+8 = 38
mov r15, *r0                2      14+8+8+8 = 34
...
(function goes here)
...
mov *sp+, r11               2      14+8+8+8 = 38
mov *sp+, r9                2      14+8+8+8 = 38
mov *sp+, r13               2      14+8+8+8 = 38
mov *sp+, r14               2      14+8+8+8 = 38
mov *sp,  r15               2      14+8+8+8 = 34  <-- this line is different, no post-increment, saved 4 cycles
ai sp, framesize+2          4      14+8+8   = 30

Totals                    =30               =454



Nvols  used:       0   1   2   3   4
                  --  --  --  --  --
Form0  bytes:      6
       clocks:    90

Form1  bytes:     12  18  24  30  36   Use for one or less non-vol regs saved
       clocks:   132 208 284 360 436
                 ^^^^^^^
Form2  bytes:     14  18  22  26  30   Use for two or more non-vol regs saved
       clocks:   154 230 306 382 458
                         ^^^^^^^^^^^
Form2a bytes:     14  18  22  26  30   Use for two or more non-vol regs saved plus stack
       clocks:   150 226 302 378 454

If no stack frame is required, four bytes and 30 cycles can be saved from forms one and two

Exciting! Who isn't thrilled by stack frames?

This is one form that looked interesting, but totally impractical for a compiler. Although it might be handy in a some assembly library or something.

The idea is that most of the stack setup and teardown is in a callable function. This reduces the per-function byte count at the expense of speed. Lots of speed. I'm mostly worried about the "b @8(r11)" instruction, I'm not sure if that's legal or will do what I expect. I haven't tested this, and it may not work, but it sure looks interesting.

Form 3
code                                  bytes  clocks
------------                          -----  ------
ai sp, -(regs*2+framesize)            4      14+8+8   = 30   <-- allocate space on the stack
mov r11, r0                           2      14+8     = 22   <-- make copy of return pointer
bl @(store_multiple+16-regs*4)        4      12+8+8   = 28   <-- jump into common stack setup
...
(function goes here)
...
li r0, framesize+regs*2               4      12+8+8   = 28   <-- size of stack allocated
b @(load_multiple_return+16-regs*4)   4      8+8+8    = 24
   <-- jump into common stack teardown then return

store_multiple:
   mov r15, @-8(sp)         4      14+8+8+8 = 38  <-- entry point for four registers saved
   mov r14, @-6(sp)         4      14+8+8+8 = 38  <-- entry point for three registers saved
   mov r13, @-4(sp)         4      14+8+8+8 = 38  <-- entry point for two registers saved
   mov r9,  @-2(sp)         4      14+8+8+8 = 38  <-- entry point for one registers saved
   mov r0, *sp              2      14+8+4+8 = 34  <-- entry point for zero registers saved
   b @8(r11)                2      8+4      = 12  <-- return to just after "bl @..." call

load_multiple_return:
   mov @-8(sp), r15         4      14+8+8+8 = 38  <-- entry point for four registers saved
   mov @-6(sp), r14         4      14+8+8+8 = 38  <-- entry point for three registers saved
   mov @-4(sp), r13         4      14+8+8+8 = 38  <-- entry point for two registers saved
   mov @-2(sp), r9          4      14+8+8+8 = 38  <-- entry point for one registers saved
   mov *sp, r11             2      14+8+4+8 = 34  <-- restore link pointer
   a sp, r0                 2      14+8     = 22  <-- restore stack
   b *r11                                         <-- return to caller

       nvols:      0   1   2   3   4
Form3  bytes:     18  18  18  18  18
       clocks:   234 310 386 462 538


The TMS9900 has a simple instruction set, but there are still some neat things that can be done with it. So now, I'm off to implement what I've shown here, and fix more compiler bugs.

#22 JamesD OFFLINE  

JamesD

    Quadrunner

  • 7,305 posts

Posted Tue Jun 22, 2010 6:23 AM

Well, GCC does have different optimization settings. Letting people choose size or speed to suit their app makes some sense.
Just remember that you have to be able to link routines compiled with different settings.

#23 retroclouds OFFLINE  

retroclouds

    Stargunner

  • 1,521 posts
  • Location:Germany

Posted Tue Jun 22, 2010 8:05 AM

This is very cool. I'm currently redesigning my SPECTRA assembly game library and one of the key elements is that it's stack based.
I'm currenlty redoing that part and its nice seeing the ideas you came up with for the stack handling.
For 'popping' the registers of the stack I'll be having a small subroutine in scratch-pad memory.

I don't know any C myself, but I presume that the C implementation will be using some of the registers and memory for handling its own requirements.

* Will scratch-pad memory be used by the compiler generated program ?
* Do you mind sharing which registers are "taboo" for external assembly routines.
* What conventions should assembly routines stick to for being callable from a C program ?

#24 JamesD OFFLINE  

JamesD

    Quadrunner

  • 7,305 posts

Posted Tue Jun 22, 2010 9:43 AM

This is very cool. I'm currently redesigning my SPECTRA assembly game library and one of the key elements is that it's stack based.
I'm currenlty redoing that part and its nice seeing the ideas you came up with for the stack handling.
For 'popping' the registers of the stack I'll be having a small subroutine in scratch-pad memory.

I don't know any C myself, but I presume that the C implementation will be using some of the registers and memory for handling its own requirements.

* Will scratch-pad memory be used by the compiler generated program ?
* Do you mind sharing which registers are "taboo" for external assembly routines.
* What conventions should assembly routines stick to for being callable from a C program ?

Here are some general rules for interfacing with C. Comments about the 9900 version of GCC are just guesses.

C variables are normally allocated on the stack. Any other memory use would probably be through allocation routines and it is accessed through pointers.
Perhaps you could specify scratchpad memory in a call to the memory allocation routine similar to how the Amiga allowed allocation of CHIP (graphics) or FAST memory. Due to scratch-pad's limited size and importance I would suggest managing it's allocation from regular memory instead of using a linked list in the memory itself. Accessing the TI's graphics memory would probably involve custom defined values and APIs.

Registers used by a called subroutine are normally pushed onto the stack and restored after the return from that subroutine so that the subroutine does not destroy their contents.
The parameters to the subroutine are pushed onto the stack before the call and are accessed there by the subroutine. After the subroutine returns, the stack pointer is adjusted and registers are restored. Some compilers support registerized parameters so some of the call parameters can be passed in registers. A return value is normally expected in a register.
In the case of the 9900, the registers are in memory but I would think it has to follow similar rules.

Registers should already be preserved by the caller but I'm assuming you have to access parameters on the stack through the register used as a stack pointer. If registerized parameters are supported the subroutine would just start using the registers and assume parameters are already loaded in them.
<edit>
Since registers are in memory, don't you have the option of totally moving where registers are? Then you could just copy only the registers you need and restore the register pointer when you are done.

Edited by JamesD, Tue Jun 22, 2010 4:29 PM.


#25 insomnia OFFLINE  

insomnia

    Star Raider

  • Topic Starter
  • 67 posts
  • Location:Pittsburgh, PA

Posted Tue Jun 22, 2010 10:43 PM

A couple of points here (bear with me, I haven't figured out how to quote properly on this forum yet...):

GCC optimization levels
-----------------------
The optimizer doesn't really know how to generate fast code. It can optimize for size, algorithmic complexity, combine constants, and move constant expressions out of loops, inlining. You get the idea. These things will typically generate fast code, but this is not guaranteed. Also, GCC has no way of counting cycles or taking advantage of the speed of the scratchpad memory.


Scratch pad memory usage
------------------------
The compiler uses a single register set. It doesn't know where in memory this set lies. It is the responsibility of the C environment initialization code. This is ususally a bit of assembly code. On other machines, this can be quite involved, potentially involving lots of driver or memory initialization. I'm anticipating that for the TI, I'll only need to initialize R10 (used for the stack pointer), set the workspace register to some convenient location and clear the BSS section. If performance demands that the register set be at a specific location, that can be handled in the initialization code. If scratchpad is to be used for memory, that can be done in C by specifying data pointers in that space. If code must be run from there, that can be done in C as well (use function pointers to scratchpad). The point is that these things are beyond the scope of converting C code to assembly.


Calling convention
------------------
In my port, function arguments are primarily passed by register. If there is not enough room for all the arguments, the rest are passed on the stack. I'm still finalizing the order of these arguments on the stack. Likewise, function-local variables are stored in registers if there is room. GCC can determine the lifetime of these variables, and can use the same register to hold many different variables, as long as they are not needed at the same time. Once all registers are used, the remaining variables are stored on the stack.

The called function is responsible for preserving a small set of registers if they are to be used. The calling function assumes that these registers will not be modified by the act of calling a function. Values in the other registers are assumed to be destroyed by calling a function.

The short version: R1 through R6 are used to pass function arguments, R1 is used to return values to the caller. R9 to R11, R13 to R15 must not be changed by calling a function. All other registers can be modified in any way.

If assembly modules hold to the calling convention, things will run smoothly. If not, expect random behavior and crashes.


"Taboo" registers
-----------------
This is dependant on the calling convention. For my port, any register may be used, but the values in six registers (R9, R10(stack pointer), R11 (return pointer), R13, R14, R15 (These are needed to return from a BLWP instruction) ) must not be changed when an assembly module returns. This can be done by saving these values in memory and restoring then to registers before the module exits. Or most simply by not using these registers.


Accessing values on the stack
-----------------------------
The stack grows towards zero, so all stack variables can be accessed by indexing off the stack pointer register. This also allows more flexability when calling functions, since fixed addresses are not used.


The general idea is that by using the C language, functional code can be written quickly, and code can be ported more easily from other machines. If more control is needed in how code is implemented (either for size, speed, memory usage or other requirements), assembly can be used.
I think that's it for the points raised so far. I intend to make a document describing all this in more detail. See the earlier posts for more information.




0 user(s) are browsing this forum

0 members, 0 guests, 0 anonymous users