#!/bin/bash -eu
#
# Copyright © 2017 Samuel Holland <samuel@sholland.org>
# See LICENSE in the project directory for license terms.
#
# bash is required for regular expression matching.
#

# Adjust these as needed
ARCH=${ARCH:-or1k}
CROSS_COMPILE=${CROSS_COMPILE:-${ARCH}-linux-musl-}

# Generated, but might need adjustment
case "$ARCH" in
  arm)
    CALL_INSN="bl "
    TAIL_INSN="b "
    ;;
  or1k)
    CALL_INSN="l.jal "
    TAIL_INSN="l.j "
    ;;
  riscv*)
    CALL_INSN="jal ra,"
    TAIL_INSN="j "
esac

# Command-line parameters
input_file=$1
output_file=$2

# Internal variables
caller=unknown

cat > "$output_file" << "EOF"
strict digraph calls {
  graph [nodesep = 0.5, ranksep = 3]
  layout = dot
  node [height = 1, shape = box]
  rankdir = TB
  splines = ortho
EOF
grep -F -e '>:' -e "$CALL_INSN" -e "$TAIL_INSN" "$input_file" |
while read -r line; do
  if [[ $line =~ ^[[:xdigit:]]{8,16}\ \<([[:alnum:]_]+)\>:$ ]]; then
    caller=${BASH_REMATCH[1]}
    [[ $caller =~ ^__.+si3$ || $caller =~ ^nop_ ]] && continue
    printf '  %s\n' "$caller" >> "$output_file"
  elif [[ $line =~ ^.*\ ${CALL_INSN}+[[:xdigit:]]+\ \<([[:alnum:]_]+)\>$ ]]; then
    callee=${BASH_REMATCH[1]}
    [[ $callee =~ ^__.+si3$ || $callee =~ printf$ || $callee =~ pwrstate$ ]] && continue
    printf '  %s -> %s\n' "$caller" "$callee" >> "$output_file"
  elif [[ $line =~ ^.*\ ${TAIL_INSN}+[[:xdigit:]]+\ \<([[:alnum:]_]+)\>$ ]]; then
    callee=${BASH_REMATCH[1]}
    [[ $callee =~ ^__.+si3$ || $callee =~ printf$ || $callee =~ pwrstate$ ]] && continue
    printf '  %s -> %s [style = dashed]\n' "$caller" "$callee" >> "$output_file"
  fi
done
printf '}\n' >> "$output_file"
