1 require 'voodoo/generators/common_code_generator'
4 # = NASM Code Generator
6 # The NASM code generator is a common base class for generators that output
7 # assembly code for use with the {Netwide Assembler}[http://www.nasm.us/].
9 # This class is used by both the I386NasmGenerator and the
10 # AMD64NasmGenerator, and contains the functionality that is common to
13 # To use the functionality from this class, a subclass must define the
14 # following methods and constants:
18 # - @FUNCTION_ALIGNMENT
20 # - @STACK_ALIGNMENT_BITS
25 # - @AX, @BX, @CX, @DX, @BP, and @SP
26 class NasmGenerator < CommonCodeGenerator
27 def initialize params = {}
30 @output_file_suffix = '.asm'
37 # Export symbols from the current section
39 emit "global #{symbols.join ', '}\n"
42 # Continue execution at the given address
44 with_temporary do |temporary|
45 value_ref = load_value value, temporary
46 emit "jmp #{value_ref}\n"
50 # Import labels into the current section
52 emit "extern #{symbols.join ', '}\n"
55 # Define a label in the current section
64 # Define a byte with the given value
69 # Define a dword with the given value
74 # Define a qword with the given value
79 # Define a string with the given value
83 value.each_byte do |b|
84 if b >= 32 && b < 127 && b != 39
88 code << ',' unless code.empty?
97 code << ',' unless code.empty?
102 code << "'" if in_quote
110 def emit_align alignment
111 emit "align #{alignment}\n"
118 # Emits function epilogue.
119 def emit_function_epilogue formals = []
123 # Ends a function body
125 if @environment == @top_level
126 raise "Cannot end function when not in a function"
128 @environment = @top_level
132 # Returns from a function.
134 # _words_ may contain an expression to be evaluated. The result
135 # of the evaluation is returned from the function.
137 eval_expr(words) unless words.empty?
138 emit_function_epilogue
146 # Begins a new block.
147 def begin_block *code
148 # If entering a block at top level,
149 # Save @BP, then set @BP to @SP
150 if @environment == @top_level
152 emit "mov #{@BP}, #{@SP}\n"
154 environment = Environment.new @environment
155 @environment = environment
158 # Ends the current block.
160 # Restore old value of @environment
161 @environment = @environment.parent
163 # If returning to top level, restore old @BP
164 emit "leave\n" if @environment == @top_level
168 # == Memory Allocation
171 # Allocates n bytes on the stack and stores a pointer to the allocated
172 # memory in the specified register. The number of bytes is rounded up
173 # to the nearest multiple of @STACK_ALIGNMENT.
174 def auto_bytes n, register = @RETURN_REG
175 if n.kind_of? Integer
176 auto_bytes_immediate n, register
178 load_value_into_register n, register
179 auto_bytes_register register, register
183 # Implements auto_bytes where the number of bytes to allocate is given
184 # as an immediate value.
185 def auto_bytes_immediate nbytes, register
186 nbytes = ((nbytes + @STACK_ALIGNMENT - 1) >> @STACK_ALIGNMENT_BITS) <<
187 @STACK_ALIGNMENT_BITS
188 emit "sub #{@SP}, #{nbytes}\n"
189 emit "mov #{register}, #{@SP}\n" if register != @SP
192 # Implements auto_bytes where the number of bytes is supplied in a
194 def auto_bytes_register nbytes, register = @RETURN_REG
195 emit "add #{nbytes}, #{@STACK_ALIGNMENT - 1}\n"
196 emit "shr #{nbytes}, #{@STACK_ALIGNMENT_BITS}\n"
197 emit "shl #{nbytes}, #{@STACK_ALIGNMENT_BITS}\n"
198 emit "sub #{@SP}, #{nbytes}\n"
199 emit "mov #{register}, #{@SP}\n" if register != @SP
202 # Allocates n words on the stack and stores a pointer to the allocated
203 # memory in the specified register.
204 def auto_words n, register = @RETURN_REG
205 if n.kind_of? Integer
206 auto_bytes_immediate n * @WORDSIZE, register
208 load_value_into_register n, register
209 if @STACK_ALIGNMENT_BITS > @WORDSIZE_BITS
210 emit "add #{register}, " +
211 "#{(1 << @STACK_ALIGNMENT_BITS >> @WORDSIZE_BITS) - 1}\n"
212 emit "shr #{register}, #{@STACK_ALIGNMENT_BITS - @WORDSIZE_BITS}\n"
213 emit "shl #{register}, #{STACK_ALIGNMENT_BITS}\n"
215 emit "shl #{register}, #{@WORDSIZE_BITS}\n"
217 emit "sub #{@SP}, #{register}\n"
218 emit "mov #{register}, #{@SP}\n" if register != @SP
226 # Introduces a new local variable.
227 def let symbol, *words
228 loc = local_offset_or_register @environment.locals
229 @environment.add_local symbol, loc
237 # End a conditional body
239 label = @if_labels.pop
244 # == Value Classification
247 # Tests if an operand is an immediate operand
248 def immediate_operand? operand
252 # Tests if an operand is a memory operand
253 def memory_operand? operand
254 operand.kind_of?(String) && operand[0] == ?[
261 # Loads a word into a register.
262 def emit_load_word register, base, offset = 0
264 emit "mov #{register}, [#{base}]\n"
266 emit "mov #{register}, [#{base} + #{offset} * #{@WORDSIZE}]\n"
270 # Create a value reference to an address.
271 # Invoking this code may clobber @BX and/or @CX
272 def load_address base, offset, scale
273 base_ref = load_value base, @BX
274 offset_ref = load_value offset, @CX
278 # Only an integer base
281 # Some complex base; load in @BX
282 emit "mov #{@BX}, #{base_ref}\n"
286 if integer? offset_ref
287 # Only a scaled offset
288 "[#{offset_ref.to_i * scale}]"
290 # Some complex offset; load in @CX
291 emit "mov #{@CX}, #{offset_ref}\n"
292 "[#{@CX} * #{scale}]"
294 elsif integer? base_ref
295 if integer? offset_ref
296 # All integers, combine them together
297 "[#{base_ref.to_i + (offset_ref.to_i * scale)}]"
299 # Complex offset; use @CX
300 emit "mov #{@CX}, #{offset_ref}\n"
301 "[#{base_ref} + #{@CX} * #{scale}]"
303 elsif integer? offset_ref
304 # Complex base, integer offset; use @BX
305 emit "mov #{@BX}, #{base_ref}\n"
306 "[#{@BX} + #{offset_ref.to_i * scale}]"
308 # Both base and offset are complex
309 # Use both @BX and @CX
310 emit "mov #{@BX}, #{base_ref}\n"
311 emit "mov #{@CX}, #{offset_ref}\n"
312 "[#{@BX} + #{@CX} * #{scale}]"
316 # Load the value at the given address.
317 # Invoking this code may clobber @BX.
318 def load_at address, reg
319 if integer?(address) || global?(address)
322 load_value_into_register address, @BX
327 # Loads the value associated with the given symbol.
328 def load_symbol symbol, reg
329 x = @environment[symbol]
332 elsif x.kind_of? Integer
341 # Returns a string that can be used to refer to the loaded value.
342 def load_value value, reg
343 if substitution? value
344 value = substitute_number value[1]
348 if @WORDSIZE > 4 && (value < -2147483648 || value > 2147483647)
349 # AMD64 can load immediate values that are outside the range
350 # that can be represented as a 32-bit signed integer, but
351 # only with a mov instruction that loads the value into a
353 emit "mov #{@WORD_NAME} #{reg}, #{value}\n"
359 load_symbol value, reg
361 load_at value[1], reg
363 raise "Don't know how to load #{value.inspect}"
367 # Loads a value into a register.
368 def load_value_into_register value, register
369 value_ref = load_value value, register
370 set_register register, value_ref
377 # Stores the value of a register in memory.
378 def emit_store_word register, base, offset = 0
380 emit "mov [#{base}], #{register}\n"
382 emit "mov [#{base} + #{offset} * #{@WORDSIZE}], #{register}\n"
386 # Evaluate the expr in words and store the result in target
387 def set target, *words
389 raise "Cannot change value of integer #{target}"
390 elsif global?(target)
391 raise "Cannot change value of global #{target}"
394 if words.length != 1 || words[0] != target
395 if symbol?(target) && symbol?(@environment[target])
396 eval_expr words, @environment[target]
398 eval_expr words, @RETURN_REG
399 target_ref = load_value target, @BX
400 emit "mov #{target_ref}, #{@RETURN_REG}\n"
405 # Set the byte at _base_ + _offset_ to _value_
406 def set_byte base, offset, value
407 if immediate_operand?(value)
410 load_value_into_register value, @RETURN_REG
413 addr_ref = load_address base, offset, 1
414 emit "mov byte #{addr_ref}, #{value_ref}\n"
417 # Set the word at _base_ + _offset_ * +@WORDSIZE+ to _value_
418 def set_word base, offset, value
419 if immediate_operand?(value)
420 value_ref = load_value value, @RETURN_REG
422 load_value_into_register value, @RETURN_REG
423 value_ref = @RETURN_REG
425 addr_ref = load_address base, offset, @WORDSIZE
426 emit "mov #{@WORD_NAME} #{addr_ref}, #{value_ref}\n"
429 # Divide x by y and store the quotient in target
432 target_ref = load_value target, @BX
433 emit "mov #{target_ref}, #{@AX}\n"
436 # Divide target by x and store the quotient in target
438 div target, target, x
441 # Divide x by y and store the remainder in target
444 target_ref = load_value target, @BX
445 emit "mov #{target_ref}, #{@DX}\n"
448 # Divide target by x and store the remainder in target
450 mod target, target, x
453 # Multiply x by y and store the result in target
456 target_ref = load_value target, @BX
457 emit "mov #{target_ref}, #{@RETURN_REG}\n"
460 # Multiply target by x and store the result in target
462 mul target, target, x
470 # The quotient is stored in @AX, the remainder in @DX.
472 with_temporary do |temporary|
473 x_ref = load_value_into_register x, @AX
474 y_ref = load_value y, temporary
475 emit "mov #{@DX}, #{@AX}\n"
476 emit "sar #{@DX}, #{@WORDSIZE * 8 - 1}\n"
477 if immediate_operand?(y_ref)
478 set_register @BX, y_ref
481 emit "idiv #{@WORD_NAME} #{y_ref}\n"
486 # Evaluate an expression.
487 # The result is stored in _register_ (@RETURN_REG by default).
488 # The following registers may be clobbered: @AX, @BX, @CX, @DX
489 def eval_expr words, register = @RETURN_REG
492 emit "xor #{register}, #{register}\n"
494 load_value_into_register words[0], register
499 when :asr, :bsr, :rol, :ror, :shl, :shr
503 load_value_into_register words[2], @CX
506 load_value_into_register words[1], register
507 emit "#{action_to_mnemonic op} #{register}, #{y_ref}\n"
509 auto_bytes words[1], register
511 auto_words words[1], register
514 emit "mov #{register}, #{@RETURN_REG}\n" if register != @RETURN_REG
516 eval_div words[1], words[2]
517 set_register register, @AX
519 # Get address reference
520 address_ref = load_address words[1], words[2], 1
521 # Load byte from address
524 set_register register, 0
525 set_register :al, address_ref
527 set_register register, 0
528 set_register :bl, address_ref
530 set_register register, 0
531 set_register :cl, address_ref
533 set_register register, 0
534 set_register :dl, address_ref
537 set_register :al, address_ref
538 set_register register, @AX
541 address_ref = load_address words[1], words[2], @WORDSIZE
542 set_register register, address_ref
544 eval_div words[1], words[2]
545 set_register register, @DX
547 eval_mul words[1], words[2], register
549 load_value_into_register words[1], register
550 emit "not #{register}\n"
553 x_ref = load_value words[1], @DX
554 y_ref = load_value words[2], @BX
555 emit "mov #{register}, #{x_ref}\n" unless register == x_ref
556 emit "#{op} #{register}, #{y_ref}\n"
558 raise "Not a magic word: #{words[0]}"
565 # The result is stored in @AX by default, but
566 # a different register can be specified by passing
568 def eval_mul x, y, register = @AX
569 x_ref = load_value x, @DX
570 y_ref = load_value y, @BX
572 if immediate_operand? x_ref
573 if immediate_operand? y_ref
574 set_register register, x_ref * y_ref
576 emit "imul #{register}, #{y_ref}, #{x_ref}\n"
578 elsif immediate_operand? y_ref
579 emit "imul #{register}, #{x_ref}, #{y_ref}\n"
580 elsif y_ref != register
581 emit "mov #{register}, #{x_ref}\n" unless x_ref == register
582 emit "imul #{register}, #{y_ref}\n"
584 emit "imul #{register}, #{x_ref}\n"
592 # Start a conditional using the specified branch instruction
593 # after the comparison.
594 def common_if branch, x, y = nil
595 # Inverses of branches. E.g.
610 y_ref = load_value y, @DX
611 x_ref = load_value x, @AX
612 if immediate_operand?(x_ref)
613 # Can't have an immediate value as the first operand.
614 if immediate_operand?(y_ref)
615 # Both are immediates. Put the first in a register.
616 emit "mov #{@AX}, #{x_ref}\n"
619 # y isn't immediate; swap x and y.
620 x_ref, y_ref = [y_ref, x_ref]
621 branch = inverse_branch[branch]
623 elsif memory_operand?(x_ref) && memory_operand?(y_ref)
624 # Can't have two memory operands. Move the first into a register.
625 emit "mov #{@AX}, #{x_ref}\n"
628 truelabel = @environment.gensym
629 falselabel = @environment.gensym
630 @if_labels.push falselabel
632 emit "cmp #{@WORD_NAME} #{x_ref}, #{y_ref}\n"
633 emit "#{branch} #{truelabel}\n"
634 emit "jmp #{falselabel}\n"
635 emit "#{truelabel}:\n"
640 label = @if_labels.pop
644 # Start the false path of a conditional.
646 newlabel = @environment.gensym
647 emit "jmp #{newlabel}\n"
648 label = @if_labels.pop
650 @if_labels.push newlabel
653 # Test if x is equal to y
658 # Test if x is greater than or equal to y
663 # Test if x is strictly greater than y
668 # Test if x is less than or equal to y
673 # Test if x is strictly less than y
678 # Test if x different from y
687 # Translates a Voodoo action name to an x86 mnemonic
688 def action_to_mnemonic action
704 # Returns a memory reference for the address at the given offset
705 # from the frame pointer.
706 def offset_reference offset
708 "[#{@BP} + #{offset}]"
710 "[#{@BP} - #{-offset}]"
716 # Set a register to a value.
717 # The value must be a valid operand to the mov instruction.
718 def set_register register, value_ref
723 emit "xor #{register}, #{register}\n"
725 emit "mov #{register}, #{value_ref}\n"
733 # Write generated code to the given IO object.
735 io.puts "bits #{@WORDSIZE * 8}\n\n"
736 @sections.each do |section,code|
738 io.puts "section #{section.to_s}"