#!/usr/bin/perl
#############################################################################
## Crytek Source File
## Copyright (C) 2007, Crytek Studios
##
## Creator: Michael Glueck
## Description: Patch alignment in SPU job asm.
#############################################################################

if ($#ARGV != 1)
{
  print STDERR "Syntax: spuasmpatch.pl (INPUT) (OUTPUT)\n";
  exit 1;
}

$file = $ARGV[0];
$file_out = $ARGV[1];

open(ASMTEXT, $file);
@lines = <ASMTEXT>;
close(ASMTEXT);
open(ASMTEXT_OUT, ">$file_out");

$func_pattern = '@function';
$align_pattern = '.align';
$jump_table_pattern = ".word .L";

$i=0;
$last_align = 0;
$cur_function_align = 0;
$found = 0;
$cur_function_name = "";
$cur_function_alignment_string = "";

foreach $asm_line (@lines)		
{
	if($asm_line =~ /$align_pattern/)
	{
		$last_align = $i;
	}

	if($asm_line =~ /$func_pattern/)
	{
		$found = 0;													#reset found to not list a function twice
		$cur_function_name = $asm_line;
		$cur_function_align = $last_align;
	}

	if($asm_line =~ /$jump_table_pattern/)
	{
		if($found == 0)
		{
			$found = 1;
			$function_name = substr($cur_function_name, 7, length($cur_function_name)-19);
			$old_alignment = substr($lines[$cur_function_align], 8);
			$old_alignment = substr($old_alignment,0,1);
			print "     adjust alignment for $function_name from .align $old_alignment to .align 7\n";
			$lines[$cur_function_align] = ".align 7\n";
		}
	}	
	
	$i++;	
}

print ASMTEXT_OUT @lines;
close(ASMTEXT_OUT);

