code optimization techniques: a)dead code elimination b) constant propagation

, by Prashant Gunjal

###  tac.txt ###
1 := b - c
2 * b c c
3 + b a res
4 - res no1 res
5 := 322 - no
6 := no - x
7 * x c res1

###### pr_10.c ######
/*
9) WAP to implement following code optimization techniques:
   a)dead code elimination   b) constant propagation
*/
#include<stdio.h>

struct holder
{
char seqno[3],op[3],arg1[8],arg2[8],result[8];
}tac[50];
int cnt=0,i,j,k,used,isnum;
char hunted[8];

void removeline(int no)
{
for(k=no;k<=cnt;k++)
tac[k]=tac[k+1];
cnt--;
}
void eliminate_dead()
{
//if not used in future remove that line
for(i=0;i<cnt-1;i++)
{
used=0;
strcpy(hunted,tac[i].result);
for(j=i+1;j<cnt;j++)
{
if(strcmp(tac[j].arg1,hunted)==0 || strcmp(tac[j].arg2,hunted)==0)
{
used=1;
break;
}
}
if(!used)
{
printf("\n\t Removing .. %s",tac[i].seqno);
removeline(i);
i--;
}
}
}
void const_propo()
{
//hunt var1 = const and insted of var1 replece const
for(i=0;i<cnt;i++)
{
if(strcmp(tac[i].op,":=")==0 && strcmp(tac[i].arg2,"-")==0)
{
isnum=1;
for(j=0;j<strlen(tac[i].arg1);j++)
if(!isdigit(tac[i].arg1[j]))
isnum=0;
if(isnum)
{
strcpy(hunted,tac[i].result);
for(k=i+1;k<cnt;k++)
{
if(strcmp(tac[k].arg1,hunted)==0)
strcpy(tac[k].arg1,tac[i].arg1);
if(strcmp(tac[k].arg2,hunted)==0)
strcpy(tac[k].arg2,tac[i].arg1);
}
}
}
}

int main()
{
FILE * fin =fopen("tac.txt","r");
int i;
while(!feof(fin))
{
fscanf(fin,"%s%s%s%s%s",tac[cnt].seqno,tac[cnt].op,tac[cnt].arg1,tac[cnt].arg2,tac[cnt].result);
cnt++;
}
cnt--;
printf("\n\t\t*** PURE INPUT ****");
printf("\n\tIndex\tOP\tArg1\tArg2\tResult");
for(i=0;i<cnt;i++)
{
printf("\n\t%s\t%s\t%s\t%s\t%s",tac[i].seqno,tac[i].op,tac[i].arg1,tac[i].arg2,tac[i].result);
}
const_propo();
printf("\n\t\t*** After Process ****");
printf("\n\tIndex\tOP\tArg1\tArg2\tResult");
for(i=0;i<cnt;i++)
{
printf("\n\t%s\t%s\t%s\t%s\t%s",tac[i].seqno,tac[i].op,tac[i].arg1,tac[i].arg2,tac[i].result);
}
printf("\n\tEnter t0 cont..");
scanf("%d",&i);
eliminate_dead();
printf("\n\t\t*** After Process ****");
printf("\n\tIndex\tOP\tArg1\tArg2\tResult");
for(i=0;i<cnt;i++)
{
printf("\n\t%s\t%s\t%s\t%s\t%s",tac[i].seqno,tac[i].op,tac[i].arg1,tac[i].arg2,tac[i].result);
}
fclose(fin);
}

### output #####
 ./a.out

*** PURE INPUT ****
Index OP Arg1 Arg2 Result
1 := b - c
2 * b c c
3 + b a res
4 - res no1 res
5 := 3 - pi
6 := pi - x
7 * x c res1
*** After Process ****
Index OP Arg1 Arg2 Result
1 := b - c
2 * b c c
3 + b a res
5 := 3 - pi
7 * 3 c res1

0 comments: