#!/bin/sh
# Compile and assemble the test cases in the current working directory.
# These test cases are not valid GNU C, so the compiler should return a
# non-zero exit status.

cleanup()
{
  rm -f *.s *.o core tempfile x.c x.s a.out *.c.* err
}

if [ "x$1" = x-clean ]
  then
    shift
    cleanup
    if [ $# = 0 ]
      then exit 0
      fi
  fi

if [ $# = 0 ]
  then exec $0 gcc
  fi

if [ $# -gt 1 ]
  then
    for i in "$@"
      do ./$0 "$i"
      done
    exit 0
  fi

if [ -d "$1" ]
  then GCC="$1/xgcc -B$1/"
  else GCC="$1"
  fi
echo "TESTING WITH $GCC"

echo "f(m){int i,s=0;for(i=-m;i<m;i++)s+=i;return s;}" > x.c

# Make sure the specified compiler can be run.
if $GCC -S x.c
  then true
  else
    echo "Tests not run"
    exit 0
  fi

# Check if we can assemble.
NATIVE=false
if $GCC -c x.c 2> /dev/null
  then NATIVE=true
  fi
rm -f x.c

if $NATIVE
  then SC=-c
  else
    echo "No assembler found--can't verify assembler syntax."
    SC=-S
  fi

FAILURES=0

testit()
{
  prog=$1
  shift
  $GCC $SC $prog $@ -w -o tempfile 2> err
  status=$?
  if [ $status = 0 ]
    then
      echo "ERROR: compiler accepts syntax error with: $@"
      FAILURES=`expr $FAILURES + 1`
    else
      if grep "fatal signal" < err > tempfile
	then
          signal=`sed 's;.*signal \(.*\)$;\1;' < tempfile`
	  echo "ERROR: compiler got signal $signal with: $@"
	  FAILURES=`expr $FAILURES + 1`
	fi
    fi
}

for i in `ls -r *.c`; do
  echo $i
  testit $i
  testit $i -O
  testit $i -O2
  testit $i -O2 -fomit-frame-pointer
  if egrep >/dev/null 'for|while' $i
    then
    testit $i -O2 -funroll-loops
    testit $i -O2 -funroll-all-loops
    fi
done

cleanup

if [ $FAILURES = 0 ]
  then echo "Test completed successfully."
else if [ $FAILURES = 1 ]
  then echo "Test completed with 1 failure."
else echo "Test completed with $FAILURES failures."
fi; fi
