1 require 'voodoo/generators/common_code_generator'
5 # = MIPS GNU Assembler Code Generator
7 # The MIPS code generator generates assembly code for use with
10 # == Calling Convention
12 # The first four arguments are passed in the registers $4 through $7.
13 # Any additional arguments are passed on the stack, starting at
14 # $sp + 16. Words $sp through $sp + 12 will be available for the called
15 # function to use. $sp will always be a multiple of 8.
17 # The return address for the called function is passed in $31.
19 # When performing a position-independent call, the address of the called
20 # function is passed in $25.
22 # The called function will store its return value in $2.
24 # The called function is required to preserve the values of registers
25 # $16 through $23 and register $30.
27 # This calling convention is compatible with the System V ELF ABI.
31 # Call frames have the following layout:
33 # When a function is called, it receives a stack frame that looks like
44 # empty0 <-- $sp points here
46 # The function prologue of functions generated by this code generator
47 # creates activation frames that look as follows:
57 # arg0 <-- $fp points here
59 # pointer to Global Offset Table
67 # padding <-- $sp points here
71 # The four empty slots provided by the caller are used to store
72 # arguments 0 through 3 (originally passed in $4 through $7),
75 # The stack frame created below the four slots provided by the caller
76 # contains the following data, in order:
78 # - Saved return address (originally passed in $31), if necessary.
80 # - Saved pointer to global offset table (computed from $25), if necessary.
82 # - Saved value of $fp, if necessary.
84 # - Saved values of caller's locals 0 through 7
85 # (originally in $16 through $23), if necessary.
87 # - Values of our locals > 8, if necessary.
89 # - Padding to align $sp on a multiple of 8, if necessary.
92 # In accordance with the System V ELF ABI for MIPS, the pointer to
93 # the global offset table is calculated as follows:
95 # $gp = _gp_disp + $25
97 # where $gp is the register to store the pointer, $25 is the register
98 # holding the address of the called function, and _gp_disp is the
99 # offset between the beginning of the function and the global offset table.
101 # Callee-Save Registers
103 # Registers $16 through $23 and $28 through $30 are callee-save.
105 # All other registers are caller-save.
107 class MIPSGasGenerator < CommonCodeGenerator
108 def initialize params
110 @WORDSIZE = 1 << @WORDSIZE_BITS
112 @DATA_ALIGNMENT = @WORDSIZE
113 @STACK_ALIGNMENT_BITS = 3
114 @STACK_ALIGNMENT = 1 << @STACK_ALIGNMENT_BITS
115 @FP_OFFSET = -3 * @WORDSIZE
116 @FUNCTION_ALIGNMENT = @WORDSIZE
117 @GP_OFFSET = -2 * @WORDSIZE
118 @INITIAL_FRAME_SIZE = 4 * @WORDSIZE
119 @REGISTER_ARG_BASE = 4
121 @LOCAL_REGISTERS = [:'$16', :'$17', :'$18', :'$19',
122 :'$20', :'$21', :'$22', :'$23']
123 @LOCAL_REGISTERS_SET = Set.new @LOCAL_REGISTERS
124 @REGISTER_LOCAL_BASE = 16
125 @NREGISTER_LOCALS = @LOCAL_REGISTERS.length
126 @RA_OFFSET = -@WORDSIZE
131 @SAVE_FRAME_REGISTERS = [:'$16', :'$17', :'$18', :'$19', :'$20',
132 :'$21', :'$22', :'$23', :'$28', :'$29',
134 @SAVED_FRAME_LAYOUT = {}
135 @SAVE_FRAME_REGISTERS.each_with_index { |r,i| @SAVED_FRAME_LAYOUT[r] = i }
136 @TEMPORARIES = [:'$8', :'$9', :'$10', :'$11',
137 :'$12', :'$13', :'$14', :'$15']
138 @function_end_label = nil
142 @output_file_suffix = '.s'
144 :'bits-per-word' => '32',
145 :'bytes-per-word' => '4'
148 @features[:'byte-order'] = 'big-endian'
150 @features[:'byte-order'] = 'little-endian'
152 raise ArgumentError.new("#{self.class} does not support " +
153 "architecture #{@architecture}")
157 # Adds immediate to source and stores the result in target.
158 def addiu target, source, immediate, temporary = @TEMPORARY
159 if immediate >= -32768 && immediate < 32767
160 emit "addiu #{target}, #{source}, #{immediate}\n"
162 emit "lui #{target}, #{(immediate >> 16) & 0xffff}\n"
163 emit "ori #{target}, #{target}, #{immediate & 0xffff}\n"
165 addiu temporary, "$0", immediate
166 emit "addu #{target}, #{source}, #{temporary}\n"
170 # Return the offset from the frame base at which the nth argument is
176 # Returns an $fp-relative reference for the nth (0-based) argument.
178 offset_reference(arg_offset(n))
181 # Returns the register in which the nth (0-based) argument is stored, or
182 # nil if not stored in a register.
185 "$#{@REGISTER_ARG_BASE + n}"
191 def auto_bytes n, register
192 if n.kind_of? Integer
193 # Maintain stack alignment
194 n = (n + @STACK_ALIGNMENT - 1) / @STACK_ALIGNMENT * @STACK_ALIGNMENT
197 temporary = @TEMPORARIES.pop
199 load_value_into_register n, register
200 emit "addi #{register}, #{@STACK_ALIGNMENT - 1}\n"
201 emit "li #{temporary}, -#{@STACK_ALIGNMENT}\n"
202 emit "and #{register}, #{register}, #{temporary}\n"
203 emit "sub $sp, #{register}\n"
205 @TEMPORARIES.push temporary
208 emit "move #{register}, $sp\n" unless register == "$sp"
211 def auto_words n, register
212 if n.kind_of? Integer
213 auto_bytes n * @WORDSIZE, register
215 load_value_into_register n, register
216 if @STACK_ALIGNMENT_BITS > @WORDSIZE_BITS
217 bits = @STACK_ALIGNMENT_BITS - @WORDSIZE_BITS
218 emit "addi #{register}, #{(1 << bits) - 1}\n"
219 emit "srl #{register}, #{register}, #{bits}\n"
220 emit "sll #{register}, #{register}, #{@STACK_ALIGNMENT_BITS}\n"
222 emit "sll #{register}, #{register}, #{@WORDSIZE_BITS}\n"
224 emit "sub $sp, $sp, #{register}\n"
225 emit "move #{register}, $sp\n" unless register == "$sp"
229 # Begins a new block.
230 def begin_block *code
231 # If we are at top-level, create a frame
232 if @environment == @top_level
233 create_frame count_locals(code)
235 environment = Environment.new @environment
236 @environment = environment
239 # Emits function prologue and declare _formals_ as function arguments.
240 def begin_function formals, nlocals
241 if @environment != @top_level
242 raise "Cannot begin function when already in a function"
245 environment = Environment.new @environment
247 formals.each {|x| environment.add_arg x, arg_offset(environment.args)}
248 @environment = environment
249 @function_end_label = gensym
250 emit_function_prologue formals, nlocals
253 # Defines a byte with the given value.
255 emit ".byte #{value}\n"
260 # Grow the stack frame, subject to 3 conditions:
261 # 1. There must be enough space to hold all arguments
262 # 2. $sp must remain a multiple of 8
263 # 3. We must provide space for at least 4 words
264 increment = ([args.length, 4].max * @WORDSIZE + 7) / 8 * 8
267 # Put arguments in the right places
269 while n < args.length
270 if n < @NREGISTER_ARGS
271 # Put arguments up to @NREGISTER_ARGS in registers
272 load_value_into_register args[n], arg_register(n)
274 # Put other arguments on the stack
275 load_value_into_register args[n], @TEMPORARY
276 emit "sw #{@TEMPORARY}, #{n * @WORDSIZE}($sp)\n"
281 # Load function address
283 if @imports.has_key? func
284 # Load address from global offset table
285 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
287 # Assume label defined in this module
288 emit "lui #{@FUNCTION}, %hi(#{func})\n"
289 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
293 load_value_into_register func, "#{@FUNCTION}"
297 emit "jalr #{@FUNCTION}\n"
301 # Restore original stack frame
302 grow_stack -increment
305 emit "lw #{@GOT}, #{@GP_OFFSET}($fp)\n"
313 # Starts a conditional using the specified branch instruction
314 # after the comparison.
315 def common_if comp, x, y = nil
316 temporaries = @TEMPORARIES.dup
317 xreg = load_value x, temporaries[0]
318 temporaries.delete xreg
319 yreg = load_value y, temporaries[0]
320 temporaries.delete yreg
322 falselabel = @environment.gensym
323 @if_labels.push falselabel
327 emit "bne #{xreg}, #{yreg}, #{falselabel}\n"
329 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
330 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
332 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
333 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
335 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
336 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
338 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
339 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
341 emit "beq #{xreg}, #{yreg}, #{falselabel}\n"
343 raise "Unknown conditional: #{comp}"
348 # Creates an activation frame which can store nlocals local variables.
349 def create_frame nlocals
350 @frame_size = @INITIAL_FRAME_SIZE
352 @frame_size = @frame_size + (nlocals * @WORDSIZE + 7) / 8 * 8
354 grow_stack @frame_size
357 def emit_align alignment
358 emit ".align #{alignment}\n"
361 # Emits function prologue.
362 def emit_function_prologue formals = [], nlocals = 0
363 # Calculate new value for $gp
364 emit "lui #{@GOT}, %hi(_gp_disp)\n"
365 emit "addiu #{@GOT}, %lo(_gp_disp)\n"
366 emit "addu #{@GOT}, #{@GOT}, #{@FUNCTION}\n"
370 # Save return address
371 emit "sw $31, #{@frame_size - @WORDSIZE}($sp)\n"
374 emit "sw #{@GOT}, #{@frame_size - 2 * @WORDSIZE}($sp)\n"
377 emit "sw $fp, #{@frame_size - 3 * @WORDSIZE}($sp)\n"
379 # Point fp at where sp was before we created the frame
380 addiu "$fp", "$sp", @frame_size
382 # Save parameters 0 .. 3 in the stack space that the caller
383 # should have allocated for them.
384 [@NREGISTER_ARGS, formals.length].min.times do |n|
385 ref = offset_reference(@environment[formals[n]])
386 emit "sw $#{n + @REGISTER_ARG_BASE}, #{ref}\n"
390 # Loads a word into a register.
391 def emit_load_word register, base, offset
392 emit "lw #{register}, #{offset * @WORDSIZE}(#{base})\n"
395 # Stores the value of a register in memory.
396 def emit_store_word register, base, offset
397 emit "sw #{register}, #{offset * @WORDSIZE}(#{base})\n"
400 # Ends a function body.
402 if @environment == @top_level
403 raise "Cannot end function when not in a function"
406 label @function_end_label
407 # Restore saved locals
408 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
409 emit "lw #{local_register n}, #{local_reference n}\n"
411 # Load return address
412 emit "lw $31, #{@RA_OFFSET}($fp)\n"
413 # Restore stack pointer
414 emit "move $sp, $fp\n"
415 # Restore frame pointer
416 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
421 @function_end_label = nil
422 @environment = @top_level
425 # Ends the current block.
427 # If we are returning to top level, restore stack pointer
428 if @environment.parent == @top_level
429 grow_stack -@frame_size
432 # Restore old value of @environment
433 @environment = @environment.parent
436 # Ends a conditional.
438 label = @if_labels.pop
442 # Evaluates the binary operation expr and store the result in register.
443 def eval_binop expr, register
444 temporaries = @TEMPORARIES.dup
445 x = load_value expr[1], temporaries[0]
447 y = load_value expr[2], temporaries[0]
452 emit "srav #{register}, #{x}, #{y}\n"
454 emit "srlv #{register}, #{x}, #{y}\n"
456 emit "div $0, #{x}, #{y}\n"
457 emit "mflo #{register}\n"
459 emit "div $0, #{x}, #{y}\n"
460 emit "mfhi #{register}\n"
462 emit "mult #{x}, #{y}\n"
463 emit "mflo #{register}\n"
465 emit "subu #{@TEMPORARY}, $0, #{y}\n"
466 emit "srlv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
467 emit "sllv #{register}, #{x}, #{y}\n"
468 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
470 emit "subu #{@TEMPORARY}, $0, #{y}\n"
471 emit "sllv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
472 emit "srlv #{register}, #{x}, #{y}\n"
473 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
475 emit "sllv #{register}, #{x}, #{y}\n"
477 emit "srlv #{register}, #{x}, #{y}\n"
479 emit "#{expr[0]} #{register}, #{x}, #{y}\n"
483 # Evaluates the expression expr and store the result in register.
484 def eval_expr expr, register
487 load_value_into_register expr[0], register
489 # Evaluate expression
493 auto_bytes expr[1], register
495 auto_words expr[1], register
498 emit "move #{register}, #{@RETURN}\n" if register != @RETURN
500 get_byte expr[1], expr[2], register
502 get_word expr[1], expr[2], register
504 eval_binop [:nor, 0, expr[1]], register
507 eval_binop expr, register
509 raise "Not a magic word: #{op}"
515 # Exports symbols from the current section.
517 symbols.each { |sym| emit ".globl #{sym}\n" }
520 # Loads byte from _base_ + _offset_ into _register_.
521 def get_byte base, offset, register
522 # If base is an integer, but offset isn't, swap them
523 if !integer?(offset) && integer?(base)
524 base, offset = [offset, base]
528 base_reg = load_value base
529 emit "lb #{register}, #{offset}(#{base_reg})\n"
531 eval_binop [:add, base, offset], @TEMPORARY
532 emit "lb #{register}, 0(#{@TEMPORARY})\n"
536 # Loads word from _base_ + _offset_ * _@WORDSIZE_ into _register_.
537 def get_word base, offset, register
539 base_reg = load_value base
540 emit "lw #{register}, #{offset * @WORDSIZE}(#{base_reg})\n"
542 offset_reg = @TEMPORARIES.pop
544 load_value_into_register offset, offset_reg
545 base_reg = load_value base
546 emit "sll #{offset_reg}, #{offset_reg}, 2\n" # multiply by @WORDSIZE
547 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
548 emit "lw #{register}, 0(#{@TEMPORARY})\n"
550 @TEMPORARIES.push offset_reg
555 # Jumps to an address.
558 emit "j #{address}\n"
560 register = load_value address, @TEMPORARY
561 emit "jr #{register}\n"
566 # Grows the stack by n bytes.
568 addiu "$sp", "$sp", -n
571 # Starts the false path of a conditional.
573 newlabel = @environment.gensym
574 emit "j #{newlabel}\n"
576 label = @if_labels.pop
578 @if_labels.push newlabel
581 # Tests if x is equal to y
583 common_if :ifeq, x, y
586 # Tests if x is greater than or equal to y
588 common_if :ifge, x, y
591 # Tests if x is strictly greater than y
593 common_if :ifgt, x, y
596 # Tests if x is less than or equal to y
598 common_if :ifle, x, y
601 # Tests if x is strictly less than y
603 common_if :iflt, x, y
606 # Tests if x different from y
608 common_if :ifne, x, y
611 # Imports labels into the current section.
613 # Record imported labels in @imports
614 symbols.each { |sym| @imports[sym] = sym }
622 # Introduces a new local variable.
623 def let symbol, *expr
624 n = @environment.locals
625 register = local_register n
626 ref = local_reference n
628 # We will use a register to store the value
629 @environment.add_local symbol, register
630 # Save current value of register
631 emit "sw #{register}, #{ref}\n"
633 eval_expr expr, register
635 # We will use the stack to store the value
636 @environment.add_local symbol, local_offset(n)
637 eval_expr expr, @TEMPORARY
638 emit "sw #{@TEMPORARY}, #{ref}\n"
642 # Loads the value at the given address.
643 def load_at address, register = @TEMPORARY
644 load_value_into_register address, register
645 emit "lw #{register}, 0(#{register})\n"
649 # Loads a value into a register.
650 # Returns the name of the register.
651 # If the value was already in a register, the name of that
652 # register is returned.
653 # Else, the value is loaded into a register and the name of
654 # that register is returned. The register to use in that case
655 # may be specified using the optional second argument.
656 def load_value x, register = @TEMPORARY
658 x = substitute_number x[1]
664 addiu register, "$0", x
667 binding = @environment[x]
669 # Value is already in a register. Return register name.
671 elsif binding.kind_of? Integer
672 # Load value from memory.
673 emit "lw #{register}, #{offset_reference binding}\n"
677 emit "lui #{register}, %hi(#{x})\n"
678 emit "addiu #{register}, %lo(#{x})\n"
682 load_at x[1], register
684 raise "Don't know how to load #{x.inspect}"
688 # Loads a value into a specific register.
689 def load_value_into_register x, register
690 reg = load_value x, register
692 emit "move #{register}, #{reg}\n"
696 # Returns the offset from the frame base at which the nth local is stored.
697 # For register locals this is the offset at which the saved
698 # value (from the calling function) is stored.
703 # Returns an $sp-relative reference for the nth (0-based) local.
704 def local_reference n
705 offset_reference(local_offset(n))
708 # Returns the register in which the nth local (0-based) is stored, or
709 # nil if not stored in a register.
714 # Computes the maximum number of locals that would fit in the current
717 # + 1, because the initial frame size has room for 1 local
718 (@frame_size - @INITIAL_FRAME_SIZE) / @WORDSIZE + 1
721 # Given an offset relative to the base of the frame, returns
722 # an reference to that memory location.
723 def offset_reference offset
727 # Returns true if the nth (0-based) local is stored in a register.
728 def register_local? n
729 n < @NREGISTER_LOCALS
732 # Returns from a function.
734 # _words_ may contain an expression to be evaluated. The result
735 # of the evaluation is returned from the function.
737 # Compute return value and store it in @RETURN
738 eval_expr(words, @RETURN) unless words.empty?
740 goto @function_end_label
743 # Saves the current frame at the given location.
744 def save_frame location
745 load_value_into_register location, @TEMPORARY
746 @SAVE_FRAME_REGISTERS.each_with_index do |register,i|
747 emit "sw #{register}, #{i * @WORDSIZE}(#{@TEMPORARY})\n"
751 # Sets a variable to the result of evaluating an expression.
752 def set symbol, *expr
754 eval_expr expr, @RETURN
755 load_value_into_register symbol.to_s[1..-1].to_sym, @TEMPORARY
756 emit "sw #{@RETURN}, 0(#{@TEMPORARY})\n"
758 x = @environment[symbol]
760 raise "Cannot change value of constant #{symbol}"
764 # Should be an integer.
765 eval_expr expr, @TEMPORARY
766 emit "sw #{@TEMPORARY}, #{offset_reference x}\n"
771 # Sets the byte at _base_ + _offset_ to _value_.
772 def set_byte base, offset, value
773 # If base is an integer, but offset isn't, swap them
774 if !integer?(offset) && integer?(base)
775 base, offset = [offset, base]
778 value_reg = @TEMPORARIES.pop
779 load_value_into_register value, value_reg
782 base_reg = load_value base
783 emit "sb #{value_reg}, #{offset}(#{base_reg})\n"
785 eval_binop [:add, base, offset], @TEMPORARY
786 emit "sb #{value_reg}, 0(#{@TEMPORARY})\n"
789 @TEMPORARIES.push value_reg
793 # Sets the word at _base_ + _offset_ * +@WORDSIZE+ to _value_.
794 def set_word base, offset, value
795 value_reg = @TEMPORARIES.pop
796 load_value_into_register value, value_reg
799 base_reg = load_value base
800 emit "sw #{value_reg}, #{offset * @WORDSIZE}(#{base_reg})\n"
802 offset_reg = @TEMPORARIES.pop
804 load_value_into_register offset, offset_reg
805 base_reg = load_value base
806 emit "sll #{offset_reg}, #{offset_reg}, 2\n"
807 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
808 emit "sw #{value_reg}, 0(#{@TEMPORARY})\n"
810 @TEMPORARIES.push offset_reg
814 @TEMPORARIES.push value_reg
818 # Defines a string with the given value.
821 value.each_byte do |b|
824 elsif b >= 32 && b < 127 && b != 34
827 code << sprintf("\\%03o", b)
830 emit ".ascii \"#{code}\"\n"
833 # Calls a function, re-using the current call frame if possible.
834 def tail_call func, *args
835 # Compute number of stack arguments
836 nstackargs = number_of_stack_arguments args.length
837 # If we need more stack arguments than we have now,
838 # perform a normal call and return
839 if nstackargs > number_of_stack_arguments(@environment.args)
840 emit "# Not enough space for proper tail call; using regular call\n"
841 ret :call, func, *args
844 # Back up any stack arguments we will need after we overwrite them
845 temporaries = @TEMPORARIES.dup
846 nlocals = @environment.locals
847 (@NREGISTER_ARGS...args.length).each do |i|
848 x = @environment[args[i]]
849 if integer?(x) && x < arg_offset(i)
850 # args[i] is in a location that will have been overwritten by the
851 # time we get around to passing argument i to the called function.
852 # Make a backup of the value before we overwrite it.
853 if temporaries.empty?
854 # Oh dear, we're out of temporaries.
855 # Store the value in the current stack frame, extending it
857 if nlocals >= max_locals
860 reg = load_value args[i]
861 emit "sw #{reg}, #{local_reference nlocals}\n"
862 args[i] = [:local, nlocals]
863 nlocals = nlocals + 1
865 # Load the argument into a temporary
866 reg = temporaries.shift
867 load_value_into_register args[i], reg
868 # Update args[i] so we know how to get to it later
869 args[i] = [:reg, reg]
874 # Set stack arguments
875 (@NREGISTER_ARGS...args.length).each do |i|
880 if arg.kind_of? Array
881 # Special cases, created above
886 emit "lw #{reg}, #{local_reference arg[1]}\n"
889 load_value_into_register arg, reg
892 # Store value in designated place
893 emit "sw #{reg}, #{arg_reference i}\n"
896 # Set register arguments
897 [@NREGISTER_ARGS,args.length].min.times do |i|
899 load_value_into_register args[i], reg
902 # Load function address
904 if @imports.has_key? func
905 # Load address from global offset table
906 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
908 # Assume label defined in this module
909 emit "lui #{@FUNCTION}, %hi(#{func})\n"
910 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
914 load_value_into_register func, "#{@FUNCTION}"
917 # Restore saved registers
918 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
919 emit "lw #{local_register n}, #{local_reference n}\n"
922 # Restore return address
923 emit "lw $31, #{@RA_OFFSET}($fp)\n"
925 # Restore stack pointer
926 emit "move $sp, $fp\n"
928 # Restore frame pointer
929 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
932 emit "jr #{@FUNCTION}\n"
937 # Defines a word with the given value
939 emit ".int #{value}\n"
942 # Write generated code to the given IO object.
945 @sections.each do |section,code|
947 io.puts ".section #{section.to_s}"
956 # Register class for big endian MIPS
957 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
958 :architecture => :mips,
962 # Register class for little endian MIPS
963 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
964 :architecture => :mipsel,