#!/bin/bash

IDIR=`dirname $0`
source "$IDIR"/cnt_utils.sh

## TOOL / USAGE / OPTION
TOOL=cnt_init
VERSION=0.2

HELP="
version: $VERSION
usage:   $TOOL file.c fun <option>
options:
   -i|-inline     (CIL) recursively inline the function
   -noswitch      (CIL) remose switches
   -s|-simplify   (CIL) apply a 3-adress code transformation
   -nops          add extra nop's to ease C/bin traceability
   -xcount        experimental counter insertion
   -f|-force      remove existing dir, no prompt
	-eabi          use gcc Embedded ABI (dflt is arm-elf-gcc)
   -O0|-O1|-O2    optimization level for gcc (dflt -O0)
   -CO1|-CO2      additional, customize optimization level
   -I<dir>        include dir for gcc
   -l<lib>        standard library for gcc
	-ds <string>   specify the suffix for the workind dir (dflt is CC options) 
   -v/-vv         verbose/more verbose
misc:
   -d|-dir        print the correspondint working dir and stops
output:  a directory file-fun containing
  - $(n_ref file)
  - $(n_cptr file)
  - $(n_cptrloc file)
  - $(n_looploc file)
requires:
   - arm-elf-gcc
	- (and/or arm-none-eabi-gcc)
   - cdig        (>= r.505)
"

function usage {
   echo -e "$HELP"
}

INLINE=
SIMPLIFY=
NOSWITCH=
CDIG_OPTS=""
#FORCE=false
FORCE=true
CCOPT=-O0
CFLAGS=
VERBOSE=
CLIBS=
CC=arm-elf-gcc


#customized opt levels
CFG_KEEP="\
          -fno-auto-inc-dec \
          -fno-cprop-registers \
          -fno-dce \
          -fno-defer-pop \
          -fno-dse \
          -fno-guess-branch-probability \
          -fno-if-conversion2 \
          -fno-if-conversion \
          -fno-inline-small-functions \
          -fno-ipa-pure-const \
          -fno-ipa-reference \
          -fno-merge-constants\
          -fno-split-wide-types \
          -fno-tree-builtin-call-dce \
          -fno-tree-ccp \
          -fno-tree-ch \
          -fno-tree-copyrename \
          -fno-tree-dce \
          -fno-tree-dominator-opts \
          -fno-tree-dse \
          -fno-tree-fre \
-fno-tree-loop-distribution \
-fno-tree-loop-im \
-fno-tree-loop-ivcanon \
-fno-tree-loop-linear \
-fno-tree-loop-optimize \
          -fno-tree-sra \
          -fno-tree-ter \
          -fno-unit-at-a-time \
-fno-crossjumping \
-fno-if-conversion \
-fno-if-conversion2 \
-fno-jump-tables \
-fno-loop-block \
-fno-loop-interchange \
-fno-loop-strip-mine \
-fno-move-loop-invariants \
-fno-reorder-blocks \
-fno-reorder-blocks-and-partition \
-fno-reschedule-modulo-scheduled-loops \
-fno-unroll-loops \
-fno-unroll-all-loops \
-fno-unsafe-loop-optimizations \
-fno-unswitch-loops \
"

CO1="-O1 $CFG_KEEP"
CO2="-O2 $CFG_KEEP"


COUNTERS=-counters
XCOUNT=

ECHO_DIR=false

#OPTS=`getopt -a -o isnfdhv --long dir,inline,noswitch,simplify,force,O0,O1,O2,vv,help -n "$TOOL" -- "$@"`
#checkret "Error: try '$TOOL -h' for usage"

if [ $# -lt 2 ]; then
	usage ; exit 0
fi
CFILE=$1
shift
## UNNECESSARY IF -dir
#if [ ! -f "$CFILE" ]; then
#	error "Error: can't open file \"$CFILE\""
#fi
BASE=`basename "$CFILE" .c`
FUNC=$1
shift
if [ ${FUNC:0:1} == "-" ]; then
	usage ; exit 0
fi

## DEBUG cptr2bb only !
CPTR2BB_OPT=
CC_STR=
OPT_STR=$CCOPT
EXTRA_SFX=
#eval set -- "$OPTS"
while true ; do
case "$1" in
	-h|-help) usage ; exit 0;;
	-d|-dir)  ECHO_DIR=true;;
	-i|-inline) INLINE=-inline;;
	-s|-simplify) SIMPLIFY=-simplify;;
	-n|-noswitch) NOSWITCH=-noswitch;;
	-nops)        CDIG_OPTS+=" -nops";;
	-xcount)      XCOUNT=-xcount; COUNTERS=-xcounters;;
## DEBUG cptr2bb only !
	-nostrictcfg) CPTR2BB_OPT+=" -nostrictcfg"; CDIG_OPTS+=" -allowaliases";;
	-f|-force) FORCE=true;;
   -v)       VERBOSE=-v;;
   -vv)      VERBOSE=-vv;;
	-eabi) CC=arm-none-eabi-gcc; CC_STR=$1;;
	-ds) shift; EXTRA_SFX=$1;;
	-O0) CCOPT="-O0"; OPT_STR=$1;;
	-O1) CCOPT="-O1"; OPT_STR=$1;;
	-O2) CCOPT="-O2"; OPT_STR=$1;;
	-CO1) CCOPT=$CO1; OPT_STR=$1;;
	-CO2) CCOPT=$CO2; OPT_STR=$1;;
	-l*) CLIBS+=" $1";;
	-I*) CFLAGS+=" $1";;
	"") break ;;
	*) error "unexected arg \"$1\""
esac
shift
done


#-------------------------------
# 0 - CREATE WORKING DIR
#     use '-' to ease the split ...
#  INIT ALL (SHARED) VARIALESB
#
# The name of the workdir is normalized:
# basename of c file, function to analyse,
# folowed by options influencing the method
# (inline or not, gcc optimization level) 
#-------------------------------
init_vars "$BASE"
#echo REF=$REF

#DDIR_SFX=${INLINE}${NOSWITCH}${XCOUNT}${CC_STR}${OPT_STR}${EXTRA_SFX}
DDIR_SFX=${EXTRA_SFX}

#ODIR=_cnt-"$BASE"-"$FUNC"$INLINE$XCOUNT$CCDESC
ODIR=`n_workdir "$BASE" "$FUNC" "$DDIR_SFX"`

if $ECHO_DIR; then
	echo $ODIR
	exit 0
fi

#### CHECK CFILE HERE ONLY
if [ ! -f "$CFILE" ]; then
	error "Error: can't open file \"$CFILE\""
fi

if ! $FORCE && [ -d "$ODIR" ]; then
	if ! yesno "Directory $ODOR exists, continue" ; then
		exit 0
	fi
fi

rm -rf "$ODIR"
mkdir -p "$ODIR"

echo "-> working dir $ODIR created"

#-------------------------------------------------
# 1 - C-PREPROC
#-------------------------------------------------
#       either cpp or $(CC) -E
#       + remove # line directives
#       + correct #pragma syntax (Malardalen)
#         n.b. replaced by a pseudo-call
#         _wcet_loopbound(min,max)
#         cause cil (cdig) does not handle
#         pragma correctly
#       + remove all other #pragma
#-------------------------------------------------
echo "$CC -E "$CFILE" $CFLAGS"
$CC -E "$CFILE" $CFLAGS | \
	sed -e "/^# [0-9]/d" | \
	sed -e "s/^#pragma\s\+loopbound\s\+min\s\+\([0-9]\+\)\s\+max\s\+\([0-9]\+\)/_wcet_loop_bound(\1,\2);/" | \
	sed -e "/^#pragma/d" \
	> "$ODIR"/"$BASE.cpp"

checkret  "Error: $CC -E failed, abort ..."
echo "-> preprocess done"


#-------------------------------------------------
# 2 - BUILD cprt + ref
#-------------------------------------------------
# produces:
# $ODIR/$REF
# $ODIR/$CPTR_REF
# $ODIR/$CPTRLOC
# $ODIR/$LOOPLOC
#-------------------------------------------------
checkcommand cdig "Error: cdig not available, abort ..."
# modifs first ...
echo "cdig $COUNTERS -oneret $NOSWITCH $CDIG_OPTS $INLINE $SIMPLIFY -f $FUNC $BASE.cpp $VERBOSE"
(cd $ODIR; cdig $COUNTERS -oneret $NOSWITCH $CDIG_OPTS $INLINE $SIMPLIFY -f "$FUNC" "$BASE.cpp" $VERBOSE)

checkret "Error: cdig failed, abort ..."
echo "-> ref files created"

#-------------------------------------------------
# 3 - COMPILE ref
#-------------------------------------------------
# produces: 
# $ODIR/$ELF
#
# --specs=linux.specs is necessary for running osim
#-------------------------------------------------
echo "$CC $CCOPT $CFLAGS -g3 --specs=linux.specs $REF $CLIBS -o $ELF"
(cd "$ODIR"; $CC $CCOPT $CFLAGS -g3 --specs=linux.specs "$REF" $CLIBS -o "$ELF")
checkret "Error: '$CC $CCOPT $CFLAGS -g $REF $CLIBS -o $ELF' failed, abort ..."
echo "-> $ODIR/$ELF created"

#--------------------------------------------------
# 4 - Compute cptr2bb
#--------------------------------------------------
#
#--------------------------------------------------
echo "-> building $CPTR2BB"
set -x
#(cd "$ODIR"; cptr2bb "$ELF" "$CPTRLOC" -f "$FUNC" $VERBOSE $CPTR2BB_OPT > "$CPTR2BB" && cat "$CPTR2BB")
(cd "$ODIR"; cptr2bb "$ELF" "$CPTRLOC" -f "$FUNC" $VERBOSE $CPTR2BB_OPT > "$CPTR2BB")
ec=$?
set +x
checkcode $ec "Error: \"cptr2bb $ELF $CPTRLOC\" failed, abort ..."
echo "-> $CPTR2BB done"
echo "-----------------------"

#--------------------------------------------------
# 5 - todo ref0 -> ref1 without useless counters
#--------------------------------------------------
# cptr_ref_toto.c
# ref_toto.cptr2bb
# cleancounters cptr_ref_toto.c ref_toto.cptr2bb
# =>
# cptr_ref_toto.c st where all the counters
# of kind "cptr_XXXXX YYY main ?" have been commented out
#--------------------------------------------------

echo "-> cleaning counters in $CPTR2BB with $CLEANCOUNTERS"
set -x
(cd "$ODIR"; cleancounters -i "$CPTR_REF" -o "$CPTR_REF" "$CPTR2BB" $VERBOSE)
ec=$?
set +x
checkcode $ec "Error: \"cleancounters $ELF $CPTRLOC\" failed, abort ..."
echo "-> $CLEANCOUNTERS done"
echo "-----------------------"

#--------------------------------------------------
# epilog - print stats on traceability
#--------------------------------------------------
NB_C_BLOCKS=`cat $ODIR/$CPTR2BB | wc -l`
NB_TRACED_BLOCKS=`cat $ODIR/$CPTR2BB | grep -v "?" | wc -l`
if [ $NB_C_BLOCKS -gt 0 ]; then
   percent=`echo "$NB_TRACED_BLOCKS * 100 / $NB_C_BLOCKS" | bc -l`
   printf "Traceability: %.0f%% blocks traced (%d out of %d)\n" $percent $NB_TRACED_BLOCKS $NB_C_BLOCKS
fi


