简体   繁体   中英

Cannot translate this C code to MIPS Assembly

Basically I need to translate this C code ( http://pastebin.com/7EupfQ5n ) to MIPS assembly. I took a crack at this, but I am having troubles.

What I have so far is this ( http://pastebin.com/LpS6Mqr1 ). But when I run the code in a simulator, it runs in an infinite loop despite what I put into the array, and I cannot find where it is doing that. I would assume that it is referencing the array in an incorrect way in the while and if statements, but I'm not sure how or why.

If anyone can help, that would be very appreciated.

Also, is there a way to have a C to MIPS compiler (translator?) for Mac OSX? I have GCC installed but the -mips flag generates an error for me. Thanks!

Next time please use a debugger or simulator to step through your code. There were a few obvious errors that you could have noticed yourself.

  1. All your move (pseudo-)instructions are reversed. Should be move destination, source .
  2. You should initialize $s0 with zero at the start, to be safe.
  3. bge $s3, $t4, sumBetween1If3 (line 87) is using the wrong registers (copy-paste error?). It should be bge $s4, $s6, sumBetween1If3
  4. You should delete line 97, as that's useless in its current form, and outright harmful if you swap the operands (it would destroy your sum in $s5 ).
  5. No idea what you wanted to do with lines 98-100, since you don't use $ra or the stack elsewhere. So those lines are messing up both and cause your endless loop. Simply delete those 3 lines.

Funnily enough, your array accesses are all right. There are many possibilities for improvement, though, most notably there is no need to load the array item twice. I assume you intend to remove all the superfluous jumps that just go the next instruction anyway.

The easiest way to check is to compare your assembly code with the output generated by a compiler.

You do not need gcc to do this (and go through all the tedious steps required to create a cross-platform compiler) if you already have clang installed on your machine. Unfortunately, however, the version of clang that's installed on Mac doesn't support mips, so you'll have to either get clang directly from llvm's website, or do it on a linux machine. Once you get clang, simply run

clang -S -target mips -o mips.asm ./your_file.c

and compare your assembly code with the mips.asm file.

I've included output of the command here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM