Franck Pommereau

added insertion of external libraries

......@@ -7,10 +7,10 @@ def _lnomap (line) :
except :
pass
def cpp (path, arch, args) :
def cpp (path, args) :
lmap = {}
code = []
args = ["cpp", "-D__CCT__", "-D__CCT_%s__" % arch] + args + [path]
args = ["cpp", "-D__CCT__"] + args + [path]
pos = 1
out = subprocess.check_output(args)
for line in (l.rstrip() for l in out.decode().splitlines()) :
......
import io, os.path
import io, os.path, re
from . import cparse
from .cvisitors import Visitor
......@@ -123,12 +123,14 @@ class CodeGenVisitor (Visitor) :
def __init__(self, path, test=None):
Visitor.__init__(self)
self.path = path
self._lbl = re.sub("[^a-z0-9]", "", os.path.splitext(path)[0],
flags=re.I)
self.test = test
self.str_literal_str = io.StringIO()
self.str_literal_dict = {}
def new_label(self):
label = "_L%d" % self.__label
label = "_%s_L%d" % (self._lbl, self.__label)
self.__class__.__label += 1
return label
......@@ -181,21 +183,22 @@ class CodeGenVisitor (Visitor) :
self._visitList(node.nodes)
@classmethod
def concat (cls, outfile, chunks) :
def concat (cls, boot, outfile, chunks) :
outfile.write("# Generated by cct\n"
"# Franck Pommereau (2018)\n"
"# Adapted from Atul Varma's c.py (Spring 2004)\n\n")
outfile.write("#\n"
"# on computer start: call main and halt\n"
"#\n\n"
"IRQ0:\n"
" set R9 @main\n"
" call R9\n"
" halt\n")
if boot :
outfile.write("#\n"
"# on computer start: call main and halt\n"
"#\n\n"
"IRQ0:\n"
" set R9 @%s\n"
" call R9\n"
" halt\n\n" % boot)
for c in chunks :
s = c.curr_str.getvalue()
if s.strip() :
outfile.write("\n#\n# code from file %r\n#\n" % c.path)
outfile.write("#\n# code from file %r\n#\n" % c.path)
outfile.write(s)
for c in chunks :
s = c.globals_str.getvalue()
......@@ -366,7 +369,7 @@ class CodeGenVisitor (Visitor) :
if str in self.str_literal_dict :
return self.str_literal_dict[str]
label_str = "_LC%d" % self.__str_literal_label
label_str = "_%s_LC%d" % (self._lbl, self.__str_literal_label)
self.str_literal_dict[str] = label_str
str = str.replace('\n', '\\n')
self.str_literal_str.write("""%s:\n str "%s\\0"\n""" % (label_str, str))
......
# cx86.py: modified by Franck Pommereau (2018)
# ---------------------------------------------------------------
# cx86.py
#
# Atul Varma
# Python C Compiler - Intel x86 Code Generator
# $Id: cx86.py,v 1.3 2004/06/02 21:05:23 varmaa Exp $
# ---------------------------------------------------------------
import io, os.path
from . import cparse
from .cvisitors import Visitor
# ---------------------------------------------------------------
# CONSTANTS
# ---------------------------------------------------------------
# Size of the 'int' type.
INT_SIZE = 4
# Size of the 'char' type.
CHAR_SIZE = 1
# The machine's word size. Note that making this different
# from INT_SIZE may cause serious problems.
WORD_SIZE = 4
# This is a strange multiplier that needs to be used in the allocation
# of global variables for the GNU Assembler. Not sure exactly what it
# represents.
WEIRD_MULTIPLIER = 4
# ---------------------------------------------------------------
# STACK MACHINE ABSTRACTION
# ---------------------------------------------------------------
class x86Registers:
"""This class attempts to abstract the x86 registers into a stack
machine. Calling push() gives you a register that isn't currently
in use by the stack machine, pop() gives you a register with the
value of the most recently pushed element.
Through this method the stack machine can be used to compute
values the same way a reverse polish notation (RPN) calculator
does.
When push() and pop() are called, it may be the case that no
registers are currently available; if this happens, the least
recently used register is 'spilled' into a temporary local
variable on the process' stack and freed for use. Note that the
process' stack is not to be confused with this stack machine
abstraction--the two are completely different entities.
Currently, push() and pop() also implement a little bit of
implicit type conversion, so they take as parameters a cparse.Type
object; currently conversion is done between char and int types,
so depending on the pushed and popped types, some type conversion
assembly code may be generated.
Finally, an additional method, done(), should be called whenever
the stack machine is done popping values for the current
operation. This is because when pop is called, the returned
register is not immediately made 'free' for another call to pop or
push. If this were the case, then the following situation could
occur:
rightOp.calc() # calc val of right op, put on stack
leftOp.calc() # calc val of left op, put on stack
l = leftOp.pop() # pop left val from stack
r = rightOp.pop() # pop right val from stack
output('addl %s, %s' % (r, l))
The problem with this approach is that we don't know how many
registers will be used by leftOp's calc() method--it may use all
the remaining registers, in which case the value that rightOp's
calc() method put on the stack is no longer stored in a register.
If leftOp.pop() returned register %eax and immediately marked the
%eax register as being 'free for use', then the call to
rightOp.pop() could very well generate code that moves rightOp's
value from a temporary variable into %eax, thereby overwriting
leftOp's value!
So, instead, the pop() method places the %eax register (in this
example) into an internal list of 'almost free' registers;
registers that have just been returned by pop() but shouldn't be
used by the stack machine until a call to done() is made. The
done() method simply moves the registers in the 'almost free' list
over to the 'free' list."""
def __init__(self, parent, base_fp):
# A list of all registers on the machine.
self.all_regs = ['%ebx','%esi','%edi','%eax','%ecx','%edx']
# A list of the registers currently free. Note that this
# is a *copy* of the list of all registers on the machine.
self.regs_free = self.all_regs[:]
# A list of all the registers that are "almost" free
# (see the docstring for this class).
self.regs_almost_free = []
# A list of all the temporary variable memory locations
# that are currently unused.
self.mem_free = []
# A list corresponding to the actual stack of the stack
# machine. The item at the top of the stack is the
# last element of this list.
self.stack = []
# A list that stores the Type objects of each corresponding
# element on the stack machine's stack. e.g., type_stack[0]
# represents the type of the element at stack[0].
self.type_stack = []
# The location of the next memory location to be used for
# temporary variables, relative to the current function's
# frame pointer.
self.next_temp = base_fp - WORD_SIZE
# The parent CodeGenVisitor object of this stack machine.
self.parent = parent
# A list of the callee-save registers that have been used
# so far by this function. Once processing is finished,
# these registers will be pushed onto the process' stack
# at the beginning of the function and popped off just
# before the function terminates.
self.callee_save_regs_used = []
# A list of the caller-save registers on the machine.
self.caller_save_regs = ['%eax', '%ecx', '%edx']
# A list of the callee-save registers on the machine.
self.callee_save_regs = ['%ebx', '%esi', '%edi']
# A list of the registers on the machine that have
# sub-registers allowing access to their low-order bytes.
self.byte_compat_regs = ['%eax', '%ebx', '%ecx', '%edx']
# The default type of an element that is pushed onto
# the stack machine without a 'type' object passed.
self.default_type = cparse.BaseType('int')
def o(self, str, comment=None):
"""Wrapper for the parent CodeGenVisitor's o() method."""
self.parent.o(str, comment)
def save_caller_saves(self):
"""Saves the caller-save registers, which should be done
before the current function makes a function call, so that
the registers don't get corrupted by the called function.
Normally, this is done by pushing the caller-save registers
onto the stack just before the function call is made and
popping them off afterwards; however, due to the workings of
this particular stack machine it's much easier to just move
the contents of the caller-save registers, if they are
currently being used, into temporary variables."""
for reg in self.caller_save_regs:
if reg not in self.regs_free:
self._copy_reg_to_temp([reg],
"Save caller-save register to temp")
self.regs_free.append(reg)
def save_callee_saves(self):
"""Emits code that pushes the callee-save registers used by
the stack machine onto the process' stack."""
for reg in self.callee_save_regs_used:
self.o(" pushl %s" % reg,
"Save callee-save register")
def load_callee_saves(self):
"""Emits code that pops the callee-save registers used by
the stack machine off the process' stack."""
for reg in reversed(self.callee_save_regs_used):
self.o(" popl %s" % reg,
"Restore callee-save register")
def _copy_reg_to_temp(self, valid_regs, comment_str=None):
"""Copy the least recently used register on the stack into a
temporary variable. The register must be in the valid_regs
list."""
# if no free temp variables exist,
# create a new one.
if len(self.mem_free) == 0:
self.mem_free.append("%d(%%ebp)" % self.next_temp)
self.next_temp -= WORD_SIZE
# get an unused temp var
mem = self.mem_free.pop()
# find the least recently used register on the stack
reg = None
index = 0
for i in self.stack:
if i in valid_regs:
reg = i
break
index += 1
if reg == None:
raise Exception("No free registers inside OR outside of stack!")
# emit code to copy the register to the memory location.
if comment_str == None:
comment_str = "Stack machine: copy register to temp"
self.o(" movl %s, %s" % (reg, mem),
comment_str)
# Modify the element's stack machine position to reflect
# its new location.
self.stack[index] = mem
return reg
def _get_free_reg(self, valid_regs, preferred_reg=None):
"""Returns a free register that is in the valid_regs list. If
no registers are available, the most least-recently used
eligible one is freed (by moving its contents to a temporary
variable) and returned."""
# If we have a register free, return it.
if len(self.regs_free) > 0:
reg = None
if preferred_reg != None and preferred_reg in self.regs_free:
reg = preferred_reg
else:
for r in self.regs_free:
if r in valid_regs:
reg = r
if reg != None:
self.regs_free.remove(reg)
# If this register is a callee-save register that
# we haven't used before, add it to our list
# of used callee-save registers.
if reg in self.callee_save_regs and reg not in self.callee_save_regs_used:
self.callee_save_regs_used.append(reg)
return reg
# copy a register into a temp var and return the register.
return self._copy_reg_to_temp(valid_regs)
def _get_type_valid_regs(self, type):
"""Returns the valid registers that an element of the given
type can occupy. For instance, 8-bit chars should only be
placed in %eax/%ebx/%ecx/%edx because these are the only
registers with low-order byte sub-registers
(%al/%bl/%cl/%dl)."""
type_str = type.get_outer_string()
if type_str == 'char':
return self.byte_compat_regs
elif type_str in ['int', 'pointer']:
return self.all_regs
def push(self, type=None, preferred_reg=None, valid_regs=None):
"""Finds a free eligible register (or frees one if all are
being used) and returns it, pushing the register onto the
stack machine's stack.
This method associates the stack entry with the given Type
object; if none is supplied, then an 'int' type is used
by default.
If preferred_reg is passed, this function will try its
best to return preferred_reg, if it's available."""
if type == None:
type = self.default_type
if valid_regs == None:
valid_regs = self._get_type_valid_regs(type)
reg = self._get_free_reg(valid_regs, preferred_reg)
self.type_stack.append(type)
self.stack.append(reg)
return reg
def _coerce_type(self, curr_reg, from_type, to_type):
"""Attempts to coerce the element in the current register
from the given type to the given type."""
from_str = from_type.get_outer_string()
to_str = to_type.get_outer_string()
comment_str = "Implicit cast: %s -> %s" % (from_str, to_str)
if from_str == to_str:
return curr_reg
if from_str == 'char':
if to_str == 'int':
return curr_reg
elif from_str == 'int':
if to_str == 'char':
self.o(" movzbl %s, %s" % (self.lo(curr_reg),
curr_reg),
comment_str)
return curr_reg
def pop(self, type=None, valid_regs=None):
"""Pops the top element off the stack machine's stack, coerces
it to the given type if necessary, and returns a register in
which the element's value now resides.
If no type is specified, pop() returns the value of the
element as-is."""
prev_type = self.type_stack.pop()
if type != None:
if valid_regs == None:
valid_regs = self._get_type_valid_regs(type)
reg = self._pop(valid_regs)
return self._coerce_type(reg, prev_type, type)
else:
reg = self._pop(self.all_regs)
return reg
def _pop(self, valid_regs):
"""Pops the top element of the stack into a free register
that is also in valid_regs and returns the register name. If
no registers are free, the least recently used one is first
copied into a temporary variable and then used."""
loc = self.stack.pop()
# If the top of the stack is a register, just return the
# name of the register and add the register to our free
# register list.
if loc in valid_regs:
self.regs_almost_free.append(loc)
return loc
# Otherwise, copy the temp variable at the top of the stack
# into a free register, possibly requiring us to spill the
# current contents of the memory register into another temp
# variable.
reg = self._get_free_reg(valid_regs)
self.o(" movl %s, %s" % (loc, reg),
"Stack machine: copy temp to register")
# if our location was a register but not in valid_regs,
# make the register free for use.
if loc in self.all_regs:
self.regs_free.append(loc)
self.regs_almost_free.append(reg)
return reg
def peek(self):
"""Returns the top element of the stack, but doesn't pop
it. Note that this is not guaranteed to be a register; it
could be a memory location!"""
return self.stack[-1]
def is_empty(self):
"""Returns whether the stack machine is empty."""
return len(self.stack) == 0
def done(self):
"""Frees all registers that are marked as being in
intermediate use (i.e., have been pop()'d)."""
self.regs_free.extend(self.regs_almost_free)
self.regs_almost_free = []
def get_max_fp(self):
"""Returns the maximum point in the process' stack, relative
to the current function's frame pointer, that the stack
machine is using for temporary variables."""
return self.next_temp + WORD_SIZE
def lo(self, reg):
"""Returns the low-order byte of the given register. If the
register isn't byte-compatible (i.e., isn't %eax, %ebx, %ecx,
or %edx), then an exception is raised.
Example: stack.lo('%eax') == '%al'."""
if reg[0] == '$':
return reg
if reg not in self.byte_compat_regs:
raise Exception("Register %s is not byte-compatible!" % reg)
return '%' + reg[2] + 'l'
def force_type_change(self, type):
"""Forces a type change of the top element of the stack."""
self.type_stack[-1] = type
# ---------------------------------------------------------------
# CODE GENERATOR
# ---------------------------------------------------------------
class CodeGenVisitor(Visitor):
"""Visitor that generates x86 assembly code for the abstract
syntax tree."""
# The current label number we're on, for generating
# jump labels in the assembly code (e.g., 'LO', 'L1', etc).
__label = 0
# Current label number for generating string literal labels.
__str_literal_label = 0
def __init__(self, path, test=None):
"""Constructor. 'file' is the file object to output the
resulting code to."""
Visitor.__init__(self)
# path of compiled C source
self.path = path
# Current assembly code for string literals.
self.str_literal_str = io.StringIO()
self.str_literal_dict = {}
# A hashtable of binary operators and the assembly
# instructions corresponding to them. Certain instructions
# are just the 'base' instruction and require a suffix
# corresponding to the size of the operands; for instance,
# addition can be accomplished with the 'addl' instruction
# for 32-bit integers and 'addb' for 8-bit integers.
#
# In such cases, the code adds the appropriate suffixes on its
# own.
self.binop_instructions = \
{ '==' : 'sete',
'!=' : 'setne',
'>=' : 'setge',
'<=' : 'setle',
'>' : 'setg',
'<' : 'setl',
'+' : 'add',
'-' : 'sub',
'*' : 'imul',
'=' : 'mov',
}
# Windows' C linkage prepends a '_' before symbol
# names, whereas Unix doesn't. This is particularly
# critical if the source file is linking to external
# libraries that we're not compiling. Figure out
# which one to use here.
import sys
if sys.platform == 'win32':
self.symbol_prepend = "_"
else:
self.symbol_prepend = ""
def new_label(self):
"""Generate a new jump label and return it."""
label = ".L%d" % self.__label
self.__class__.__label += 1
return label
def o(self, str, comment=None):
"""Output a line of assembly code to the output file,
with an optional annotated comment (if comments are
enabled)."""
if comment != None:
comment = "# %s" % comment
self.curr_str.write("%-35s %s\n" % (str, comment))
else:
if str == "":
return
self.curr_str.write(str + "\n")
def c(self, str, indent_amt=2):
"Output a single-line comment to the output file."
indent = " " * indent_amt
self.o("\n%s# %s\n" % (indent, str))
def _loc(self, node, comment="") :
if node.lineno != self._last_lineno or comment :
self._last_lineno = node.lineno
self.curr_str.write("# %s %s\n" % (node.loc(), comment))
def vNodeList(self, node):
self._loc(node)
self._visitList(node.nodes)
def _empty_stack(self, node):
"""Pops the top value from the stack machine's stack and
discard it. This is used when a statement has a return
value (for instance, the line 'a = b + 1;') and its
return value has been pushed onto the stack but there's
nothing to pop it off."""
# if the statement was also an expression, then its return
# value is still on the stack, so empty it (throw away
# the return value).
if not self.stack.is_empty():
self.stack.pop(node.type)
self.stack.done()
if not self.stack.is_empty():
raise Exception("PANIC! Register stack isn't empty!")
def _accept_and_empty_stack(self, node):
"""Visit the node and then empty the stack machine of the
node's return value, if one exists."""
node.accept(self)
self._empty_stack(node)
def vStatementList(self, node):
for n in node.nodes:
self._loc(n)
self._accept_and_empty_stack(n)
def _generate_global_variable_definitions(self, node):
"""Generate and return a list of global variable
definitions."""
globals_str = io.StringIO()
for symbol in node.symtab.entries.values():
symbol.compile_loc = self.symbol_prepend + symbol.name
if not symbol.type.is_function() and not symbol.extern:
globals_str.write(" .comm %s,%d\n"
% (symbol.compile_loc,
self._calc_var_size(symbol.type)*WEIRD_MULTIPLIER))
return globals_str
def vTranslationUnit(self, node):
"""Outputs the entire assembly source file."""
self._last_lineno = None
self.curr_str = io.StringIO()
self.globals_str = self._generate_global_variable_definitions(node)
# Generate the main code.
self._visitList(node.nodes)
@classmethod
def concat (cls, outfile, chunks) :
outfile.write("# Generated by cct\n"
"# Franck Pommereau (2018)\n"
"# Adapted from Atul Varma's c.py (Spring 2004)\n\n")
#
outfile.write(".text\n\n")
for c in chunks :
outfile.write("# code from file %r\n" % c.path)
outfile.write(c.curr_str.getvalue())
#
outfile.write(".global_vars:\n\n")
for c in chunks :
outfile.write("\n# globals from file %r\n\n" % c.path)
outfile.write(c.globals_str.getvalue())
for c in chunks :
outfile.write("\n# string literals from file %r\n\n" % c.path)
outfile.write(c.str_literal_str.getvalue())
def _calc_var_size(self, type):
"""Calculate and return the size of the given type, in
bytes."""
type_str = type.get_outer_string()
if type_str == "int":
return INT_SIZE
elif type_str == "char":
return CHAR_SIZE
elif type_str == "pointer":
return WORD_SIZE
else:
self.error("Unknown type: %s" % type_str)
def _calc_var_align(self, type):
"""Calculate and return the alignment of the given type,
in bytes."""
return self._calc_var_size(type)
def _calc_function_var_addrs(self, symtab, last_fp_loc):
"""Calculate the addresses of all local variables in the
function and attach them to their respective symbols in
the function's symbol table(s)."""
self._calc_function_arg_addrs(symtab)
return self._calc_local_var_addrs(symtab.children[0], last_fp_loc)
def _calc_function_arg_addrs(self, symtab):
"""Calculate the addresses of all the arguments passed to
the function."""
for symbol in symtab.entries.values():
symbol.compile_loc = "%d(%%ebp)" % (WORD_SIZE*2+(symbol.param_num*WORD_SIZE))
if not symbol.is_used:
self.warning("function argument '%s' is never used." % symbol.name)
def _calc_local_var_addrs(self, symtab, last_fp_loc):
"""Calculate the locations of all the local variables defined
in the function's body and all nested scopes therein.
This model of allocation assumes a 'worst-case' scenario
where all branches and nested scopes of the function are
executed; thus the space required for all the local
variables is allocated on the process' stack at the
beginning of the function.
Note, however, that lexical scopes that cannot exist
at the same time may overlap in memory. For instance,
examine the following 'if' statement:
if (a > 1) {
int i;
} else {
int j;
}
Here 'i' and 'j' will actually occupy the same place in
memory because it is impossible for both of them to
exist in memory at the same time."""
for symbol in symtab.entries.values():
if symbol.extern:
symbol.compile_loc = self.symbol_prepend + symbol.name
continue
last_fp_loc -= self._calc_var_size(symbol.type)
# adjust location for alignment
align = self._calc_var_align(symbol.type)
bytes_overboard = (-last_fp_loc) % align
if bytes_overboard != 0:
last_fp_loc -= (align - bytes_overboard)
symbol.compile_loc = "%d(%%ebp)" % last_fp_loc
if not symbol.is_used:
self.warning("local variable '%s' is never used." % symbol.name)
max_last_fp = last_fp_loc
for kid in symtab.children:
curr_last_fp = self._calc_local_var_addrs(kid, last_fp_loc)
if curr_last_fp < max_last_fp:
max_last_fp = curr_last_fp
# adjust location for alignment, to keep the stack aligned
# on a word-sized boundary.
align = self._calc_var_align(cparse.PointerType())
bytes_overboard = (-max_last_fp) % align
if bytes_overboard != 0:
max_last_fp -= (align - bytes_overboard)
return max_last_fp
def _fill_line(self, str, width=70):
"""Fills a string to the given width with the '-'
character."""
extra = "-" * (width-1-len(str))
return str + " " + extra
def vFunctionDefn(self, node):
"""Output the assembly code for a function."""
self.break_labels = []
self.continue_labels = []
self.curr_func_end_label = self.new_label() + "_function_end"
# Calculate the base size of the stack frame (not including
# space for the stack machine's temporary variables).
stack_frame_size = self._calc_function_var_addrs(node.symtab, 0)
line = self._fill_line("BEGIN FUNCTION: %s()" % node.name)
self.c("%s\n"
"#\n"
"# Function type: %s" %
(line, node.type.get_string()), 0)
self._loc(node, "(enter function)")
if not node.static:
self.o(" .global %s" % node.compile_loc)
self.o("%s:" % node.compile_loc)
self.o(" pushl %ebp", "Save old frame pointer")
self.o(" movl %esp, %ebp", "Set new frame pointer")
# Create a new stack machine for this function.
self.stack = x86Registers(self, stack_frame_size)
# Generate assembly code for the function. Here we
# perform a little hack so that we can generate the
# code for the function into a separate string, and then
# insert it into our code later on.
old_str = self.curr_str
self.curr_str = io.StringIO()
node.body.accept(self)
function_str = self.curr_str
self.curr_str = old_str
# Figure out the final size of the stack frame, taking into
# account the stack machine's temporary variables, and
# insert the code at the beginning of the function.
if self.stack.get_max_fp() != 0:
self.o(" subl $%d, %%esp" % (-self.stack.get_max_fp()),
"Allocate space for local+temp vars")
# Save any callee-save registers that may have been used.
self.stack.save_callee_saves()
# Add the previously-generated assembly code for the function.
self.curr_str.write(function_str.getvalue())
self._loc(node, "(exit function)")
self.o("%s:" % self.curr_func_end_label)
# Restore any callee-save registers that may have been used.
self.stack.load_callee_saves()
self.o(" movl %ebp, %esp", "Deallocate stack frame")
self.o(" popl %ebp", "Restore old stack frame")
self.o(" ret\n")
line = self._fill_line("END FUNCTION: %s()" % node.name)
self.c(line, 0)
def vCompoundStatement(self, node):
self._loc(node)
node.statement_list.accept(self)
def vIfStatement(self, node):
self._loc(node)
done_label = self.new_label() + "_done"
if not node.else_stmt.is_null():
else_label = self.new_label() + "_else"
else:
else_label = done_label
self.c("IF statment - begin")
node.expr.accept(self)
comparer = self.stack.pop()
self.stack.done()
self.o(" testl %s, %s" % (comparer, comparer), "Test the result")
self.o(" jz %s" % else_label,
"If result is zero, jump to else clause")
self.c("IF statment - THEN clause - begin")
self._accept_and_empty_stack(node.then_stmt)
self.c("IF statment - THEN clause - end")
self.o(" jmp %s" % done_label)
if not node.else_stmt.is_null():
self.c("IF statment - ELSE clause - begin")
self.o("%s:" % else_label)
self._accept_and_empty_stack(node.else_stmt)
self.c("IF statment - ELSE clause - end")
self.o("%s:" % done_label)
self.c("IF statment - end")
def _push_loop_labels(self, break_label, continue_label):
"""Pushes new values of labels to jump to for 'break' and
'continue' statements."""
self.break_labels.append(break_label)
self.continue_labels.append(continue_label)
def _pop_loop_labels(self):
"""Restores old values of labels to jump to for 'break' and
'continue' statements."""
self.break_labels.pop()
self.continue_labels.pop()
def vWhileLoop(self, node):
self._loc(node)
test_label = self.new_label() + "_test"
done_label = self.new_label() + "_done"
self._push_loop_labels(break_label=done_label,
continue_label=test_label)
self.c("WHILE loop - begin")
self.o("%s:" % test_label)
node.expr.accept(self)
comparer = self.stack.pop()
self.stack.done()
self.o(" testl %s, %s" % (comparer, comparer), "Test the result")
self.o(" jz %s" % done_label,
"If result is zero, leave while loop")
self._accept_and_empty_stack(node.stmt)
self.o(" jmp %s" % test_label, "Jump to start of while loop")
self.o("%s:" % done_label)
self.c("WHILE loop - end")
self._pop_loop_labels()
def vForLoop(self, node):
self._loc(node)
test_label = self.new_label() + "_test"
done_label = self.new_label() + "_done"
self._push_loop_labels(break_label=done_label,
continue_label=test_label)
self.c("FOR loop - begin")
self._accept_and_empty_stack(node.begin_stmt)
self.o("%s:" % test_label)
node.expr.accept(self)
comparer = self.stack.pop()
self.stack.done()
self.o(" testl %s, %s" % (comparer, comparer), "Test the result")
self.o(" jz %s" % done_label,
"If result is zero, leave for loop")
self._accept_and_empty_stack(node.stmt)
self._accept_and_empty_stack(node.end_stmt)
self.o(" jmp %s" % test_label, "Jump to start of for loop")
self.o("%s:" % done_label)
self.c("FOR loop - end")
self._pop_loop_labels()
def vBreakStatement(self, node):
self._loc(node)
self.o(" jmp %s" % self.break_labels[-1],
"Loop: break statement")
def vContinueStatement(self, node):
self._loc(node)
self.o(" jmp %s" % self.continue_labels[-1],
"Loop: continue statement")
def _get_new_str_literal_label(self, str):
"""Create a new string literal label for the given string,
generate (but do not yet emit) the assembly for it, and return
the name of the new label."""
if str in self.str_literal_dict :
return self.str_literal_dict[str]
label_str = "LC%d" % self.__str_literal_label
self.str_literal_dict[str] = label_str
str = str.replace('\n', '\\12')
self.str_literal_str.write("""%s:\n .ascii "%s\\0"\n""" % (label_str, str))
self.__class__.__str_literal_label += 1
return label_str
def vStringLiteral(self, node):
self._loc(node)
label_str = self._get_new_str_literal_label(node.get_str())
# Make a little preview of the literal in the annotated
# comments.
COMMENT_CHARS = 7
comment_label = node.get_sanitized_str()
if len(comment_label) > COMMENT_CHARS:
comment_label = "%s..." % comment_label[0:COMMENT_CHARS]
self.o(" movl $%s, %s" % (label_str,
self.stack.push(node.type)),
"Get addr of string literal '%s'" % comment_label)
def vConst(self, node):
self._loc(node)
self.o(" movl $%d, %s" % (node.value,
self.stack.push(node.type)),
"Load numeric constant %d" % node.value)
def vId(self, node):
self._loc(node)
# If we're only supposed to push our address on the stack, not
# our actual value, then do that and exit.
if node.output_addr:
self.o(" leal %s, %s" % (node.symbol.compile_loc,
self.stack.push()),
"Get address of %s" % node.symbol.name)
return
type_str = node.type.get_outer_string()
if type_str in ['pointer', 'int']:
instr = 'movl'
elif type_str == 'char':
instr = 'movzbl'
self.o(" %s %s, %s" % (instr, node.symbol.compile_loc,
self.stack.push(node.type)),
"Get value of %s" % node.symbol.name)
def vArrayExpression(self, node):
self._loc(node)
node.expr.accept(self)
node.index.accept(self)
reg_index = self.stack.pop(node.index.type)
reg_expr = self.stack.pop(node.expr.type)
reg_to = self.stack.push(node.type)
size = self._calc_var_size(node.type)
addr_str = "(%s,%s,%d)" % (reg_expr, reg_index, size)
self.stack.done()
if node.output_addr:
self.o(" leal %s, %s" % (addr_str, reg_to),
"Load addr of pointer array index")
else:
type_str = node.type.get_outer_string()
if type_str in ['int', 'pointer']:
instr = 'movl'
elif type_str == 'char':
instr = 'movzbl'
self.o(" %s %s, %s" % (instr, addr_str, reg_to),
"Pointer array index dereference")
def vFunctionExpression(self, node):
"""Generates assembly for calling a function."""
self._loc(node)
self.c("FUNCTION CALL to %s() - begin" %
node.function.symbol.name)
# If we're using any caller-save registers, free them up.
self.stack.save_caller_saves()
# We need to temporarily reverse the order of the function's
# arguments because we need to push them onto the stack
# in reverse order.
node.arglist.nodes.reverse()
argnum = len(node.arglist.nodes)
for arg in node.arglist.nodes:
arg_reg = self._accept_and_pop(arg)
self.o(" pushl %s" % arg_reg, "Push arg %d" % argnum)
self.stack.done()
argnum -= 1
node.arglist.nodes.reverse()
self.o(" call %s" % node.function.symbol.compile_loc,
"Call %s()" % node.function.symbol.name)
# The function will place its return value in register %eax.
# So, we'll push a register from the stack and ask it to
# give us %eax.
result = self.stack.push(node.function.symbol.type.get_return_type(), preferred_reg='%eax')
# If we got %eax, don't do anything, because our return
# value is already in there. Otherwise, move it.
#
# (Note that in the current implementation of the stack
# machine, we should always get %eax.)
if result != '%eax':
self.o(" movl %%eax, %s" % result, "Copy return value")
arg_stack_size = (len(node.arglist.nodes)*WORD_SIZE)
if arg_stack_size > 0:
self.o(" addl $%d, %%esp" % arg_stack_size,
"Deallocate argument stack")
self.c("FUNCTION CALL to %s() - end" %
node.function.symbol.name)
def vReturnStatement(self, node):
self._loc(node)
return_reg = self._accept_and_pop(node.expr)
self.o(" movl %s, %%eax" % return_reg, "Set return value")
self.o(" jmp %s" % self.curr_func_end_label, "Exit function")
self.stack.done()
def _accept_and_pop(self, node):
"""Accept the given node and pop its value into a register and
return the register. Implicit type conversion is performed,
if necessary, by the stack machine.
Also, if the node is determined to be a numeric constant,
the literal value of the constant (e.g., '$15') is returned,
for purposes of optimization."""
if node.is_const():
return "$%d" % node.value
else:
node.accept(self)
return self.stack.pop(node.coerce_to_type)
def _binop_assign(self, node):
"""Performs an assignment operation (=, +=, etc) on the given
Binop node."""
node.left.accept(self)
right_reg = self._accept_and_pop(node.right)
left_reg = self.stack.pop()
instr = self.binop_instructions[node.op[0]]
instr += self._type_suffix(node.type)
type_str = node.type.get_outer_string()
if type_str == 'char':
right_reg = self.stack.lo(right_reg)
self.o(" %s %s, (%s)" % (instr, right_reg, left_reg),
"Perform assignment '%s'" % node.op)
# NOTE: Wow, this makes for insanely inefficient code, especially
# when the result of the operation isn't being used.
if type_str in ['int', 'pointer']:
instr = 'movl'
elif type_str == 'char':
instr = 'movzbl'
self.o(" %s (%s), %s" % (instr, left_reg,
self.stack.push(node.type)),
"Copy assignment result to register")
self.stack.done()
def _type_suffix(self, type):
"""Returns the assembly instruction suffix for the given type;
'l' for 32-bit types, 'b' for 8-bit types, etc..."""
type_str = type.get_outer_string()
if type_str in ['int', 'pointer']:
return 'l'
elif type_str == 'char':
return 'b'
def _binop_arith(self, node):
"""Performs an arithmetic operation (+, -, etc) on the given
Binop node."""
node.left.accept(self)
right_reg = self._accept_and_pop(node.right)
left_reg = self.stack.pop(node.left.coerce_to_type)
instr = self.binop_instructions[node.op] + \
self._type_suffix(node.type)
type_str = node.type.get_outer_string()
if type_str == 'char':
r_reg = self.stack.lo(right_reg)
l_reg = self.stack.lo(left_reg)
else:
r_reg = right_reg
l_reg = left_reg
self.o(" %s %s, %s" % (instr, r_reg, l_reg),
"Perform '%s'" % node.op)
self.stack.done()
# Here we are relying on the fact that left_reg is now free
# from the last pop(), so we should be able to push it
# back onto the stack machine.
new_reg = self.stack.push(node.type, preferred_reg=left_reg)
if new_reg != left_reg:
raise Exception("PANIC! Binop push() isn't same as last pop()!")
def _binop_divmod(self, node):
"""Performs a division/modulo operation on the given Binop node."""
if node.op == "/" :
result_reg = self.stack.push(node.type, preferred_reg="%eax")
else :
result_reg = self.stack.push(node.type, preferred_reg="%edx")
node.left.accept(self)
right_reg = self._accept_and_pop(node.right)
left_reg = self.stack.pop(node.left.coerce_to_type)
type_str = node.type.get_outer_string()
if type_str == 'char':
divisor_reg = self.stack.lo(right_reg)
dividend_reg = self.stack.lo("%eax")
remainder_reg = self.stack.lo("%edx")
self.o(" mov $0, %s" % result_reg, "Reset result reg")
result_reg = self.stack.lo(result_reg)
else:
divisor_reg = right_reg
dividend_reg = "%eax"
remainder_reg = "%edx"
if result_reg != "%eax" :
self.o(" pushl %eax", "Save %eax used as dividend")
if result_reg != "%edx" :
self.o(" pushl %edx", "Save %edx used as remainder")
if left_reg != dividend_reg :
self.o(" mov %s, %s" % (left_reg, dividend_reg), "Copy dividend to %eax")
self.o(" mov $0, %edx", "Reset remainder reg %edx")
self.o(" div %s" % divisor_reg, "Perform '%s'" % node.op)
if node.op == "/" and result_reg != dividend_reg :
self.o(" mov %s, %s" % (dividend_reg, result_reg), "Copy result")
elif node.op == "%" and result_reg != remainder_reg :
self.o(" mov %s, %s" % (remainder_reg, result_reg), "Copy result")
if result_reg != "%edx" :
self.o(" popl %edx", "Restore %edx")
if result_reg != "%eax" :
self.o(" popl %eax", "Restore %eax")
self.stack.done()
def _binop_compare(self, node):
"""Performs a comparison operation (>, ==, etc) on the given
Binop node."""
node.left.accept(self)
right_reg = self._accept_and_pop(node.right)
left_reg = self.stack.pop(node.left.coerce_to_type)
self.stack.done()
self.o(" cmpl %s, %s" % (right_reg, left_reg),
"Compare %s to %s" % (left_reg, right_reg))
# TODO: this could cause errors, if push() generates
# mov instructions... not sure if mov instructions
# change the flags though, they probably shouldn't
# since they're not arithmetic operations.
byte_reg = self.stack.push(cparse.BaseType('char'))
lo = self.stack.lo(byte_reg)
self.o(" %s %s" % (self.binop_instructions[node.op],
lo),
"Perform '%s'" % node.op)
self.o(" movzbl %s, %s" % (lo, byte_reg),
"Zero-extend the boolean result")
def vBinop(self, node):
self._loc(node)
if node.op in cparse.Binop.ASSIGN_OPS:
self._binop_assign(node)
elif node.op in ['+','-','*']:
self._binop_arith(node)
elif node.op in ['/','%']:
self._binop_divmod(node)
elif node.op in ['==', '!=', '<', '>', '<=', '>=']:
self._binop_compare(node)
else :
raise Exception("unsupported operator %r" % node.op)
def vNegative(self, node):
self._loc(node)
node.expr.accept(self)
self.o(" negl %s" % self.stack.peek(),
"Perform unary negation")
def vPointer(self, node):
self._loc(node)
node.expr.accept(self)
if node.output_addr:
self.o("", "(Getting pointer target addr via '*')")
return
reg_from = self.stack.pop(node.expr.type)
reg_to = self.stack.push(node.type)
type_str = node.type.get_outer_string()
if type_str in ['int', 'pointer']:
instr = 'movl'
elif type_str == 'char':
instr = 'movzbl'
self.o(" %s (%s), %s" % (instr, reg_from, reg_to),
"Pointer dereference")
self.stack.done()
def vAddrOf(self, node):
self._loc(node)
node.expr.accept(self)
self.stack.force_type_change(node.type)
self.o("", "(Address-of operator '&' used here)")
# ---------------------------------------------------------------
# End of cx86.py
# ---------------------------------------------------------------
def compile (path) :
tgt = os.path.splitext(path)[0]
return tgt, ["gcc", "-m32", "-o", tgt, path]
def cpp (args) :
if args.test :
return ["-DCC"]
else :
return []
import argparse, sys, os, os.path, subprocess
import ply.yacc as yacc
from . import cparse, cvisitors, cx86, cttc, cpp
ARCH = {"x86" : cx86,
"ttc" : cttc}
ARCHDOC = """supported target architectures:
x86 Intel 80x86 assembly (in GNU Assemble format)
ttc The Tiny Computer assembly
"""
from . import cparse, cvisitors, cttc, cpp
class CompileError (Exception) :
"Exception raised when there's been a compilation error."
......@@ -19,8 +11,7 @@ class Compiler (object) :
"""This object encapsulates the front-end for the compiler and
serves as a facade interface to the 'meat' of the compiler
underneath."""
def __init__ (self, arch, path, lmap, test) :
self.arch = arch
def __init__ (self, path, lmap, test) :
self.path = path
self.lmap = lmap
self.test = test
......@@ -45,7 +36,7 @@ class Compiler (object) :
self._compile_phase(cvisitors.SymtabVisitor())
self._compile_phase(cvisitors.TypeCheckVisitor())
self._compile_phase(cvisitors.FlowControlVisitor())
comp = self.arch.CodeGenVisitor(self.path, self.test)
comp = cttc.CodeGenVisitor(self.path, self.test)
self._compile_phase(comp)
if ast_file is not None:
self._compile_phase(cvisitors.ASTPrinterVisitor(ast_file))
......@@ -74,7 +65,6 @@ class Compiler (object) :
def main (args=None) :
parser = argparse.ArgumentParser(prog="cct",
epilog=ARCHDOC,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-o", action="store", metavar="PATH",
type=argparse.FileType('w'), default=sys.stdout,
......@@ -83,13 +73,16 @@ def main (args=None) :
help="dump AST for each C file")
parser.add_argument("--cpp", "-p", action="store_true", default=False,
help="process input file through cpp")
parser.add_argument("--arch", action="store", choices=list(ARCH), default="ttc",
help="output assembly for specified architecture"
" (default 'ttc')")
parser.add_argument("--compile", "-c", action="store_true", default=False,
help="compile generated ASM")
parser.add_argument("--test", "-t", action="store_true", default=False,
help="test compiler")
parser.add_argument("--boot", "-b", nargs=1, metavar="FUNC",
help="boot machine by calling FUNC")
parser.add_argument("-L", dest="libpath", metavar="DIR", action="append", default=[],
help="add DIR to the directories to be searched for -l")
parser.add_argument("-l", dest="libs", metavar="LIB", action="append", default=[],
help="include LIB in the generated code")
parser.add_argument("source", nargs="+", metavar="PATH",
help="C source files(s) to compile")
args = parser.parse_args(args)
......@@ -110,24 +103,39 @@ def main (args=None) :
ast_file = None
if args.cpp :
print("Preprocessing %r" % src)
cppargs = ARCH[args.arch].cpp(args)
cppargs = cttc.cpp(args)
print("..$ cpp %s %s" % (" ".join(cppargs), src))
code, lmap = cpp.cpp(src, args.arch, cppargs)
code, lmap = cpp.cpp(src, cppargs)
print("Compiling preprocessed %r" % src)
else :
code = "\n".join(l.rstrip() for l in open(src).readlines())
lmap = {}
print("Compiling %r" % src)
ret = Compiler(ARCH[args.arch], src, lmap, args.test).compile(code, ast_file)
ret = Compiler(src, lmap, args.test).compile(code, ast_file)
if ast_file is not None :
ast_file.close()
if ret is None :
sys.exit(1)
chunks.append(ret)
ARCH[args.arch].CodeGenVisitor.concat(args.o, chunks)
if args.boot :
boot = args.boot[0]
else :
boot = None
cttc.CodeGenVisitor.concat(boot, args.o, chunks)
for lib in args.libs :
for base in ["."] + args.libpath :
path = os.path.join(base, lib + ".asm")
if os.path.exists(path) :
print("Appending %r" % path)
args.o.write("\n#\n# lib %r\n#\n" % path)
args.o.write(open(path).read())
break
else :
print("Library %r not found" % lib)
sys.exit(1)
args.o.flush()
if args.compile :
tgt, cmd = ARCH[args.arch].compile(args.o.name)
tgt, cmd = cttc.compile(args.o.name)
print("Building %r" % tgt)
print(".. $ %s" % " ".join(cmd))
ret = subprocess.run(cmd)
......
all:
python3 ../cct.py --arch=ttc -p -o stdio-c.asm stdio.c
cat stdio_putc.asm > stdio.asm
tail -n +14 stdio-c.asm >> stdio.asm
python3 ../cct.py -p -l stdio_putc -o stdio.asm stdio.c
......
# Generated by cct
# Franck Pommereau (2018)
# Adapted from Atul Varma's c.py (Spring 2004)
#
# on computer start: call main and halt
#
IRQ0:
set R9 @main
call R9
halt
#
# code from file 'stdio.c'
#
# BEGIN FUNCTION: puts() -----------------------------------------------
#
# Function type: function(pointer(char))->int
# stdio.c:32 (enter function)
puts:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
set R9 2 # Allocate 2 words for local+temp vars
sub SP R9 SP # ... shift SP
push R7 # Save callee-save register
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:33
# stdio.c:35
set R9 -2 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R7 # ... save value
# stdio.c:36
set R9 -1 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 0 # Use constant 0
mov R8 R7 # Assignement '=': set result
st R7 R6 # ... save value
# stdio.c:37
# WHILE loop - begin
_L1_test:
set R7 1 # Load numeric constant 1
set R9 @_L2_done # Point towards loop exit
jz R7 R9 # ... if result is zero, jump to it
# stdio.c:38
# IF statment - begin
ldi R7 3 # Get value of s
ldi R6 -1 # Get value of i
add R7 R6 R5 # Load addr of array index
ld R5 R5 # Load array value
set R9 @_L4_else # Point towards else clause
jz R5 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:39
set R9 -2 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R7 3 # Get value of s
ldi R6 -1 # Get value of i
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# stdio.c:40
set R9 -1 # Get BP-relative address of i
add R9 BP R4 # Compute address of i
set R8 1 # Use constant 1
ld R4 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R4 # ... save value
# IF statment - THEN clause - end
set R9 @_L3_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L4_else:
# stdio.c:41
# <string>:0
set R9 @_L2_done # Loop: break statement
jmp R9 # ... jump to loop exit
# IF statment - ELSE clause - end
_L3_done:
# IF statment - end
set R9 @_L1_test # Point towards loop start
jmp R9 # ... jump to it
_L2_done:
# WHILE loop - end
# stdio.c:45
ldi R5 -2 # Get value of n
mov R5 R0 # Set return value
set R9 @_L0_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:32 (exit function)
_L0_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
pop R7 # Restore callee-save register
mov BP SP # Deallocate local+temp vars
pop BP # Restore old stack frame
ret
# END FUNCTION: puts() -------------------------------------------------
# BEGIN FUNCTION: putu() -----------------------------------------------
#
# Function type: function(int,char)->int
# stdio.c:55 (enter function)
putu:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
set R9 6 # Allocate 6 words for local+temp vars
sub SP R9 SP # ... shift SP
push R7 # Save callee-save register
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:56
# stdio.c:62
set R9 -4 # Get BP-relative address of DIGITS
add R9 BP R7 # Compute address of DIGITS
set R6 @_LC0 # Get addr of string literal '0123456...'
mov R6 R5 # Assignement '=': set result
st R5 R7 # ... save value
# stdio.c:63
set R9 -1 # Get BP-relative address of str
add R9 BP R5 # Compute address of str
set R7 @_LC1 # Get addr of string literal '65536'
mov R7 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:64
set R9 -3 # Get BP-relative address of n
add R9 BP R6 # Compute address of n
set R8 0 # Use constant 0
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:65
set R9 -2 # Get BP-relative address of p
add R9 BP R5 # Compute address of p
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:66
# IF statment - begin
ldi R6 4 # Get value of f
set R8 78 # Use constant 120
eq R6 R8 R6 # Perform '=='
set R9 @_L7_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:67
set R9 -5 # Get BP-relative address of div
add R9 BP R6 # Compute address of div
set R8 10 # Use constant 16
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# IF statment - THEN clause - end
set R9 @_L6_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L7_else:
# stdio.c:69
set R9 -5 # Get BP-relative address of div
add R9 BP R5 # Compute address of div
set R8 A # Use constant 10
mov R8 R6 # Assignement '=': set result
st R6 R5 # ... save value
# IF statment - ELSE clause - end
_L6_done:
# IF statment - end
# stdio.c:71
# WHILE loop - begin
_L8_test:
ldi R6 3 # Get value of u
set R9 @_L9_done # Point towards loop exit
jz R6 R9 # ... if result is zero, jump to it
# stdio.c:72
set R9 -6 # Get BP-relative address of r
add R9 BP R6 # Compute address of r
ldi R5 3 # Get value of u
ldi R7 -5 # Get value of div
mod R5 R7 R5 # Perform '%'
mov R5 R7 # Assignement '=': set result
st R7 R6 # ... save value
# stdio.c:73
ldi R7 -1 # Get value of str
ldi R6 -2 # Get value of p
add R7 R6 R5 # Load addr of array index
ldi R7 -4 # Get value of DIGITS
ldi R6 -6 # Get value of r
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
mov R4 R7 # Assignement '=': set result
st R7 R5 # ... save value
# stdio.c:74
set R9 -2 # Get BP-relative address of p
add R9 BP R7 # Compute address of p
set R8 1 # Use constant 1
ld R7 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R7 # ... save value
# stdio.c:75
set R9 3 # Get BP-relative address of u
add R9 BP R5 # Compute address of u
ldi R7 3 # Get value of u
ldi R4 -5 # Get value of div
div R7 R4 R7 # Perform '/'
mov R7 R4 # Assignement '=': set result
st R4 R5 # ... save value
set R9 @_L8_test # Point towards loop start
jmp R9 # ... jump to it
_L9_done:
# WHILE loop - end
# stdio.c:77
set R9 -2 # Get BP-relative address of p
add R9 BP R4 # Compute address of p
set R8 1 # Use constant 1
ld R4 R5 # Assignement '-=': load initial left value
sub R5 R8 R5 # ... subtract right value
st R5 R4 # ... save value
# stdio.c:78
# WHILE loop - begin
_L10_test:
ldi R5 -2 # Get value of p
set R8 0 # Use constant 0
inc R5 # Perform 'a >= b'
gt R5 R8 R5 # ... that is 'a+1 > b'
set R9 @_L11_done # Point towards loop exit
jz R5 R9 # ... if result is zero, jump to it
# stdio.c:79
set R9 -3 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R4 -1 # Get value of str
ldi R7 -2 # Get value of p
add R4 R7 R6 # Load addr of array index
ld R6 R6 # Load array value
push R6 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R5 R6 # Assignement '+=': load initial left value
add R6 R0 R6 # ... add right value
st R6 R5 # ... save value
# stdio.c:80
set R9 -2 # Get BP-relative address of p
add R9 BP R6 # Compute address of p
set R8 1 # Use constant 1
ld R6 R5 # Assignement '-=': load initial left value
sub R5 R8 R5 # ... subtract right value
st R5 R6 # ... save value
set R9 @_L10_test # Point towards loop start
jmp R9 # ... jump to it
_L11_done:
# WHILE loop - end
# stdio.c:82
ldi R5 -3 # Get value of n
mov R5 R0 # Set return value
set R9 @_L5_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:55 (exit function)
_L5_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
pop R7 # Restore callee-save register
mov BP SP # Deallocate local+temp vars
pop BP # Restore old stack frame
ret
# END FUNCTION: putu() -------------------------------------------------
# BEGIN FUNCTION: puti() -----------------------------------------------
#
# Function type: function(int)->int
# stdio.c:85 (enter function)
puti:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
set R9 1 # Allocate 1 words for local+temp vars
sub SP R9 SP # ... shift SP
push R7 # Save callee-save register
push R6 # Save callee-save register
# stdio.c:86
# stdio.c:87
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R7 # ... save value
# stdio.c:88
# IF statment - begin
ldi R6 3 # Get value of i
set R8 7FFF # Use constant 32767
gt R6 R8 R6 # Perform '>'
set R9 @_L14_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:89
set R9 -1 # Get BP-relative address of n
add R9 BP R6 # Compute address of n
# FUNCTION CALL to putc() - begin
set R8 2D # Use constant 45
push R8 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R6 R7 # Assignement '+=': load initial left value
add R7 R0 R7 # ... add right value
st R7 R6 # ... save value
# stdio.c:90
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
# FUNCTION CALL to putu() - begin
set R8 75 # Use constant 117
push R8 # Push arg 2
ldi R6 3 # Get value of i
neg R6 R6 # Perform unary negation
push R6 # Push arg 1
set R9 @putu # Point towards function putu()
call R9 # ... call it
set R9 2 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putu() - end
ld R7 R6 # Assignement '+=': load initial left value
add R6 R0 R6 # ... add right value
st R6 R7 # ... save value
# stdio.c:91
ldi R6 -1 # Get value of n
mov R6 R0 # Set return value
set R9 @_L12_function_end # Point towards function exit
jmp R9 # ... jump to it
# IF statment - THEN clause - end
set R9 @_L13_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L14_else:
# stdio.c:93
# FUNCTION CALL to putu() - begin
set R8 75 # Use constant 117
push R8 # Push arg 2
ldi R6 3 # Get value of i
push R6 # Push arg 1
set R9 @putu # Point towards function putu()
call R9 # ... call it
set R9 2 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putu() - end
mov R0 R0 # Set return value
set R9 @_L12_function_end # Point towards function exit
jmp R9 # ... jump to it
# IF statment - ELSE clause - end
_L13_done:
# IF statment - end
# stdio.c:85 (exit function)
_L12_function_end:
pop R6 # Restore callee-save register
pop R7 # Restore callee-save register
mov BP SP # Deallocate local+temp vars
pop BP # Restore old stack frame
ret
# END FUNCTION: puti() -------------------------------------------------
# BEGIN FUNCTION: printf() ---------------------------------------------
#
# Function type: function(pointer(char))->int
# stdio.c:97 (enter function)
printf:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
set R9 9 # Allocate 9 words for local+temp vars
sub SP R9 SP # ... shift SP
push R7 # Save callee-save register
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:98
# stdio.c:103
set R9 -1 # Get BP-relative address of iargs
add R9 BP R7 # Compute address of iargs
set R9 3 # Get BP-relative address of str
add R9 BP R6 # Compute address of str
# (Address-of operator '&' used here)
mov R6 R5 # Assignement '=': set result
st R5 R7 # ... save value
# stdio.c:104
set R9 -3 # Get BP-relative address of cargs
add R9 BP R5 # Compute address of cargs
set R9 3 # Get BP-relative address of str
add R9 BP R7 # Compute address of str
# (Address-of operator '&' used here)
mov R7 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:105
set R9 -5 # Get BP-relative address of a
add R9 BP R6 # Compute address of a
set R8 1 # Use constant 1
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:106
set R9 -4 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:107
set R9 -2 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 0 # Use constant 0
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:108
# WHILE loop - begin
_L16_test:
set R5 1 # Load numeric constant 1
set R9 @_L17_done # Point towards loop exit
jz R5 R9 # ... if result is zero, jump to it
# stdio.c:109
# IF statment - begin
ldi R5 3 # Get value of str
ldi R6 -2 # Get value of i
add R5 R6 R7 # Load addr of array index
ld R7 R7 # Load array value
set R8 0 # Use constant 0
eq R7 R8 R7 # Perform '=='
set R9 @_L19_else # Point towards else clause
jz R7 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# <string>:0
set R9 @_L17_done # Loop: break statement
jmp R9 # ... jump to loop exit
# IF statment - THEN clause - end
set R9 @_L18_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L19_else:
# stdio.c:111
# IF statment - begin
ldi R7 3 # Get value of str
ldi R5 -2 # Get value of i
add R7 R5 R6 # Load addr of array index
ld R6 R6 # Load array value
set R8 25 # Use constant 37
eq R6 R8 R6 # Perform '=='
set R9 @_L21_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:112
set R9 -2 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 1 # Use constant 1
ld R6 R7 # Assignement '+=': load initial left value
add R7 R8 R7 # ... add right value
st R7 R6 # ... save value
# stdio.c:113
# IF statment - begin
ldi R7 3 # Get value of str
ldi R6 -2 # Get value of i
add R7 R6 R5 # Load addr of array index
ld R5 R5 # Load array value
set R8 69 # Use constant 105
eq R5 R8 R5 # Perform '=='
set R9 @_L23_else # Point towards else clause
jz R5 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:114
set R9 -4 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to puti() - begin
ldi R7 -1 # Get value of iargs
ldi R6 -5 # Get value of a
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
set R9 @puti # Point towards function puti()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to puti() - end
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# IF statment - THEN clause - end
set R9 @_L22_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L23_else:
# stdio.c:115
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 75 # Use constant 117
eq R0 R8 R0 # Perform '=='
set R9 @_L25_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:116
set R9 -4 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putu() - begin
sti R0 -6 # Save caller-save register to temp
set R8 75 # Use constant 117
push R8 # Push arg 2
ldi R0 -1 # Get value of iargs
ldi R4 -5 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
set R9 @putu # Point towards function putu()
call R9 # ... call it
set R9 2 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putu() - end
ldi R5 -6 # Stack machine: copy temp to register
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# IF statment - THEN clause - end
set R9 @_L24_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L25_else:
# stdio.c:117
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 73 # Use constant 115
eq R0 R8 R0 # Perform '=='
set R9 @_L27_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:118
set R9 -4 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to puts() - begin
sti R0 -7 # Save caller-save register to temp
ldi R0 -3 # Get value of cargs
ldi R4 -5 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
set R9 @puts # Point towards function puts()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to puts() - end
ldi R5 -7 # Stack machine: copy temp to register
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# IF statment - THEN clause - end
set R9 @_L26_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L27_else:
# stdio.c:119
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 78 # Use constant 120
eq R0 R8 R0 # Perform '=='
set R9 @_L29_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:120
set R9 -4 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putu() - begin
sti R0 -8 # Save caller-save register to temp
set R8 78 # Use constant 120
push R8 # Push arg 2
ldi R0 -1 # Get value of iargs
ldi R4 -5 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
set R9 @putu # Point towards function putu()
call R9 # ... call it
set R9 2 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putu() - end
ldi R5 -8 # Stack machine: copy temp to register
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# IF statment - THEN clause - end
set R9 @_L28_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L29_else:
# stdio.c:121
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 25 # Use constant 37
eq R0 R8 R0 # Perform '=='
set R9 @_L31_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:122
set R9 -4 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putc() - begin
sti R0 -9 # Save caller-save register to temp
set R8 25 # Use constant 37
push R8 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ldi R4 -9 # Stack machine: copy temp to register
ld R4 R5 # Assignement '+=': load initial left value
add R5 R0 R5 # ... add right value
st R5 R4 # ... save value
# stdio.c:123
set R9 -2 # Get BP-relative address of i
add R9 BP R5 # Compute address of i
set R8 1 # Use constant 1
ld R5 R4 # Assignement '+=': load initial left value
add R4 R8 R4 # ... add right value
st R4 R5 # ... save value
# <string>:0
set R9 @_L16_test # Loop: continue statement
jmp R9 # ... jump to loop start
# IF statment - THEN clause - end
set R9 @_L30_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L31_else:
# stdio.c:126
set R9 -4 # Get BP-relative address of n
add R9 BP R4 # Compute address of n
# FUNCTION CALL to putc() - begin
set R8 25 # Use constant 37
push R8 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R4 R5 # Assignement '+=': load initial left value
add R5 R0 R5 # ... add right value
st R5 R4 # ... save value
# stdio.c:127
set R9 -4 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R4 3 # Get value of str
ldi R0 -2 # Get value of i
add R4 R0 R7 # Load addr of array index
ld R7 R7 # Load array value
push R7 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R5 R7 # Assignement '+=': load initial left value
add R7 R0 R7 # ... add right value
st R7 R5 # ... save value
# IF statment - ELSE clause - end
_L30_done:
# IF statment - end
# IF statment - ELSE clause - end
_L28_done:
# IF statment - end
# IF statment - ELSE clause - end
_L26_done:
# IF statment - end
# IF statment - ELSE clause - end
_L24_done:
# IF statment - end
# IF statment - ELSE clause - end
_L22_done:
# IF statment - end
# stdio.c:129
set R9 -5 # Get BP-relative address of a
add R9 BP R7 # Compute address of a
set R8 1 # Use constant 1
ld R7 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R7 # ... save value
# IF statment - THEN clause - end
set R9 @_L20_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L21_else:
# stdio.c:131
set R9 -4 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R7 3 # Get value of str
ldi R0 -2 # Get value of i
add R7 R0 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
set R9 @putc # Point towards function putc()
call R9 # ... call it
set R9 1 # Deallocate argument stack
add R9 SP SP # ... shift SP
# FUNCTION CALL to putc() - end
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# IF statment - ELSE clause - end
_L20_done:
# IF statment - end
# IF statment - ELSE clause - end
_L18_done:
# IF statment - end
# stdio.c:133
set R9 -2 # Get BP-relative address of i
add R9 BP R4 # Compute address of i
set R8 1 # Use constant 1
ld R4 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R4 # ... save value
set R9 @_L16_test # Point towards loop start
jmp R9 # ... jump to it
_L17_done:
# WHILE loop - end
# stdio.c:135
ldi R5 -4 # Get value of n
mov R5 R0 # Set return value
set R9 @_L15_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:97 (exit function)
_L15_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
pop R7 # Restore callee-save register
mov BP SP # Deallocate local+temp vars
pop BP # Restore old stack frame
ret
# END FUNCTION: printf() -----------------------------------------------
#
# string literals from file 'stdio.c'
#
_LC0:
str "0123456789ABCDEF\0"
_LC1:
str "65536\0"
#include "stdio.h"
#define UCHAR 117
#define XCHAR 120
int main() {
puts("hello world\n");
putu(42, XCHAR);
puts(" => 2A\n");
putu(42, UCHAR);
puts(" => 42\n");
puti(42);
puts(" => 42\n");
puti(-42);
puts(" => -42\n");
printf("hello %s I'm %u (%x)\n", "stdio", 42, 42);
return 0;
}
#
# extern int putc(char c)
#
putc:
set R8 2 # Point R8 towards argument c
add R8 SP R8 # ... located as SP+2
ld R8 R8 # Load argument c
set R9 1012 # Put command for screen
bus R9 R0 R8 # Write char to screen
set R0 1 # Set return value
ret
# Generated by cct
# Franck Pommereau (2018)
# Adapted from Atul Varma's c.py (Spring 2004)
#
# code from file 'stdio.c'
......@@ -19,7 +10,7 @@ putc:
#
# Function type: function(pointer(char))->int
# stdio.c:32 (enter function)
# stdio.c:20 (enter function)
puts:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
......@@ -29,48 +20,48 @@ puts:
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:33
# stdio.c:35
set R9 -2 # Get BP-relative address of n
# stdio.c:21
# stdio.c:23
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R7 # ... save value
# stdio.c:36
set R9 -1 # Get BP-relative address of i
# stdio.c:24
set R9 -2 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 0 # Use constant 0
mov R8 R7 # Assignement '=': set result
st R7 R6 # ... save value
# stdio.c:37
# stdio.c:25
# WHILE loop - begin
_L1_test:
_stdio_L1_test:
set R7 1 # Load numeric constant 1
set R9 @_L2_done # Point towards loop exit
set R9 @_stdio_L2_done # Point towards loop exit
jz R7 R9 # ... if result is zero, jump to it
# stdio.c:38
# stdio.c:26
# IF statment - begin
ldi R7 3 # Get value of s
ldi R6 -1 # Get value of i
ldi R6 -2 # Get value of i
add R7 R6 R5 # Load addr of array index
ld R5 R5 # Load array value
set R9 @_L4_else # Point towards else clause
set R9 @_stdio_L4_else # Point towards else clause
jz R5 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:39
set R9 -2 # Get BP-relative address of n
# stdio.c:27
set R9 -1 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R7 3 # Get value of s
ldi R6 -1 # Get value of i
ldi R6 -2 # Get value of i
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
......@@ -84,8 +75,8 @@ _L1_test:
ld R5 R4 # Assignement '+=': load initial left value
add R4 R0 R4 # ... add right value
st R4 R5 # ... save value
# stdio.c:40
set R9 -1 # Get BP-relative address of i
# stdio.c:28
set R9 -2 # Get BP-relative address of i
add R9 BP R4 # Compute address of i
set R8 1 # Use constant 1
ld R4 R5 # Assignement '+=': load initial left value
......@@ -94,36 +85,36 @@ _L1_test:
# IF statment - THEN clause - end
set R9 @_L3_done # Point towards if end
set R9 @_stdio_L3_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L4_else:
# stdio.c:41
_stdio_L4_else:
# stdio.c:29
# <string>:0
set R9 @_L2_done # Loop: break statement
set R9 @_stdio_L2_done # Loop: break statement
jmp R9 # ... jump to loop exit
# IF statment - ELSE clause - end
_L3_done:
_stdio_L3_done:
# IF statment - end
set R9 @_L1_test # Point towards loop start
set R9 @_stdio_L1_test # Point towards loop start
jmp R9 # ... jump to it
_L2_done:
_stdio_L2_done:
# WHILE loop - end
# stdio.c:45
ldi R5 -2 # Get value of n
# stdio.c:33
ldi R5 -1 # Get value of n
mov R5 R0 # Set return value
set R9 @_L0_function_end # Point towards function exit
set R9 @_stdio_L0_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:32 (exit function)
_L0_function_end:
# stdio.c:20 (exit function)
_stdio_L0_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
......@@ -139,7 +130,7 @@ _L0_function_end:
#
# Function type: function(int,char)->int
# stdio.c:55 (enter function)
# stdio.c:43 (enter function)
putu:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
......@@ -149,45 +140,45 @@ putu:
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:56
# stdio.c:62
set R9 -4 # Get BP-relative address of DIGITS
# stdio.c:44
# stdio.c:50
set R9 -3 # Get BP-relative address of DIGITS
add R9 BP R7 # Compute address of DIGITS
set R6 @_LC0 # Get addr of string literal '0123456...'
set R6 @_stdio_LC0 # Get addr of string literal '0123456...'
mov R6 R5 # Assignement '=': set result
st R5 R7 # ... save value
# stdio.c:63
set R9 -1 # Get BP-relative address of str
# stdio.c:51
set R9 -5 # Get BP-relative address of str
add R9 BP R5 # Compute address of str
set R7 @_LC1 # Get addr of string literal '65536'
set R7 @_stdio_LC1 # Get addr of string literal '65536'
mov R7 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:64
set R9 -3 # Get BP-relative address of n
# stdio.c:52
set R9 -1 # Get BP-relative address of n
add R9 BP R6 # Compute address of n
set R8 0 # Use constant 0
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:65
set R9 -2 # Get BP-relative address of p
# stdio.c:53
set R9 -4 # Get BP-relative address of p
add R9 BP R5 # Compute address of p
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:66
# stdio.c:54
# IF statment - begin
ldi R6 4 # Get value of f
set R8 78 # Use constant 120
eq R6 R8 R6 # Perform '=='
set R9 @_L7_else # Point towards else clause
set R9 @_stdio_L7_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:67
set R9 -5 # Get BP-relative address of div
# stdio.c:55
set R9 -2 # Get BP-relative address of div
add R9 BP R6 # Compute address of div
set R8 10 # Use constant 16
mov R8 R5 # Assignement '=': set result
......@@ -195,14 +186,14 @@ putu:
# IF statment - THEN clause - end
set R9 @_L6_done # Point towards if end
set R9 @_stdio_L6_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L7_else:
# stdio.c:69
set R9 -5 # Get BP-relative address of div
_stdio_L7_else:
# stdio.c:57
set R9 -2 # Get BP-relative address of div
add R9 BP R5 # Compute address of div
set R8 A # Use constant 10
mov R8 R6 # Assignement '=': set result
......@@ -210,83 +201,83 @@ _L7_else:
# IF statment - ELSE clause - end
_L6_done:
_stdio_L6_done:
# IF statment - end
# stdio.c:71
# stdio.c:59
# WHILE loop - begin
_L8_test:
_stdio_L8_test:
ldi R6 3 # Get value of u
set R9 @_L9_done # Point towards loop exit
set R9 @_stdio_L9_done # Point towards loop exit
jz R6 R9 # ... if result is zero, jump to it
# stdio.c:72
# stdio.c:60
set R9 -6 # Get BP-relative address of r
add R9 BP R6 # Compute address of r
ldi R5 3 # Get value of u
ldi R7 -5 # Get value of div
ldi R7 -2 # Get value of div
mod R5 R7 R5 # Perform '%'
mov R5 R7 # Assignement '=': set result
st R7 R6 # ... save value
# stdio.c:73
ldi R7 -1 # Get value of str
ldi R6 -2 # Get value of p
# stdio.c:61
ldi R7 -5 # Get value of str
ldi R6 -4 # Get value of p
add R7 R6 R5 # Load addr of array index
ldi R7 -4 # Get value of DIGITS
ldi R7 -3 # Get value of DIGITS
ldi R6 -6 # Get value of r
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
mov R4 R7 # Assignement '=': set result
st R7 R5 # ... save value
# stdio.c:74
set R9 -2 # Get BP-relative address of p
# stdio.c:62
set R9 -4 # Get BP-relative address of p
add R9 BP R7 # Compute address of p
set R8 1 # Use constant 1
ld R7 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R7 # ... save value
# stdio.c:75
# stdio.c:63
set R9 3 # Get BP-relative address of u
add R9 BP R5 # Compute address of u
ldi R7 3 # Get value of u
ldi R4 -5 # Get value of div
ldi R4 -2 # Get value of div
div R7 R4 R7 # Perform '/'
mov R7 R4 # Assignement '=': set result
st R4 R5 # ... save value
set R9 @_L8_test # Point towards loop start
set R9 @_stdio_L8_test # Point towards loop start
jmp R9 # ... jump to it
_L9_done:
_stdio_L9_done:
# WHILE loop - end
# stdio.c:77
set R9 -2 # Get BP-relative address of p
# stdio.c:65
set R9 -4 # Get BP-relative address of p
add R9 BP R4 # Compute address of p
set R8 1 # Use constant 1
ld R4 R5 # Assignement '-=': load initial left value
sub R5 R8 R5 # ... subtract right value
st R5 R4 # ... save value
# stdio.c:78
# stdio.c:66
# WHILE loop - begin
_L10_test:
ldi R5 -2 # Get value of p
_stdio_L10_test:
ldi R5 -4 # Get value of p
set R8 0 # Use constant 0
inc R5 # Perform 'a >= b'
gt R5 R8 R5 # ... that is 'a+1 > b'
set R9 @_L11_done # Point towards loop exit
set R9 @_stdio_L11_done # Point towards loop exit
jz R5 R9 # ... if result is zero, jump to it
# stdio.c:79
set R9 -3 # Get BP-relative address of n
# stdio.c:67
set R9 -1 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R4 -1 # Get value of str
ldi R7 -2 # Get value of p
ldi R4 -5 # Get value of str
ldi R7 -4 # Get value of p
add R4 R7 R6 # Load addr of array index
ld R6 R6 # Load array value
push R6 # Push arg 1
......@@ -300,26 +291,26 @@ _L10_test:
ld R5 R6 # Assignement '+=': load initial left value
add R6 R0 R6 # ... add right value
st R6 R5 # ... save value
# stdio.c:80
set R9 -2 # Get BP-relative address of p
# stdio.c:68
set R9 -4 # Get BP-relative address of p
add R9 BP R6 # Compute address of p
set R8 1 # Use constant 1
ld R6 R5 # Assignement '-=': load initial left value
sub R5 R8 R5 # ... subtract right value
st R5 R6 # ... save value
set R9 @_L10_test # Point towards loop start
set R9 @_stdio_L10_test # Point towards loop start
jmp R9 # ... jump to it
_L11_done:
_stdio_L11_done:
# WHILE loop - end
# stdio.c:82
ldi R5 -3 # Get value of n
# stdio.c:70
ldi R5 -1 # Get value of n
mov R5 R0 # Set return value
set R9 @_L5_function_end # Point towards function exit
set R9 @_stdio_L5_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:55 (exit function)
_L5_function_end:
# stdio.c:43 (exit function)
_stdio_L5_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
......@@ -335,7 +326,7 @@ _L5_function_end:
#
# Function type: function(int)->int
# stdio.c:85 (enter function)
# stdio.c:73 (enter function)
puti:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
......@@ -343,28 +334,22 @@ puti:
sub SP R9 SP # ... shift SP
push R7 # Save callee-save register
push R6 # Save callee-save register
# stdio.c:86
# stdio.c:87
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R7 # ... save value
# stdio.c:88
# stdio.c:74
# stdio.c:75
# IF statment - begin
ldi R6 3 # Get value of i
ldi R7 3 # Get value of i
set R8 7FFF # Use constant 32767
gt R6 R8 R6 # Perform '>'
set R9 @_L14_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
gt R7 R8 R7 # Perform '>'
set R9 @_stdio_L14_else # Point towards else clause
jz R7 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:89
# stdio.c:76
set R9 -1 # Get BP-relative address of n
add R9 BP R6 # Compute address of n
add R9 BP R7 # Compute address of n
# FUNCTION CALL to putc() - begin
......@@ -377,20 +362,19 @@ puti:
# FUNCTION CALL to putc() - end
ld R6 R7 # Assignement '+=': load initial left value
add R7 R0 R7 # ... add right value
st R7 R6 # ... save value
# stdio.c:90
mov R0 R6 # Assignement '=': set result
st R6 R7 # ... save value
# stdio.c:77
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
add R9 BP R6 # Compute address of n
# FUNCTION CALL to putu() - begin
set R8 75 # Use constant 117
push R8 # Push arg 2
ldi R6 3 # Get value of i
neg R6 R6 # Perform unary negation
push R6 # Push arg 1
ldi R7 3 # Get value of i
neg R7 R7 # Perform unary negation
push R7 # Push arg 1
set R9 @putu # Point towards function putu()
call R9 # ... call it
set R9 2 # Deallocate argument stack
......@@ -398,24 +382,21 @@ puti:
# FUNCTION CALL to putu() - end
ld R7 R6 # Assignement '+=': load initial left value
add R6 R0 R6 # ... add right value
st R6 R7 # ... save value
# stdio.c:91
ldi R6 -1 # Get value of n
mov R6 R0 # Set return value
set R9 @_L12_function_end # Point towards function exit
jmp R9 # ... jump to it
ld R6 R7 # Assignement '+=': load initial left value
add R7 R0 R7 # ... add right value
st R7 R6 # ... save value
# IF statment - THEN clause - end
set R9 @_L13_done # Point towards if end
set R9 @_stdio_L13_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L14_else:
# stdio.c:93
_stdio_L14_else:
# stdio.c:79
set R9 -1 # Get BP-relative address of n
add R9 BP R7 # Compute address of n
# FUNCTION CALL to putu() - begin
......@@ -430,18 +411,22 @@ _L14_else:
# FUNCTION CALL to putu() - end
mov R0 R0 # Set return value
set R9 @_L12_function_end # Point towards function exit
jmp R9 # ... jump to it
mov R0 R6 # Assignement '=': set result
st R6 R7 # ... save value
# IF statment - ELSE clause - end
_L13_done:
_stdio_L13_done:
# IF statment - end
# stdio.c:85 (exit function)
_L12_function_end:
# stdio.c:81
ldi R6 -1 # Get value of n
mov R6 R0 # Set return value
set R9 @_stdio_L12_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:73 (exit function)
_stdio_L12_function_end:
pop R6 # Restore callee-save register
pop R7 # Restore callee-save register
mov BP SP # Deallocate local+temp vars
......@@ -455,7 +440,7 @@ _L12_function_end:
#
# Function type: function(pointer(char))->int
# stdio.c:97 (enter function)
# stdio.c:84 (enter function)
printf:
push BP # Save old frame pointer
mov SP BP # Set new frame pointer
......@@ -465,8 +450,8 @@ printf:
push R6 # Save callee-save register
push R5 # Save callee-save register
push R4 # Save callee-save register
# stdio.c:98
# stdio.c:103
# stdio.c:85
# stdio.c:90
set R9 -1 # Get BP-relative address of iargs
add R9 BP R7 # Compute address of iargs
set R9 3 # Get BP-relative address of str
......@@ -474,112 +459,112 @@ printf:
# (Address-of operator '&' used here)
mov R6 R5 # Assignement '=': set result
st R5 R7 # ... save value
# stdio.c:104
set R9 -3 # Get BP-relative address of cargs
# stdio.c:91
set R9 -5 # Get BP-relative address of cargs
add R9 BP R5 # Compute address of cargs
set R9 3 # Get BP-relative address of str
add R9 BP R7 # Compute address of str
# (Address-of operator '&' used here)
mov R7 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:105
set R9 -5 # Get BP-relative address of a
# stdio.c:92
set R9 -4 # Get BP-relative address of a
add R9 BP R6 # Compute address of a
set R8 1 # Use constant 1
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:106
set R9 -4 # Get BP-relative address of n
# stdio.c:93
set R9 -2 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
set R8 0 # Use constant 0
mov R8 R6 # Assignement '=': set result
st R6 R5 # ... save value
# stdio.c:107
set R9 -2 # Get BP-relative address of i
# stdio.c:94
set R9 -3 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 0 # Use constant 0
mov R8 R5 # Assignement '=': set result
st R5 R6 # ... save value
# stdio.c:108
# stdio.c:95
# WHILE loop - begin
_L16_test:
_stdio_L16_test:
set R5 1 # Load numeric constant 1
set R9 @_L17_done # Point towards loop exit
set R9 @_stdio_L17_done # Point towards loop exit
jz R5 R9 # ... if result is zero, jump to it
# stdio.c:109
# stdio.c:96
# IF statment - begin
ldi R5 3 # Get value of str
ldi R6 -2 # Get value of i
ldi R6 -3 # Get value of i
add R5 R6 R7 # Load addr of array index
ld R7 R7 # Load array value
set R8 0 # Use constant 0
eq R7 R8 R7 # Perform '=='
set R9 @_L19_else # Point towards else clause
set R9 @_stdio_L19_else # Point towards else clause
jz R7 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# <string>:0
set R9 @_L17_done # Loop: break statement
set R9 @_stdio_L17_done # Loop: break statement
jmp R9 # ... jump to loop exit
# IF statment - THEN clause - end
set R9 @_L18_done # Point towards if end
set R9 @_stdio_L18_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L19_else:
# stdio.c:111
_stdio_L19_else:
# stdio.c:98
# IF statment - begin
ldi R7 3 # Get value of str
ldi R5 -2 # Get value of i
ldi R5 -3 # Get value of i
add R7 R5 R6 # Load addr of array index
ld R6 R6 # Load array value
set R8 25 # Use constant 37
eq R6 R8 R6 # Perform '=='
set R9 @_L21_else # Point towards else clause
set R9 @_stdio_L21_else # Point towards else clause
jz R6 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:112
set R9 -2 # Get BP-relative address of i
# stdio.c:99
set R9 -3 # Get BP-relative address of i
add R9 BP R6 # Compute address of i
set R8 1 # Use constant 1
ld R6 R7 # Assignement '+=': load initial left value
add R7 R8 R7 # ... add right value
st R7 R6 # ... save value
# stdio.c:113
# stdio.c:100
# IF statment - begin
ldi R7 3 # Get value of str
ldi R6 -2 # Get value of i
ldi R6 -3 # Get value of i
add R7 R6 R5 # Load addr of array index
ld R5 R5 # Load array value
set R8 69 # Use constant 105
eq R5 R8 R5 # Perform '=='
set R9 @_L23_else # Point towards else clause
set R9 @_stdio_L23_else # Point towards else clause
jz R5 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:114
set R9 -4 # Get BP-relative address of n
# stdio.c:101
set R9 -2 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to puti() - begin
ldi R7 -1 # Get value of iargs
ldi R6 -5 # Get value of a
ldi R6 -4 # Get value of a
add R7 R6 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
......@@ -596,29 +581,29 @@ _L19_else:
# IF statment - THEN clause - end
set R9 @_L22_done # Point towards if end
set R9 @_stdio_L22_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L23_else:
# stdio.c:115
_stdio_L23_else:
# stdio.c:102
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
ldi R5 -3 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 75 # Use constant 117
eq R0 R8 R0 # Perform '=='
set R9 @_L25_else # Point towards else clause
set R9 @_stdio_L25_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:116
set R9 -4 # Get BP-relative address of n
# stdio.c:103
set R9 -2 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putu() - begin
......@@ -627,7 +612,7 @@ _L23_else:
set R8 75 # Use constant 117
push R8 # Push arg 2
ldi R0 -1 # Get value of iargs
ldi R4 -5 # Get value of a
ldi R4 -4 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
......@@ -645,36 +630,36 @@ _L23_else:
# IF statment - THEN clause - end
set R9 @_L24_done # Point towards if end
set R9 @_stdio_L24_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L25_else:
# stdio.c:117
_stdio_L25_else:
# stdio.c:104
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
ldi R5 -3 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 73 # Use constant 115
eq R0 R8 R0 # Perform '=='
set R9 @_L27_else # Point towards else clause
set R9 @_stdio_L27_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:118
set R9 -4 # Get BP-relative address of n
# stdio.c:105
set R9 -2 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to puts() - begin
sti R0 -7 # Save caller-save register to temp
ldi R0 -3 # Get value of cargs
ldi R4 -5 # Get value of a
ldi R0 -5 # Get value of cargs
ldi R4 -4 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
......@@ -692,29 +677,29 @@ _L25_else:
# IF statment - THEN clause - end
set R9 @_L26_done # Point towards if end
set R9 @_stdio_L26_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L27_else:
# stdio.c:119
_stdio_L27_else:
# stdio.c:106
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
ldi R5 -3 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 78 # Use constant 120
eq R0 R8 R0 # Perform '=='
set R9 @_L29_else # Point towards else clause
set R9 @_stdio_L29_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:120
set R9 -4 # Get BP-relative address of n
# stdio.c:107
set R9 -2 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putu() - begin
......@@ -723,7 +708,7 @@ _L27_else:
set R8 78 # Use constant 120
push R8 # Push arg 2
ldi R0 -1 # Get value of iargs
ldi R4 -5 # Get value of a
ldi R4 -4 # Get value of a
add R0 R4 R5 # Load addr of array index
ld R5 R5 # Load array value
push R5 # Push arg 1
......@@ -741,29 +726,29 @@ _L27_else:
# IF statment - THEN clause - end
set R9 @_L28_done # Point towards if end
set R9 @_stdio_L28_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L29_else:
# stdio.c:121
_stdio_L29_else:
# stdio.c:108
# IF statment - begin
ldi R4 3 # Get value of str
ldi R5 -2 # Get value of i
ldi R5 -3 # Get value of i
add R4 R5 R0 # Load addr of array index
ld R0 R0 # Load array value
set R8 25 # Use constant 37
eq R0 R8 R0 # Perform '=='
set R9 @_L31_else # Point towards else clause
set R9 @_stdio_L31_else # Point towards else clause
jz R0 R9 # ... if result is zero, jump to it
# IF statment - THEN clause - begin
# stdio.c:122
set R9 -4 # Get BP-relative address of n
# stdio.c:109
set R9 -2 # Get BP-relative address of n
add R9 BP R0 # Compute address of n
# FUNCTION CALL to putc() - begin
......@@ -782,27 +767,27 @@ _L29_else:
ld R4 R5 # Assignement '+=': load initial left value
add R5 R0 R5 # ... add right value
st R5 R4 # ... save value
# stdio.c:123
set R9 -2 # Get BP-relative address of i
# stdio.c:110
set R9 -3 # Get BP-relative address of i
add R9 BP R5 # Compute address of i
set R8 1 # Use constant 1
ld R5 R4 # Assignement '+=': load initial left value
add R4 R8 R4 # ... add right value
st R4 R5 # ... save value
# <string>:0
set R9 @_L16_test # Loop: continue statement
set R9 @_stdio_L16_test # Loop: continue statement
jmp R9 # ... jump to loop start
# IF statment - THEN clause - end
set R9 @_L30_done # Point towards if end
set R9 @_stdio_L30_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L31_else:
# stdio.c:126
set R9 -4 # Get BP-relative address of n
_stdio_L31_else:
# stdio.c:113
set R9 -2 # Get BP-relative address of n
add R9 BP R4 # Compute address of n
# FUNCTION CALL to putc() - begin
......@@ -819,14 +804,14 @@ _L31_else:
ld R4 R5 # Assignement '+=': load initial left value
add R5 R0 R5 # ... add right value
st R5 R4 # ... save value
# stdio.c:127
set R9 -4 # Get BP-relative address of n
# stdio.c:114
set R9 -2 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R4 3 # Get value of str
ldi R0 -2 # Get value of i
ldi R0 -3 # Get value of i
add R4 R0 R7 # Load addr of array index
ld R7 R7 # Load array value
push R7 # Push arg 1
......@@ -843,40 +828,40 @@ _L31_else:
# IF statment - ELSE clause - end
_L30_done:
_stdio_L30_done:
# IF statment - end
# IF statment - ELSE clause - end
_L28_done:
_stdio_L28_done:
# IF statment - end
# IF statment - ELSE clause - end
_L26_done:
_stdio_L26_done:
# IF statment - end
# IF statment - ELSE clause - end
_L24_done:
_stdio_L24_done:
# IF statment - end
# IF statment - ELSE clause - end
_L22_done:
_stdio_L22_done:
# IF statment - end
# stdio.c:129
set R9 -5 # Get BP-relative address of a
# stdio.c:116
set R9 -4 # Get BP-relative address of a
add R9 BP R7 # Compute address of a
set R8 1 # Use constant 1
ld R7 R5 # Assignement '+=': load initial left value
......@@ -885,20 +870,20 @@ _L22_done:
# IF statment - THEN clause - end
set R9 @_L20_done # Point towards if end
set R9 @_stdio_L20_done # Point towards if end
jmp R9 # ... jump to it
# IF statment - ELSE clause - begin
_L21_else:
# stdio.c:131
set R9 -4 # Get BP-relative address of n
_stdio_L21_else:
# stdio.c:118
set R9 -2 # Get BP-relative address of n
add R9 BP R5 # Compute address of n
# FUNCTION CALL to putc() - begin
ldi R7 3 # Get value of str
ldi R0 -2 # Get value of i
ldi R0 -3 # Get value of i
add R7 R0 R4 # Load addr of array index
ld R4 R4 # Load array value
push R4 # Push arg 1
......@@ -915,37 +900,37 @@ _L21_else:
# IF statment - ELSE clause - end
_L20_done:
_stdio_L20_done:
# IF statment - end
# IF statment - ELSE clause - end
_L18_done:
_stdio_L18_done:
# IF statment - end
# stdio.c:133
set R9 -2 # Get BP-relative address of i
# stdio.c:120
set R9 -3 # Get BP-relative address of i
add R9 BP R4 # Compute address of i
set R8 1 # Use constant 1
ld R4 R5 # Assignement '+=': load initial left value
add R5 R8 R5 # ... add right value
st R5 R4 # ... save value
set R9 @_L16_test # Point towards loop start
set R9 @_stdio_L16_test # Point towards loop start
jmp R9 # ... jump to it
_L17_done:
_stdio_L17_done:
# WHILE loop - end
# stdio.c:135
ldi R5 -4 # Get value of n
# stdio.c:122
ldi R5 -2 # Get value of n
mov R5 R0 # Set return value
set R9 @_L15_function_end # Point towards function exit
set R9 @_stdio_L15_function_end # Point towards function exit
jmp R9 # ... jump to it
# stdio.c:97 (exit function)
_L15_function_end:
# stdio.c:84 (exit function)
_stdio_L15_function_end:
pop R4 # Restore callee-save register
pop R5 # Restore callee-save register
pop R6 # Restore callee-save register
......@@ -961,7 +946,24 @@ _L15_function_end:
# string literals from file 'stdio.c'
#
_LC0:
_stdio_LC0:
str "0123456789ABCDEF\0"
_LC1:
_stdio_LC1:
str "65536\0"
#
# lib './stdio_putc.asm'
#
#
# extern int putc(char c)
#
putc:
set R8 2 # Point R8 towards argument c
add R8 SP R8 # ... located as SP+2
ld R8 R8 # Load argument c
set R9 1012 # Put command for screen
bus R9 R0 R8 # Write char to screen
set R0 1 # Set return value
ret
......
// CCT compiler with TTC backend
#ifdef __CCT_ttc__
// CCT compiler
#ifdef __CCT__
extern int putc(char c);
#define neg(i) -i
#define UINT(i) i
#define _DIGITS "0123456789ABCDEF"
#define _STR "65536"
#endif
// CCT compiler with x86 backend
#ifdef __CCT_x86__
extern int putchar(int c);
#define putc(c) putchar(c)
#define neg(i) -i
#define UINT(i) i
#define _DIGITS "0123456789ABCDEF"
#define _STR "65536"
#endif
// regular compiler
#ifndef __CCT__
#else
extern int putchar(int c);
#define putc(c) putchar(c)
#define neg(i) ~i + 1
......@@ -84,14 +72,13 @@ int putu(int u, char f) {
int puti(int i) {
int n;
n = 0;
if (UINT(i) > 32767) {
n += putc(MINUS);
n = putc(MINUS);
n += putu(neg(i), UCHAR);
return n;
} else {
return putu(i, UCHAR);
n = putu(i, UCHAR);
}
return n;
}
int printf(char *str, ...) {
......@@ -134,17 +121,3 @@ int printf(char *str, ...) {
}
return n;
}
/* int main() { */
/* puts("hello world\n"); */
/* putu(42, XCHAR); */
/* puts(" => 2A\n"); */
/* putu(42, UCHAR); */
/* puts(" => 42\n"); */
/* puti(42); */
/* puts(" => 42\n"); */
/* puti(-42); */
/* puts(" => -42\n"); */
/* printf("hello %s I'm %u (%x)\n", "stdio", 42, 42); */
/* return 0; */
/* } */
......