view CbC-examples/conv.c @ 22:0eb6cac880f0

add cbc example of quicksort.
author kent <kent@cr.ie.u-ryukyu.ac.jp>
date Tue, 13 Oct 2009 17:15:58 +0900
parents 959d4c8c8abc
children
line wrap: on
line source

#include "stdio.h"

f0(int i) {
    int k,j;
    k = 3+i;
    j = g0(i+3);
    return k+4+j;
}

g0(int i) {
    return i+4;
}


typedef void *stack;

__code f_g0(int i,int k,stack sp) ;

struct cont_interface { // General Return Continuation
    __code (*ret)(int, void*);
};

__code f(int i,stack sp) {
    int k,j;
    k = 3+i;
    goto f_g0(i,k,sp);
}

struct f_g0_interface {  // Specialized Return Continuation
    __code (*ret)();
    int i_,k_,j_;
};

__code f_g1(int j,stack sp);
__code g(int i,stack sp) ;

__code f_g0(int i,int k,stack sp) { // Caller
    struct f_g0_interface *c = 
	(struct f_g0_interface *)(sp -= sizeof(struct f_g0_interface));

    c->ret = f_g1;
    c->k_ = k;
    c->i_ = i;

    goto g(i+3,sp);
}

__code f_g1(int j,stack sp) {  // Continuation 
    struct f_g0_interface *c = (struct f_g0_interface *)sp;
    int k = c->k_;
    sp += sizeof(struct f_g0_interface);
    goto (( (struct cont_interface *)sp)->ret)(k+4+j,sp);
}

__code g(int i,stack sp) {
    goto (( (struct cont_interface *)sp)->ret)(i+4,sp);
}

struct main_continuation { // General Return Continuation
    __code (*ret)(int, void*);
    __code (*main_ret)(int, void*);
    void *env;
};

__code main_return(int i,stack sp) {
    printf("#0061:%d\n",i);
    goto (( (struct main_continuation *)sp)->main_ret)(i,
           ((struct main_continuation *)sp)->env);
}

#define STACK_SIZE 2048
char main_stack[STACK_SIZE];
#define stack_last (&main_stack[STACK_SIZE])

typedef __code (*return_type)(int, void*);
int
main(int argc, char **argv)
{
    struct main_continuation *cont;
    stack sp = stack_last;

    printf("#0075:%d\n",f0(233));

    sp -= sizeof(*cont);
    cont = (struct main_continuation *)sp;
    cont->ret = main_return;
    cont->main_ret = (return_type) _CbC_return;
    cont->env = _CbC_environment;
    goto f(233,sp);
}

/* end */