PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Challenge for the ARM Assembler gurus!

Hi,

I am writing a compiler which translate code into ARM assembly and would like to know how in C I can convert a 32bits number into 12bits.

ex:

str r0, [r5, #0xFA0] ; This represents 1000 * 4 in C.
mov r1, #1, 20 ; This is 4096;
mov r1, #0x7D, 26 ; This is 8000;
mov r1, #0xFA, 26 ; And this is 16000;

I hope it's clear enough. I would like to be able to get two values out of the function. The base value and the shift value.

ex: conv32to12 (16000, &base;, &shift;);

Regards,
Alain Deschenes
hrm... just a thought... you don't need to represent the numbers that way in order for it to be valid arm assembly code. I you are just using "armasm", the assembler will figure out the shift for you. Thus writing:

mov r1, #8000

will translate appropriately. If you do wish to pursue calculating the base and the shift, just remember it is not a 12 bit number but an 8 bit number rotated to the right by an even number of bits.
Thanks for your answer but I know I can do that but the problem is that I need to write code directly into byte code and not assembly. I dynamicly compile to memory code and then call this memory blcok as a procedure.

I would just love to do it in assembly language and not worry about this nightmare the ARM processor causes. :(

Regards,
Alain Deschenes
Can you give me a code sample in C on how to convert the numbers?

Regards,
Alain Deschenes
Making this up as I go along, so it's all untested.

Surely you just need to do a CLZ (count leading zeroes) on the number you'd like to enter, round that to be exactly divisible by 2 and make sure that the next 8 bits are the only bit-range with bits set (or unset if you're going to put a MVN there rather than a MOV).

As Exocet said - you need a base and a rotate right by an even number, not a shift.

I.e. the number is:
0x0ff00000

The Rotate is the top 4 bits (result of a CLZ) + the 8 bits of the constant itself = 12.
The base is then the input>>(32-rotate) = 0x0ff00000>>20 = 0xff


So, going by your 8000 example:

8000 in hex is 0x1f40

CLZ(0x1f40) gives 19, which we round to 18

So, Rotate is (18 + 8) = 26

Base is 0x1f40>>(32-26) = 0x1f40>>6 = 0x7d


Some constants would work "better" as a MVN using a count-leading-ones approach (e.g. 0xff00 ffff).

I would just love to do it in assembly language and not worry about this nightmare the ARM processor causes.


Because variable length instructions are such fun to work with~ :P
Can you give me a code function in C to help me figure it out? I am not very good with numbers sometimes and not the best in C either. I am a Delphi programmer on Windows mainly.

Regards,
Alain Deschenes
There are a few C and ARM ASM clz implementations in this forum, for use on non-XScale devices. To put Refractor's algorithm in C:

Code:

void conv32to12 (int n, int &nBase;, int &nShift;) {
nShift=clz(n); //Count leading zeros
nShift&=0xfffffffe; //Round down to nearest even number
nShift+=8;
nBase=n>>nShift;
}


Hmm, TAB doesn't work in the message edit box. Must be something else broken with the new version of phpBB that Chris needs to fix.

Dan East
Hi Dan,

Since the CLZ opcode can only be used with ARM code and I want to debug it with the emulator, I cannot use it. I used this routine, can you confirm that it's correct please?

Code:
int CLZ( int n )
{
int numZeros = 0;
if( n == 0 ) return (sizeof(n)*8);
while( n >= 0 )
{
n = n << 1;
if (n >= 0)
numZeros++;
}
return numZeros;
}


Regards,
Alain
Hi Dan,

Is it possible your code was missing this: nBase=n>>(32-nShift); ?

Code:
void conv32to12 (int n, int &nBase;, int &nShift;) {
nShift=CLZ(n); //Count leading zeros
nShift&=0xfffffffe; //Round down to nearest even number
nShift+=8;
nBase=n>>(32-nShift);
}


Thanx,
Alain
Hi All,

I just tested this code here and it works for a value of 8000 and 16000 but for 4096 it doesn't work! Very strange.

Code:
int CLZ( int n )
{
int numZeros = 0;
if( n == 0 ) return (sizeof(n)*8);
while( n >= 0 )
{
n = n << 1;
numZeros++;
}
return numZeros;
}

void conv32to12 (int n, int &nBase;, int &nShift;) {
nShift=CLZ(n); //Count leading zeros
nShift&=0xfffffffe; //Round down to nearest even number
nShift+=8;
nBase=n>>(32-nShift);
}

int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
int base, shift;

conv32to12(8000, base, shift);
conv32to12(4096, base, shift);
conv32to12(16000, base, shift);
}


Regards,
Alain
kornalius wrote: would just love to do it in assembly language and not worry about this nightmare the ARM processor causes. :(


arm processor caused me nightmares too... after programming arm a lot, a day I dreamt I had to code some things in x86 :) that was the nightmare! :)

I don't know exactly what you mean with that function, but I think this should work:

Code:

void conv32to12 (int n, int *nBase, int *nShift)
{
int shift;

if (n==0) { *nBase=0; *nShift=0; return; } // handle 0

shift=0;
while (1) // calc shift, base value
{
if (n&1) break;
n=n>>1;
shift++;
}

if (base>4095) then handle error: bigger than 12 bits, can't be represented

*nShift=shift;
*nBase=n;
}
kornalius wrote:Hi All,

I just tested this code here and it works for a value of 8000 and 16000 but for 4096 it doesn't work! Very strange.



btw, remember that 4096 is base 1, shift 12 , but can also be base 2, shift 11 , or base 4 shift 10, ..... or base 2048 shift 1
This should solve your problem. It is a bit of a dirty hack but it will tell you if you need to bitwise negate the value. So if a user wrote mov r1,#-1 you would know to convert it to mvn r1,#0. The program will also give an error when the number supplied cannot be represented in the 8ROR format.

- Exocet



Code:
#include <stdio.h>

#define CALC8ROR_NORMAL 0
#define CALC8ROR_NEGATE 1
#define CALC8ROR_ERROR 2

#define ROL2(x) ( ((x) << 2) | ((x) >> 30) )


__int32 clz(unsigned __int32 value)
{
__int32 nlz = 32;
unsigned __int32 temp;

// 16
temp = value >> 16;
if (temp != 0) {
nlz -= 16;
value = temp;
}
// 8
temp = value >> 8;
if (temp != 0) {
nlz -= 16;
value = temp;
}
// 4
temp = value >> 4;
if (temp != 0) {
nlz -= 4;
value = temp;
}

// 2
temp = value >> 2;
if (temp != 0) {
nlz -= 2;
value = temp;
}

// 1
temp = value >> 1;
if (temp != 0) {
nlz -= 1;
value = temp;
}

if (value == 1)
nlz -= 1;

return nlz;
}

__int32 calc8ROR( unsigned __int32 value,
unsigned __int32 * val,
unsigned __int32 * ror)
{
__int32 i;
unsigned __int32 n_value = ~value;

// continually ROL until the value is in the lower 8 bits
for (i = 0; i < 32; i += 2) {
if (clz(value) >= 24) {
*val = value;
*ror = i;
return CALC8ROR_NORMAL;
}

if (clz(n_value) >= 24) {
*val = n_value;
*ror = i;
return CALC8ROR_NEGATE;
}

value = ROL2(value);
n_value = ROL2(n_value);
}
return CALC8ROR_ERROR;
}

void test8ROR(unsigned __int32 value)
{
unsigned __int32 val, ror;
__int32 sign = calc8ROR(value, &val, &ror);
if (sign == CALC8ROR_NORMAL)
{
pr__int32f("0x%08x val:0x%02x ror:%d\n",
value, val, ror);
}
else if (sign == CALC8ROR_NEGATE)
{
pr__int32f("0x%08x BITWISE NEGATE val:0x%02x ror:%d\n",
value, val, ror);
}
else if (sign == CALC8ROR_ERROR)
{
pr__int32f("0x%08x INVALID 8ROR number\n",
value);
}
}

__int32 main()
{
test8ROR(0x00550000);
test8ROR(0x00000100);
test8ROR(0x80000001);
test8ROR(0xFFFF3FFF);
test8ROR(0x12345600);
}
Wow, thanx so much it seem to be working like a charm. I will do some more test and let ya know. So far so good though.

Now I just need to figure out how I am going to generate the 4 bytes opcode in assembly that will do all the mumbo-jumbo in ARM assembly. Something like "e801e027" to put into memory. It was SO easy in 8086. :wink:

Do you guys mind if I ask some more questions about the ARM assembly code in general in the coming days?

Regards,
Alain.
I'm glad it worked. It was a great way to kill time at the office. :) Feel free to ask any ARM related question.
Thanx a lot. I will be doing some more testing tomorrow.

Btw, how would you convert this into assembly opcodes:

mov r0, #0xFA, 26

I know it's e3a0dfa but I need to be able to add my dfa to e3a0. Could I do it with a string and then convert it back into int? If so how to do this in C?

Another one: Let's say I have an array of *char that I need to use inside my new assembly code, can I directly access an array item with it's address or does it have to be relative to the pc (r15 i think)?

You see I want to do something like this: (Move the address of array[10] variable into r0 and then call a regular C void called _push).

C code
=====

void _push(char *s)
{
PushOnInternalStack(s);
}

Assembly code to generate
==================

ldr r0, array[10]
bl _push

How would this translate into ARM opcodes?

Regards,
Alain Deschenes
kornalius wrote:Another one: Let's say I have an array of *char that I need to use inside my new assembly code, can I directly access an array item with it's address or does it have to be relative to the pc (r15 i think)?


you can use all registers for addressing. pc is used to load constants, which were put between the functions by the compiler. because there is no immediate 32bit constant load, this is the fastest way to get a 32bit constant value into a register (like global addresses). example on mips there is another way: immediate values are 16bit and with a seperate instruction to load the higher 16bit part, loading a 32bit value needs only 2 instructions. in arm the immediate values store only 8bits (but can be shifted), so a ldr rd, [pc,#n] is faster.

i'am not sure i understand the next question. if you want to access a global variable, you should put the address after the arm function and load it (the address) with [pc,#n] relative addressing.

btw you can check my dynamic "compiler" in my draw library http://www.demoscene.hu/~picard/pmvp/emu.zip
(/draw/dyncode_arm.cpp or the actual usage in /draw/blit_arm.cpp)

what level of compiler are thinking about, what form of input will it compile to arm binary? i had to think about it too. i didn't want to go into to much trouble with actaul assembly text (or higher language) prasing and stuff. i choose an inbetween solution to add the instructions manually with as many automation as possible.

bye, Picard
ps: don't forget to flush the instruction cache before calling the (re)generated assembly code (VirtualProtect or CacheSync, but there is thread about it somewhere in this forum)
You see the first question was really about how to generate bytecode for the arm. In 8086 it was easy because each opcode is a byte and then you could have a word. I then used something like:

GenByte(CodeBuff, opcode);
GenWord(CodeBuff, value);

But in ARM the instruction is all into a 4 bytes format. Lets say I have my opcode value and the 32 bits value shifted:

opcode = 0xe3a0 ; or whatever it is.
value = 0xFA;
shift = 0x26; In order to store it needs to be split in half.

How can I generate my whole 4 bytes ARM code with these 3 values. Can I just simply add them together? Sorry for these stupid questions I am not very good with all of this.

As for my second question it was about a global variable that is being used by the parser/compiler that I would keep in order to save memory. Same thing with the _push function who would be located inside my main C code and that would like to use with my new generated code. I don't think I can use relative addressing here because my new code buffer might end up being too far away from my main C code.

Regards,
Alain Deschenes
kornalius wrote:opcode = 0xe3a0 ; or whatever it is.
value = 0xFA;
shift = 0x26; In order to store it needs to be split in half.

How can I generate my whole 4 bytes ARM code with these 3 values. Can I just simply add them together? Sorry for these stupid questions I am not very good with all of this.


if you shift the components to the required bit positions you can add them (but logical or would be more understandable) example GenDWord(CodeBuff, (opcode << 16) | ((shift >> 1) << 8) | (value)) (shift should be decimal 26, and not 0x26)

kornalius wrote:I don't think I can use relative addressing here because my new code buffer might end up being too far away from my main C code.

you should save the 32bit address after/before the arm code (with GenDWord) and load it with pc relative addressing. relative addressing is not for the actual destination address, but only for the code embedded constants. it's just the fastest way to load a 32bit constant into a register (example a global address). btw the arm branch instruction can handle 24bit (*4) relative addressing, so this may be unnecessary in most jumps/calls.
So the way I understand it is that any values/constants or addresses to global variables should be stored in a location after the ARM code to call and accessed with the relative location to the pc. So this would be even easier than using the shifting idea for values > 4096.

So in order to load the value 8000 into r0 and to call the _push function, it would be something like this:

Code:

begin of code

push pc to stack
ldr r0, [pc, #xxx] ; points to constant #1 in storage area
bl ???????? ; How to call _push if it's address is stored in a relative mem loc.?
....
pull pc from stack

constants / function locations storage area begin
1= 8000
2= function _push address
constants / function locations storage area end

end of code


How would I call the _push function if it's address is stored in a memory location. I think the bl opcode calls whatever you pass as a value?
kornalius wrote:How would I call the _push function if it's address is stored in a memory location. I think the bl opcode calls whatever you pass as a value?


you can use 'mov lr,pc; mov pc,rn;' or just the 'blx rn' instruction (arm 4T or above required). bl opcode uses relativate addressing (if the function has a fixed address and is not out of range, this is the fastest)

btw a strongly recommend to check out some evc generated assembly listing files of c code.
Thanx picard, I did in fact learn some of the ARM by looking at the generated code from evc. Not easy at first but now it is starting to make a lot of sense.

Thanx for your time and patience.

Regards,
Alain Deschenes
One more question:

Is it hard to use floating points in ARM?
kornalius wrote:One more question:

Is it hard to use floating points in ARM?

Probably depends mostly on the implementation of ARM you are talking about. What you find in mobile devices typically does not include FP hardware. You could either use the standard floating point instructions defined by the ARM architecture and rely on correct software trapping to happen, our you'd directly call into such library (which should be faster if you know that you do not have a hardware implementation available). As an example, have a look at what EVC is creating.

Depending on what you are doing, a common alternative is to use fixed point numbers.
'blx rn' instruction (arm 4T or above required).


Just to say that 4T does not include StrongARM (I would entirely ignore Thumb for the purposes of dynamic compilation).

As for the "data" section, copy what the linker does...
Hi guys,

What is the best way in evc to debug a code like mine without having to go through the long process of debugging with the device connected to my pc. If I use the emulator it's fast and cool, but it only works with Intel code.

You see, if I create a block of memory with ARM binary in it, it won't be able to dissassemble it and show me the result in memory.
One more question. If I have this procedure:

Code:
void GenQuad(unsigned long l)
{
unsigned long *p = (unsigned long *)OffCodeBuff;

*p = l;
p++;
OffCodeBuff = p;
}


And I want to generate the following ARM code:

Code:
GenQuad(0xe89da000);


It becomes 00 a0 9d e8 in memory. Is this the same if I use the same procedure once it's generated in ARM's code? If so, how can I modify this procedure to invert the information back to the original e89da000 in ARM's memory?

It would be so much easier to be able to debug in ARM's code using the emulator and being able to see the memory content and be able to watch variables too. Can this be done?
Theres no need to do this at all. The ARM unfortunately (or fortunately if you're a traditional PC programmer) is little endian. Exactly the same as your PC. So even though the byte order has changed, the ARM processor will understand your code perfectly.

-Exocet
Oh yeah? Now that is good news. :D

What is the best way to debug using evc without using the device but still be able to see the code in ARM's?
kornalius wrote:What is the best way to debug using evc without using the device but still be able to see the code in ARM's?


is there a way? i think you would need an ARM emulator with full emulation of a pocketpc (which can communicate with evc just like the x86 emulator). probably there are commercial solutions for this (very expensive), but i don't know any way to achive this with a standard evc setup. you can add free ARM emulator to your project and run the ARM code emulated in a x86 build, but evc wouldn't show and debug the ARM code in this case.
Hi Picard,

How did you do your testing for your ARM emulator. How did you test if your dynamic code was running alright and if there was a bug within it, how did you figure out where and what was happening?
i used normal c debugging for my arm emulator (c version). first with very simple programs (hello world, etc) compiled by me (with assembly list files). later with complex programs like pocketmvp, pockettv.

i tested the dynamic code mostly on my ppc arm device. sometimes i used my emulator too, but it's much harder to track anything. mainly i used the emulator as an error indicator (after i got a working version and made some changes), if something went wrong and couldn't find the problem in the emulator easily, i used the arm device.
Ok I see. Well I guess I'll keep using my device. I find it slow but hey, better than nothing! :wink:

Thanks again!
Btw, how can I use your emu.h file from within my project? I did Reset, AttachThread but I can't compile. I included "emu.h" into my project from the emu directory. But I get undeclared identifiers for all of these functions.

I did this:

#include "emu\emu.h"

Should I put all of your files in the root directory of my project for it to work or can I leave them in the emu directory and tell the compiler to use this path for all of the emu.h required files?
sorry i included only a vc6 project file (not embedded). so you should add the sources to your project (not the include directory, but to the project tree) or a nicer solution is to create a new static or dynamic library project and add all the files in the emu directory and compile. then set 'project/dependencies' so your project can include the generated emu.lib automaticly.
Hi Picard,

I get this error when I try to compile:

C:\arm_emulator\emu.cpp(203) : fatal error C1189: #error : callback not implemeted yet

What should I do?

Regards,
Alain
kornalius wrote:C:\arm_emulator\emu.cpp(203) : fatal error C1189: #error : callback not implemeted yet


you can only compile it under an x86 project. if you use your arm build disable the emulator (example use 'exclude from build' option in project settings/general)

(if you don't compile the emulator to a dll, replace the EMU_API define in emu.h with an empty define)
Hi,

I now get this error:

mapper.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) const emu::mapper::`vftable'" (__imp_??_7mapper@emu@@6B@)

emulatorDbg/emulator.dll : fatal error LNK1120: 1 unresolved externals

My project is x86 debug with PPC 2003 emulator.

Is it also normal to get a big list of warnings from imported functions ... ?

Regards,
Alain
you should replace the EMU_API define part (the whole #ifdef/#else/#endif) in the beginning of emu.h with a simple '#define EMU_API' (empty define). this should solve the warnings and the compiler error.
Well, I was able to compile the emu.dll but I tried to add it to my project without success. Can you, please, direct me on how to do this, including the necessary #include's I should put etc... I am still pretty new to C and sometimes I can get very confused.

Regards,
Alain
I finally was able to compile my project, just by inserting the .h and .cpp files into it.

Sorry for all the trouble. :(
i'am sorry. i released the source without checking and only compile able under the one enviroment i used (emulator.dsw under vc6)...

so. you need to use "emu" namespace. like this:

#include "emu/emu.h"
using namespace emu;

(and you should use c++ file. sorry about that too. after rethink it's totally unnecessary for this library, there is no public objects at all...)

bye, Picard
Is it possible that your compiler doesn't support these?

Here is my code: (Just a regular procedure entry)

    GenQuad(0xe52de004); // str lr, [sp, #-4]
    GenQuad(0xe8bd8000); // ldmia sp!, {pc}



Here is the code that emu compiler has generated:

    1A1F0000 60 pushad
    1A1F0001 8B 74 24 28 mov esi,dword ptr [esp+28h]
    1A1F0005 8B 44 24 24 mov eax,dword ptr [esp+24h]
    1A1F0009 BF 1C BE 0B 00 mov edi,0BBE1Ch
    1A1F000E BD 4C 89 06 00 mov ebp,6894Ch
    1A1F0013 FF D0 call eax
    1A1F0015 61 popad
    1A1F0016 C2 08 00 ret 8


It then crashes at address 1A1F0015.

Any idea why?
ldmia sp!, {pc}


Educated guess: Try replacing that with the corresponding LDR instruction (i.e. LDR pc,[sp],#4)
I will try that, but what is the best way to get the bytecodes from an assembly line? Can I just use __asm { ldr pc, [sp], #4} in C and then check the result in the .cod file?

Edit:: Damn, __asm is not supported under ARM/PPC 2003 projects.
Can anybody tell me what is the best way to find out the corresponding bytecode of an assembly line? eVc is not always going to generate the bytecodes I am looking for obviously.

Regards,
Alain
search for documentations on the web. i used this pdf for the basics: http://www.demoscene.hu/~picard/arm_inst.pdf
Thanks picard, that is some good pdf. I had a few pdf's but none were that good. I also found narm for windows. Nice little assembler that works quite well and can give me an idea of what the bytecode will look like.

Btw, does your emu library support procedure entry, like, storing the pc to the stack and pulling it back at the end of the procedure?