/*
 * 68K/386 32-bit C compiler.
 *
 * copyright (c) 1996, David Lindauer
 * 
 * This compiler is intended for educational use.  It may not be used
 * for profit without the express written consent of the author.
 *
 * It may be freely redistributed, as long as this notice remains intact
 * and sources are distributed along with any executables derived from them.
 *
 * The author is not responsible for damages, either direct or consequential,
 * that may arise from use of this software.
 *
 * V2.05 June 2002
 * David Lindauer, gclind01@starbase.spd.louisville.edu
 *
 * Credits to Mathew Brandt for original K&R C compiler
 *
 */
/*
 * istmt.c
 *
 * channge the statement list to icode
 */
#include        <stdio.h>
#include				"utype.h"
#include        "lists.h"
#include        "expr.h"
#include        "c.h"
#include				"iexpr.h"
#include 				"iopt.h"
#include 				"diag.h"

extern int global_flag;
extern TABLE gsyms;
extern long nextlabel;
extern TYP              stdfunc;
extern SYM *currentfunc;
extern int prm_cplusplus;
extern int prm_locsub;
extern short addrsize,intsize;
extern BLOCKLIST *blockhead;
extern int blocknum;
extern QUAD *intermed_head;
extern TABLE tempsyms;
extern int firstlabel;
/*
 * virtual registers
 */
IMODE rlink = { i_rlink, 0, 0 };
IMODE rsp = { i_rsp, 0, 0 };
IMODE rstruct = { i_rstruct, 0, 0 };
IMODE rstructstar = { i_rstructstar, 0, 0 };
IMODE rret = { i_rret, 0, 0 };
static int 	diddef;     /* True if did default */
/*
 * current label values 
 */
static int     breaklab;
static int     contlab;
static int     retlab;
static int deflab;
/*
 * temporaries used in switch-case optimizations
 */
static int switchbottom, switchcount;
static int switchtop;
static int oldswitchsize=0;
static int *switchlabels=0;
static int *switchids=0;
static int *switchbinlabels=0;
static int tempnum;

void genstmtini(void)
{
	oldswitchsize = 0;
	switchlabels = switchids = switchbinlabels = 0;
	rsp.size = rlink.size = addrsize;
}
IMODE		*tempreg(int size, int mode)
/*
 * create a temporary register
 */
{
	SYM *sp;
	IMODE *ap;
	char buf[10];
	ap = xalloc(sizeof(IMODE));
	sp = xalloc(sizeof(SYM));
	sprintf(buf,"$$t%d",tempnum);
	sp->name = litlate(buf);
	sp->storage_class = sc_temp;
	sp->value.i = tempnum++;
	if (prm_locsub)
		insert(sp,&tempsyms);
	ap->offset = makenode(en_tempref,sp,0);
	ap->size = size;
	if (mode)
		ap->mode = i_immed;
	else
		ap->mode = i_direct;
	return ap;
}
IMODE    *make_direct(int i)
/*
 *      make a direct reference to an immediate value.
 */
{       return make_offset(makenode(en_icon,(char *)i,0));
}

IMODE    *make_strlab(char *s)
/*
 *      generate a direct reference to a string label.
 */
{       IMODE    *ap;
        ap = xalloc(sizeof(IMODE));
				ap->size = addrsize;
        ap->mode = i_direct;
        ap->offset = makenode(en_nacon,s,0);
        return ap;
}

void genwhile(SNODE *stmt)
/*
 *      generate code to evaluate a while statement.
 */
{       int     lab1, lab2, lab3;
        lab1 = contlab;         /* save old continue label */
        contlab = nextlabel++;  /* new continue label */
        if( stmt->s1 != 0 )      /* has block */
                {
        				lab2 = breaklab;        /* save old break label */
                breaklab = nextlabel++;
								gen_igoto(contlab);
								lab3 = nextlabel++;
								gen_label(lab3);
                genstmt(stmt->s1);
								gen_label(contlab);
								if (stmt->lst)
		 							gen_line(stmt->lst);
                truejp(stmt->exp,lab3);
                gen_label(breaklab);
                breaklab = lab2;        /* restore old break label */
                }
        else					        /* no loop code */
                {
								if (stmt->lst)
		 							gen_line(stmt->lst);
        				gen_label(contlab);
                truejp(stmt->exp,contlab);
                }
        contlab = lab1;         /* restore old continue label */
}

void gen_for(SNODE *stmt)
/*
 *      generate code to evaluate a for loop
 */
{       int     old_break, old_cont, exit_label, loop_label, start_label;
        old_break = breaklab;
        old_cont = contlab;
        loop_label = nextlabel++;
        contlab = nextlabel++;
				start_label = nextlabel++;
        exit_label = nextlabel++;
        if( stmt->label != 0 )
                gen_expr(0,stmt->label,F_NOVALUE
                        ,natural_size(stmt->label));
				
				gen_igoto(start_label);
        gen_label(loop_label);
        if( stmt->s1 != 0 ) {
								breaklab = exit_label;
                genstmt(stmt->s1);
				}
				gen_label(contlab);
        if( stmt->s2 != 0 )
                gen_expr(0,stmt->s2,F_NOVALUE,natural_size(stmt->s2));
				gen_label(start_label);
				if (stmt->lst)
		 			gen_line(stmt->lst);
        if( stmt->exp != 0 )
                truejp(stmt->exp,loop_label);
				else
						gen_igoto(loop_label);
				gen_label(exit_label);
 				breaklab = old_break;
				contlab = old_cont;
}

void genif(SNODE *stmt)
/*
 *      generate code to evaluate an if statement.
 */
{       int     lab1, lab2;
        lab1 = nextlabel++;     /* else label */
        lab2 = nextlabel++;     /* exit label */
        falsejp(stmt->exp,lab1);
        genstmt(stmt->s1);
        if( stmt->s2 != 0 )             /* else part exists */
                {
								gen_igoto(lab2);
                gen_label(lab1);
                genstmt(stmt->s2);
                gen_label(lab2);
                }
        else                            /* no else code */
                gen_label(lab1);
}

void gendo(SNODE *stmt)
/*
 *      generate code for a do - while loop.
 */
{       int     oldcont, oldbreak;
        oldcont = contlab;
        oldbreak = breaklab;
        contlab = nextlabel++;
        gen_label(contlab);
        if( stmt->s1 != 0 && stmt->s1->next != 0 )
                {
                breaklab = nextlabel++;
                genstmt(stmt->s1);      /* generate body */
                truejp(stmt->exp,contlab);
                gen_label(breaklab);
                }
        else
                {
                genstmt(stmt->s1);
                truejp(stmt->exp,contlab);
                }
        breaklab = oldbreak;
        contlab = oldcont;
}
void gen_genword(SNODE *stmt)
/*
 * generate data in the code seg
 */
{
		gen_icode(i_genword,0,make_immed((int)stmt->exp),0);
}
IMODE *set_symbol(char *name, int isproc)
/*
 *      generate a call to a library routine.
 */
{       SYM     *sp;
        IMODE *result;
        sp = gsearch(name);
        if( sp == 0 )
                {
                ++global_flag;
                sp = xalloc(sizeof(SYM));
                sp->tp = &stdfunc;
                sp->name = name;
                sp->storage_class = sc_external;
								sp->extflag = TRUE;
                insert(sp,&gsyms);
                --global_flag;
                }
				result = make_strlab(name);
				return result;					
}
IMODE *call_library(char *lib_name,int size)
/*
 *      generate a call to a library routine.
 */
{       
        IMODE *result;
				result = set_symbol(lib_name,1);
        gen_icode(i_gosub,0,result,0);
        if( size != 0 ) {
          gen_icode(i_parmadj,0,make_immed(size),0);
				}
				result = tempreg(intsize,0);
        gen_icode(i_assn,result,&rret,0);
				return result;					
}

int analyzeswitch(SNODE *stmt)
/*
 * select a type of switch-case statement
 *
 * types are :
 * 1) compact switch (label list )
 * 2) binary switch (binary tree if if statements)
 */
{
	switchbottom = 0x7fff;
	switchtop = 0;
	switchcount = 0;
	stmt = stmt->s1;
	while (stmt) {
		if (!stmt->s2) {
			switchcount++;
			if ((int)stmt->label < switchbottom)
				switchbottom = (int)stmt->label;
			if ((int)stmt->label > switchtop)
				switchtop = (int)stmt->label;
		}
		stmt = stmt->next;
	}
	switchtop++;
	if (switchcount == 0)
		return(0);
	if (switchcount > 3)
		if (switchcount*10/(switchtop-switchbottom) >= 8)
			return(1);
	return(2);
}
void bingen(int lower, int avg, int higher,IMODE *ap1, int deflab, int size)
/*
 * generate the binary tree of if statements
 */
{
	IMODE *ap2 = make_immed(switchids[avg]);
	long labnum = switchlabels[avg];
	if (switchbinlabels[avg] != -1)
		gen_label(switchbinlabels[avg]);
	gen_icgoto(i_je,labnum,ap1,ap2);
	if (avg == lower) {
		gen_igoto(deflab);
	}
	else {
		int avg1 = (lower + avg)/2;
		int avg2 = (higher + avg+1)/2;
		if (avg+1 < higher) 
			labnum = switchbinlabels[avg2]=nextlabel++;
		else
			labnum = deflab;
		if (size < 0)
			gen_icgoto(i_jg,labnum,0,0);
		else
			gen_icgoto(i_ja,labnum,0,0);
		bingen(lower,avg1,avg,ap1,deflab,size);
		if (avg+1 < higher)
			bingen(avg+1,avg2,higher,ap1,deflab,size);
	}
}
void genbinaryswitch(SNODE *stmt)
/*
 * setup for binary switch gen
 */
{
	int curlab, i=0,j,size = natural_size(stmt->exp);
	IMODE *ap1,*ap2;
	deflab = nextlabel++;
	curlab = nextlabel++;
  ap1 = gen_expr(0,stmt->exp,0,4);
	if (ap1->mode != i_direct || ap1->offset->nodetype != en_tempref) {
		ap2 = tempreg(4,0);
		gen_icode(i_assn,ap2,ap1,0);
		ap1 = ap2;
	}
	global_flag++;
	if (switchcount > oldswitchsize) {
		switchlabels = xalloc((switchcount) * sizeof(int));
		switchids = switchbinlabels = 0;
		oldswitchsize = switchcount;
	}
	if (!switchids) {
		switchbinlabels = xalloc((switchcount) * sizeof(int));
		switchids = xalloc((switchcount) * sizeof(int));
	}
	global_flag--;
	stmt = stmt->s1;
	while (stmt) {
                if( stmt->s2 )          /* default case ? */
                        {
                        stmt->label = (SNODE *) deflab;
												diddef = TRUE;
                        }
                else
                        {
												switchlabels[i] = curlab;
												switchbinlabels[i] = -1;
												switchids[i++] = (int)stmt->label;
												stmt->label = (SNODE *)curlab;
                        }
                if( stmt->s1 != 0 && stmt->next != 0 )
                        curlab = nextlabel++;
                stmt = stmt->next;
                }
	for (i=0; i < switchcount; i++)
		for (j=i+1; j < switchcount; j++)
			if (switchids[j] < switchids[i]) {
				int temp = switchids[i];
				switchids[i] = switchids[j];
				switchids[j] = temp;
				temp = switchlabels[i];
				switchlabels[i] = switchlabels[j];
				switchlabels[j] = temp;
			}
	bingen(0,(switchcount)/2,switchcount,ap1,deflab,size);
}
void gencompactswitch(SNODE *stmt)
/*
 * generate a compact (packed labels) switch
 */
{       int             curlab,i;
        IMODE    *ap;
        deflab = nextlabel++;
				curlab = nextlabel++;
        ap = gen_expr(0,stmt->exp,F_VOL,4);
				gen_icode2(i_coswitch,ap,make_immed(switchbottom),
						make_immed(switchtop-switchbottom),deflab);

	if (switchtop - switchbottom > oldswitchsize) {
		global_flag++;
		switchlabels = xalloc((switchtop-switchbottom) * sizeof(int));
		switchids = switchbinlabels = 0;
		global_flag--;
		oldswitchsize = switchtop - switchbottom;
	}
	for (i=switchbottom; i < switchtop; i++) {
		switchlabels[i-switchbottom] = deflab;
	}
	stmt = stmt->s1;
	while (stmt) {
                if( stmt->s2 )          /* default case ? */
                        {
                        stmt->label = (SNODE *)deflab;
												diddef = TRUE;
                        }
                else
                        {
												switchlabels[(int)stmt->label-switchbottom] = curlab;
												stmt->label = (SNODE *)curlab;
                        }
                if( stmt->s1 != 0 && stmt->next != 0 )
                        curlab = nextlabel++;
                stmt = stmt->next;
                }
	for (i=0; i < switchtop-switchbottom; i++)
		gen_idc(switchlabels[i]);
}

void gencase(SNODE *stmt)
/*
 *      generate all cases for a switch statement.
 */
{       while( stmt != 0 )
                {
                if( stmt->s1 != 0 )
                        {
                        gen_label((int)stmt->label);
                        genstmt(stmt->s1);
                        }
                else if( stmt->next == 0 )
                        gen_label((int)stmt->label);
                stmt = stmt->next;
                }
}

void genxswitch(SNODE *stmt)
/*
 *      analyze and generate best switch statement.
 */
{       int     oldbreak;
        oldbreak = breaklab;
        breaklab = nextlabel++;
				diddef = FALSE;
				switch (analyzeswitch(stmt)) {
  			case 2:
						genbinaryswitch(stmt);
						break;
					case 1:
						gencompactswitch(stmt);
						break;
					case 0:
						if (stmt->s1)
							stmt->s1->label = (SNODE *) nextlabel++;
						break;
				}
        gencase(stmt->s1);
        gen_label(breaklab);
				if (!diddef)
        	gen_label(deflab);
        breaklab = oldbreak;
}

void genreturn(SNODE *stmt,int flag)
/*
 *      generate a return statement.
 */
{       IMODE    *ap,*ap1;
				int size;
				/* returns a value? */
        if( stmt != 0 && stmt->exp != 0 )
        {
								if (currentfunc->tp->btp && isstructured(currentfunc->tp->btp->type)) {
									size = currentfunc->tp->btp->size;
  	              ap = gen_expr(0,stmt->exp,F_VOL,4);
									gen_icode(i_assnblock,&rstructstar,ap,(IMODE *)size);
									gen_icode(i_assn,&rret,&rstruct,0);
								}
								else {
									size = natural_size(stmt->exp);
  	              ap = gen_expr(0,stmt->exp,0,size);
									gen_icode(i_assn,&rret,ap,0);
								}
        }
				/* create the return or a branch to the return
				 * return is put at end of function...
				 */
				if (flag) {
        	if( retlab != -1 )
                gen_label(retlab);
					if (currentfunc->intflag)
           	gen_icode(i_rett,0,0,0);
					else
           	gen_icode(i_ret,0,0,0);
        }
        else {
					if (retlab == -1)
						retlab = nextlabel++;
					gen_igoto(retlab);
				}
}

void genstmt(SNODE *stmt)
/*
 *      genstmt will generate a statement and follow the next pointer
 *      until the block is generated.
 */
{
		   while( stmt != 0 )
                {
                switch( stmt->stype )
                        {
												case st_block:
																genstmt(stmt->exp);
																break;
                        case st_label:
                                gen_label((int)stmt->label);
                                break;
                        case st_goto:
																gen_igoto((int)stmt->label);
                                break;
                        case st_expr:
                                gen_expr(0,stmt->exp,F_NOVALUE,
                                        natural_size(stmt->exp));
                                break;
                        case st_return:
                                genreturn(stmt,0);
                                break;
                        case st_if:
                                genif(stmt);
                                break;
                        case st_while:
                                genwhile(stmt);
                                break;
                        case st_do:
                                gendo(stmt);
                                break;
                        case st_for:
                                gen_for(stmt);
                                break;
												case st_line:
																gen_line(stmt);
																break;
                        case st_continue:
																gen_igoto(contlab);
                                break;
                        case st_break:
																gen_igoto(breaklab);
                                break;
                        case st_switch:
                                genxswitch(stmt);
                                break;
												case st__genword:
																gen_genword(stmt);
																break;
												case st_passthrough:
																gen_asm(stmt);
																break;
                        default:
                                DIAG("unknown statement.");
                                break;
                        }
                stmt = stmt->next;
                }
}
void genfunc(SNODE *stmt)
/*
 *      generate a function body and dump the icode
 */
{       retlab = contlab = breaklab = -1;
		intermed_head = 0;
		tempnum = 0;
		blocknum = 0;
		blockhead = 0;
		addblock(-1);
		firstlabel = nextlabel;
#ifdef CPLUSPLUS
		if (prm_cplusplus)
#endif
				if (stmt->stype == st_line) {
					gen_line(stmt);
					stmt = stmt->next;
				}
				/* We do constant folding while we still have the enode list */
/*        scanconst(stmt);
*/				switchbottom = switchtop = 0;

				/* Generate the icode */
				/* LCSE is done while code is generated */
        genstmt(stmt);
        genreturn(0,1);
/*
 * icode optimizations goes here.  Note that LCSE is done through
 * DAG construction during the actual construction of the blocks
 * so it is already done at this point.
 *
 * Order IS important!!!!!!!!! be careful!!!!!
 */
				/* Global opts */
				flows_and_doms();
				commondelete(intermed_head); /* reuse common code frags */

				/* Local opts */
				peep_icode(intermed_head);	/* peepcode optimizer for icode */

				/* Code gen from icode */
				gen_strlab(currentfunc->name);  /* name of function */
				rewrite_icode(intermed_head); /* Translate to machine code & dump */
}
