1 require 'voodoo/generators/common_code_generator'
4 # = MIPS GNU Assembler Code Generator
6 # The MIPS code generator generates assembly code for use with
9 # == Calling Convention
11 # The first four arguments are passed in the registers $4 through $7.
12 # Any additional arguments are passed on the stack, starting at
13 # $sp + 16. Words $sp through $sp + 12 will be available for the called
14 # function to use. $sp will always be a multiple of 8.
16 # The return address for the called function is passed in $31.
18 # When performing a position-independent call, the address of the called
19 # function is passed in $25.
21 # The called function will store its return value in $2.
23 # The called function is required to preserve the values of registers
24 # $16 through $23 and register $30.
26 # This calling convention is compatible with the System V ELF ABI.
30 # Call frames have the following layout:
32 # When a function is called, it receives a stack frame that looks like
43 # empty0 <-- $sp points here
45 # The function prologue of functions generated by this code generator
46 # creates activation frames that look as follows:
56 # arg0 <-- $fp points here
58 # pointer to Global Offset Table
66 # padding <-- $sp points here
70 # The four empty slots provided by the caller are used to store
71 # arguments 0 through 3 (originally passed in $4 through $7),
74 # The stack frame created below the four slots provided by the caller
75 # contains the following data, in order:
77 # - Saved return address (originally passed in $31), if necessary.
79 # - Saved pointer to global offset table (computed from $25), if necessary.
81 # - Saved value of $fp, if necessary.
83 # - Saved values of caller's locals 0 through 7
84 # (originally in $16 through $23), if necessary.
86 # - Values of our locals > 8, if necessary.
88 # - Padding to align $sp on a multiple of 8, if necessary.
91 # In accordance with the System V ELF ABI for MIPS, the pointer to
92 # the global offset table is calculated as follows:
94 # $gp = _gp_disp + $25
96 # where $gp is the register to store the pointer, $25 is the register
97 # holding the address of the called function, and _gp_disp is the
98 # offset between the beginning of the function and the global offset table.
100 class MIPSGasGenerator < CommonCodeGenerator
101 def initialize params
104 @DATA_ALIGNMENT = @WORDSIZE
105 @FP_OFFSET = -3 * @WORDSIZE
106 @FUNCTION_ALIGNMENT = @WORDSIZE
107 @GP_OFFSET = -2 * @WORDSIZE
108 @INITIAL_FRAME_SIZE = 4 * @WORDSIZE
109 @REGISTER_ARG_BASE = 4
111 @REGISTER_LOCAL_BASE = 16
112 @NREGISTER_LOCALS = 8
113 @RA_OFFSET = -@WORDSIZE
118 @TEMPORARIES = [:'$8', :'$9', :'$10', :'$11',
119 :'$12', :'$13', :'$14', :'$15']
120 @function_end_label = nil
124 @output_file_suffix = '.s'
126 :'bits-per-word' => '32',
127 :'bytes-per-word' => '4'
130 @features[:'byte-order'] = 'big-endian'
132 @features[:'byte-order'] = 'little-endian'
134 raise ArgumentError.new("#{self.class} does not support " +
135 "architecture #{@architecture}")
139 # Adds immediate to source and stores the result in target.
140 def addiu target, source, immediate, temporary = @TEMPORARY
141 if immediate >= -32768 && immediate < 32767
142 emit "addiu #{target}, #{source}, #{immediate}\n"
144 emit "lui #{target}, #{(immediate >> 16) & 0xffff}\n"
145 emit "ori #{target}, #{target}, #{immediate & 0xffff}\n"
147 addiu temporary, "$0", immediate
148 emit "addu #{target}, #{source}, #{temporary}\n"
152 def align alignment = nil
154 # Get default alignment
157 alignment = @CODE_ALIGNMENT
159 alignment = @DATA_ALIGNMENT
161 alignment = @FUNCTION_ALIGNMENT
163 # Use data alignment as default
164 alignment = @DATA_ALIGNMENT
167 emit ".align #{alignment}\n" unless alignment == 0
170 # Return the offset from the frame base at which the nth argument is
176 # Return an $fp-relative reference for the nth (0-based) argument
178 offset_reference(arg_offset(n))
181 # Return 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 # Test if op is a binary operation
192 def assymetric_binop? op
193 [:asr, :bsr, :div, :mod, :rol, :ror, :shl, :shr, :sub].member?(op)
196 # Test if a value is an at-expression
198 value.respond_to?(:[]) && value[0] == :'@'
201 def auto_bytes n, register
202 # Maintain stack pointer at a multiple of 8 bytes.
205 emit "move #{register}, $sp\n" unless register == "$sp"
208 def auto_words n, register
209 auto_bytes n * @WORDSIZE, register
212 # Begins a new block.
213 def begin_block *code
214 emit "# begin block\n"
215 # If we are at top-level, create a frame
216 if @environment == @top_level
217 create_frame count_locals(code)
219 environment = Environment.new @environment
220 @environment = environment
223 # Emit function prologue and declare _formals_ as function arguments
224 def begin_function formals, nlocals
225 if @environment != @top_level
226 raise "Cannot begin function when already in a function"
229 environment = Environment.new @environment
231 formals.each {|x| environment.add_arg x, arg_offset(environment.args)}
232 @environment = environment
233 @function_end_label = gensym
234 emit_function_prologue formals, nlocals
237 # Test if op is a binary operation
239 assymetric_binop?(op) || symmetric_binop?(op)
242 # Define a byte with the given value
244 emit ".byte #{value}\n"
249 # Grow the stack frame, subject to 3 conditions:
250 # 1. There must be enough space to hold all arguments
251 # 2. $sp must remain a multiple of 8
252 # 3. We must provide space for at least 4 words
253 increment = ([args.length, 4].max * @WORDSIZE + 7) / 8 * 8
256 # Put arguments in the right places
258 while n < args.length
259 if n < @NREGISTER_ARGS
260 # Put arguments up to @NREGISTER_ARGS in registers
261 load_value_into_register args[n], arg_register(n)
263 # Put other arguments on the stack
264 load_value_into_register args[n], @TEMPORARY
265 emit "sw #{@TEMPORARY}, #{n * @WORDSIZE}($sp)\n"
270 # Load function address
272 if @imports.has_key? func
273 # Load address from global offset table
274 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
276 # Assume label defined in this module
277 emit "lui #{@FUNCTION}, %hi(#{func})\n"
278 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
282 load_value_into_register func, "#{@FUNCTION}"
286 emit "jalr #{@FUNCTION}\n"
290 # Restore original stack frame
291 grow_stack -increment
294 emit "lw #{@GOT}, #{@GP_OFFSET}($fp)\n"
302 # Start a conditional using the specified branch instruction
303 # after the comparison.
304 def common_if comp, x, y = nil
305 emit "# #{comp} #{x} #{y}\n"
307 temporaries = @TEMPORARIES.dup
308 xreg = load_value x, temporaries[0]
309 temporaries.delete xreg
310 yreg = load_value y, temporaries[0]
311 temporaries.delete yreg
313 falselabel = @environment.gensym
314 @if_labels.push falselabel
318 emit "bne #{xreg}, #{yreg}, #{falselabel}\n"
320 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
321 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
323 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
324 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
326 emit "slt #{@TEMPORARY}, #{yreg}, #{xreg}\n"
327 emit "bne #{@TEMPORARY}, $0, #{falselabel}\n"
329 emit "slt #{@TEMPORARY}, #{xreg}, #{yreg}\n"
330 emit "beq #{@TEMPORARY}, $0, #{falselabel}\n"
332 emit "beq #{xreg}, #{yreg}, #{falselabel}\n"
334 raise "Unknown conditional: #{comp}"
339 # Creates an activation frame which can store nlocals local variables
340 def create_frame nlocals
341 @frame_size = @INITIAL_FRAME_SIZE
343 @frame_size = @frame_size + (nlocals * @WORDSIZE + 7) / 8 * 8
345 grow_stack @frame_size
348 # Emit function prologue.
349 def emit_function_prologue formals = [], nlocals = 0
350 # Calculate new value for $gp
351 emit "lui #{@GOT}, %hi(_gp_disp)\n"
352 emit "addiu #{@GOT}, %lo(_gp_disp)\n"
353 emit "addu #{@GOT}, #{@GOT}, #{@FUNCTION}\n"
357 # Save return address
358 emit "sw $31, #{@frame_size - @WORDSIZE}($sp)\n"
361 emit "sw #{@GOT}, #{@frame_size - 2 * @WORDSIZE}($sp)\n"
364 emit "sw $fp, #{@frame_size - 3 * @WORDSIZE}($sp)\n"
366 # Point fp at where sp was before we created the frame
367 addiu "$fp", "$sp", @frame_size
369 # Save parameters 0 .. 3 in the stack space that the caller
370 # should have allocated for them.
371 [@NREGISTER_ARGS, formals.length].min.times do |n|
372 ref = offset_reference(@environment[formals[n]])
373 emit "sw $#{n + @REGISTER_ARG_BASE}, #{ref}\n"
377 # End a function body
379 if @environment == @top_level
380 raise "Cannot end function when not in a function"
383 label @function_end_label
384 # Restore saved locals
385 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
386 emit "lw #{local_register n}, #{local_reference n}\n"
388 # Load return address
389 emit "lw $31, #{@RA_OFFSET}($fp)\n"
390 # Restore stack pointer
391 emit "move $sp, $fp\n"
392 # Restore frame pointer
393 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
398 emit "# end function\n\n"
400 @function_end_label = nil
401 @environment = @top_level
404 # Ends the current block.
408 # If we are returning to top level, restore stack pointer
409 if @environment.parent == @top_level
410 grow_stack -@frame_size
413 # Restore old value of @environment
414 @environment = @environment.parent
419 label = @if_labels.pop
423 # Evaluate the binary operation expr and store the result in register
424 def eval_binop expr, register
425 temporaries = @TEMPORARIES.dup
426 x = load_value expr[1], temporaries[0]
428 y = load_value expr[2], temporaries[0]
433 emit "srav #{register}, #{x}, #{y}\n"
435 emit "srlv #{register}, #{x}, #{y}\n"
437 emit "div $0, #{x}, #{y}\n"
438 emit "mflo #{register}\n"
440 emit "div $0, #{x}, #{y}\n"
441 emit "mfhi #{register}\n"
443 emit "mult #{x}, #{y}\n"
444 emit "mflo #{register}\n"
446 emit "subu #{@TEMPORARY}, $0, #{y}\n"
447 emit "srlv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
448 emit "sllv #{register}, #{x}, #{y}\n"
449 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
451 emit "subu #{@TEMPORARY}, $0, #{y}\n"
452 emit "sllv #{@TEMPORARY}, #{x}, #{@TEMPORARY}\n"
453 emit "srlv #{register}, #{x}, #{y}\n"
454 emit "or #{register}, #{register}, #{@TEMPORARY}\n"
456 emit "sllv #{register}, #{x}, #{y}\n"
458 emit "srlv #{register}, #{x}, #{y}\n"
460 emit "#{expr[0]} #{register}, #{x}, #{y}\n"
464 # Evaluate the expression expr and store the result in register
465 def eval_expr expr, register
468 load_value_into_register expr[0], register
470 # Evaluate expression
474 auto_bytes expr[1], register
476 auto_words expr[1], register
479 emit "move #{register}, #{@RETURN}\n" if register != @RETURN
481 get_byte expr[1], expr[2], register
483 get_word expr[1], expr[2], register
485 eval_binop [:nor, 0, expr[1]], register
488 eval_binop expr, register
490 raise "Not a magic word: #{op}"
496 # Export symbols from the current section
498 symbols.each { |sym| emit ".globl #{sym}\n" }
501 # Load byte from _base_ + _offset_ into _register_
502 def get_byte base, offset, register
503 # If base is an integer, but offset isn't, swap them
504 if !integer?(offset) && integer?(base)
505 base, offset = [offset, base]
509 base_reg = load_value base
510 emit "lb #{register}, #{offset}(#{base_reg})\n"
512 eval_binop [:add, base, offset], @TEMPORARY
513 emit "lb #{register}, 0(#{@TEMPORARY})\n"
517 # Load word from _base_ + _offset_ * _@WORDSIZE_ into _register_
518 def get_word base, offset, register
520 base_reg = load_value base
521 emit "lw #{register}, #{offset * @WORDSIZE}(#{base_reg})\n"
523 offset_reg = @TEMPORARIES.pop
525 load_value_into_register offset, offset_reg
526 base_reg = load_value base
527 emit "sll #{offset_reg}, #{offset_reg}, 2\n" # multiply by @WORDSIZE
528 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
529 emit "lw #{register}, 0(#{@TEMPORARY})\n"
531 @TEMPORARIES.push offset_reg
536 # Test if a symbol refers to a global
538 symbol?(symbol) && @environment[symbol] == nil
547 # Grows the stack by n bytes.
549 addiu "$sp", "$sp", -n
552 # Start the false path of a conditional.
555 newlabel = @environment.gensym
556 emit "j #{newlabel}\n"
558 label = @if_labels.pop
560 @if_labels.push newlabel
563 # Test if x is equal to y
565 common_if :ifeq, x, y
568 # Test if x is greater than or equal to y
570 common_if :ifge, x, y
573 # Test if x is strictly greater than y
575 common_if :ifgt, x, y
578 # Test if x is less than or equal to y
580 common_if :ifle, x, y
583 # Test if x is strictly less than y
585 common_if :iflt, x, y
588 # Test if x different from y
590 common_if :ifne, x, y
593 # Import labels into the current section
595 # Record imported labels in @imports
596 symbols.each { |sym| @imports[sym] = sym }
599 # Test if a value is an integer
601 value.kind_of? Integer
609 # Introduces a new local variable.
610 def let symbol, *expr
611 emit "# let #{symbol} #{expr.join ' '}\n"
612 n = @environment.locals
613 register = local_register n
614 ref = local_reference n
616 # We will use a register to store the value
617 @environment.add_local symbol, register
618 # Save current value of register
619 emit "sw #{register}, #{ref}\n"
621 eval_expr expr, register
623 # We will use the stack to store the value
624 @environment.add_local symbol, local_offset(n)
625 eval_expr expr, @TEMPORARY
626 emit "sw #{@TEMPORARY}, #{ref}\n"
630 # Loads the value at the given address.
631 def load_at address, register = @TEMPORARY
632 load_value_into_register address, register
633 emit "lw #{register}, 0(#{register})\n"
637 # Loads a value into a register.
638 # Returns the name of the register.
639 # If the value was already in a register, the name of that
640 # register is returned.
641 # Else, the value is loaded into a register and the name of
642 # that register is returned. The register to use in that case
643 # may be specified using the optional second argument.
644 def load_value x, register = @TEMPORARY
648 addiu register, "$0", x
651 binding = @environment[x]
652 if binding.kind_of? String
653 # Value is already in a register. Return register name.
655 elsif binding.kind_of? Integer
656 # Load value from memory.
657 emit "lw #{register}, #{offset_reference binding}\n"
661 emit "lui #{register}, %hi(#{x})\n"
662 emit "addiu #{register}, %lo(#{x})\n"
666 load_at x[1], register
668 raise "Don't know how to load #{x.inspect}"
672 # Load a value into a specific register
673 def load_value_into_register x, register
674 reg = load_value x, register
676 emit "move #{register}, #{reg}\n"
680 # Return the offset from the frame base at which the nth local is stored.
681 # For register locals this is the offset at which the saved
682 # value (from the calling function) is stored.
687 # Return an $sp-relative reference for the nth (0-based) local
688 def local_reference n
689 offset_reference(local_offset(n))
692 # Return the register in which the nth local (0-based) is stored, or
693 # nil if not stored in a register
696 "$#{@REGISTER_LOCAL_BASE + n}"
702 # Compute the maximum number of locals that would fit in the current
705 # + 1, because the initial frame size has room for 1 local
706 (@frame_size - @INITIAL_FRAME_SIZE) / @WORDSIZE + 1
709 # Calculate the number of stack arguments,
710 # given the total number of arguments.
711 def number_of_stack_arguments n
712 [0, n - @NREGISTER_ARGS].max
715 # Given an offset relative to the base of the frame, returns
716 # an reference to that memory location.
717 def offset_reference offset
721 # Returns true if the nth (0-based) argument is stored in a register
726 # Returns true if the nth (0-based) local is stored in a register
727 def register_local? n
728 n < @NREGISTER_LOCALS
731 # Return a from a function.
733 # _words_ may contain an expression to be evaluated. The result
734 # of the evaluation is returned from the function.
736 emit "# return #{words.join ' '}\n"
737 # Compute return value and store it in @RETURN
738 eval_expr(words, @RETURN) unless words.empty?
740 goto @function_end_label
743 # Set a variable to the result of evaluating an expression
744 def set symbol, *expr
746 eval_expr expr, @RETURN
747 load_value_into_register symbol.to_s[1..-1].to_sym, @TEMPORARY
748 emit "sw #{@RETURN}, 0(#{@TEMPORARY})\n"
750 x = @environment[symbol]
752 raise "Cannot change value of constant #{symbol}"
753 elsif x.kind_of? String
757 # Should be an integer.
758 eval_expr expr, @TEMPORARY
759 emit "sw #{@TEMPORARY}, #{offset_reference x}\n"
764 # Set the byte at _base_ + _offset_ to _value_
765 def set_byte base, offset, value
766 emit "# set-byte #{base} #{offset} #{value}\n"
767 # If base is an integer, but offset isn't, swap them
768 if !integer?(offset) && integer?(base)
769 base, offset = [offset, base]
772 value_reg = @TEMPORARIES.pop
773 load_value_into_register value, value_reg
776 base_reg = load_value base
777 emit "sb #{value_reg}, #{offset}(#{base_reg})\n"
779 eval_binop [:add, base, offset], @TEMPORARY
780 emit "sb #{value_reg}, 0(#{@TEMPORARY})\n"
783 @TEMPORARIES.push value_reg
787 # Set the word at _base_ + _offset_ * +@WORDSIZE+ to _value_
788 def set_word base, offset, value
789 emit "# set-word #{base} #{offset} #{value}\n"
791 value_reg = @TEMPORARIES.pop
792 load_value_into_register value, value_reg
795 base_reg = load_value base
796 emit "sw #{value_reg}, #{offset * @WORDSIZE}(#{base_reg})\n"
798 offset_reg = @TEMPORARIES.pop
800 load_value_into_register offset, offset_reg
801 base_reg = load_value base
802 emit "sll #{offset_reg}, #{offset_reg}, 2\n"
803 emit "add #{@TEMPORARY}, #{base_reg}, #{offset_reg}\n"
804 emit "sw #{value_reg}, 0(#{@TEMPORARY})\n"
806 @TEMPORARIES.push offset_reg
810 @TEMPORARIES.push value_reg
814 # Define a string with the given value
817 value.each_byte do |b|
820 elsif b >= 32 && b < 127 && b != 34
823 code << sprintf("\\%03o", b)
826 emit ".ascii \"#{code}\"\n"
829 # Test if a value is a symbol
831 value.kind_of? Symbol
834 # Test if op is a symmetric binary operation (i.e. it will yield the
835 # same result if the order of its source operands is changed).
836 def symmetric_binop? op
837 [:add, :and, :mul, :or, :xor].member? op
840 # Call a function, re-using the current call frame if possible.
841 def tail_call func, *args
842 emit "# tail-call #{func} #{args.join ' '}\n"
844 # Compute number of stack arguments
845 nstackargs = number_of_stack_arguments args.length
846 # If we need more stack arguments than we have now,
847 # perform a normal call and return
848 if nstackargs > number_of_stack_arguments(@environment.args)
849 emit "# Not enough space for proper tail call; using regular call\n"
850 ret :call, func, *args
853 # Back up any stack arguments we will need after we overwrite them
854 temporaries = @TEMPORARIES.dup
855 nlocals = @environment.locals
856 (@NREGISTER_ARGS...args.length).each do |i|
857 x = @environment[args[i]]
858 if x && x[0] == :arg && x[1] >= @NREGISTER_ARGS && x[1] < i
859 # args[i] is a stack arg, but has an index < i
860 # That means that, by the time we get to pass arg[i] to the called
861 # function, it will have been overwritten. So we make a backup.
862 if temporaries.empty?
863 # Oh dear, we're out of temporaries.
864 # Store the value in the current stack frame, extending it
866 if nlocals >= max_locals
869 reg = load_value args[i]
870 emit "sw #{reg}, #{local_reference nlocals}\n"
871 args[i] = [:local, nlocals]
872 nlocals = nlocals + 1
874 # Load the argument into a temporary
875 reg = temporaries.shift
876 load_value_into_register args[i], reg
877 # Update args[i] so we know how to get to it later
878 args[i] = [:reg, reg]
883 # Set stack arguments
884 (@NREGISTER_ARGS...args.length).each do |i|
889 if arg.kind_of? Array
890 # Special cases, created above
895 emit "lw #{reg}, #{local_reference arg[1]}\n"
898 load_value_into_register arg, reg
901 # Store value in designated place
902 emit "sw #{reg}, #{arg_reference i}\n"
905 # Set register arguments
906 [@NREGISTER_ARGS,args.length].min.times do |i|
908 load_value_into_register args[i], reg
911 # Load function address
913 if @imports.has_key? func
914 # Load address from global offset table
915 emit "lw #{@FUNCTION}, %call16(#{func})(#{@GOT})\n"
917 # Assume label defined in this module
918 emit "lui #{@FUNCTION}, %hi(#{func})\n"
919 emit "addiu #{@FUNCTION}, %lo(#{func})\n"
923 load_value_into_register func, "#{@FUNCTION}"
926 # Restore saved registers
927 [@NREGISTER_LOCALS, @environment.locals].min.times do |n|
928 emit "lw #{local_register n}, #{local_reference n}\n"
931 # Restore return address
932 emit "lw $31, #{@RA_OFFSET}($fp)\n"
934 # Restore stack pointer
935 emit "move $sp, $fp\n"
937 # Restore frame pointer
938 emit "lw $fp, #{@FP_OFFSET}($fp)\n"
941 emit "jr #{@FUNCTION}\n"
946 # Define a word with the given value
948 emit ".int #{value}\n"
951 # Write generated code to the given IO object.
954 @sections.each do |section,code|
956 io.puts ".section #{section.to_s}"
965 # Register class for big endian MIPS
966 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
967 :architecture => :mips,
971 # Register class for little endian MIPS
972 Voodoo::CodeGenerator.register_generator MIPSGasGenerator,
973 :architecture => :mipsel,