#!/usr/bin/python

import os
import argparse
import subprocess
import sys

#####################
# SPM compiler      #
############################################################################
#                                                                          #
# Compiles a C source file into LLVM IR code, performs transformations on  #
# this IR code and outputs an ELF file. These ELF files can later be used  #
# to create an SPM                                                         #
#                                                                          #
############################################################################
# Arguments         #
############################################################################
#                                                                          #
# --dynamic-spms  Specifies that PMs should be created statically i.e. a   #
#                   single SPM for the entire application, or that SPMs    #
#                   should be created on requests and thus multiple        #
#                   instances should be supported. The latter case will    #
#                   result in wrapper functions that assume that the first #
#                   argument is a reference to the SPM                     #
# --verbose       Specifies that the compilation steps should be verbose   #
#                   This outputs the used commands and debug info from     #
#                   the LLVM pass                                          #
# -D              Passes a token as defined to the preprocessor            #
# -i              Specifies the input file                                 #
#                                                                          #
############################################################################

def find_path( file, environment ):
	path = filter( 	os.path.exists, 
			map( lambda d: d + "/" + file , os.environ[ environment ].split( ':' ) ) )
	
	if len(path) > 0:
		return path[0]
	else:
		return ""

def find_directories( environment ):
	return filter( 	os.path.exists, 
			os.environ[ environment ].split( ':' ) )

parser = argparse.ArgumentParser( 	description='Compiles c-files to be used as part of an SPM' )

parser.add_argument(	'-D',
			nargs='*',
			metavar='defines',
			default=[],
			help='Passes a token as defined to the preprocessor' )

parser.add_argument(	'--dynamic',
			default='0',
			nargs='?',
			const='10',
			type=int,
			help='Specifies that SPMs should be created statically i.e. a single SPM for the entire application, or that SPMs should be created on requests and thus multiple instances should be supported. The latter case will result in wrapper functions that assume that the first argument is a reference to the SPM' )

parser.add_argument(	'--verbose',
			action='store_true',
			help='Provides verbose output' )

parser.add_argument(	'-i',
			nargs=1,
			required=True,
			help='the c-file to compile' )


args = parser.parse_args()

input = args.i[0]

defines = ' '.join( map( lambda d: "-D" + d, args.D ) )

if input[-2:] == ".c":
	base = input[:-2]
else:
	base = input

bc = base + ".bc"
spmbc = base + ".spm.bc"
spms = base + ".spm.s"
output = base + ".spmo"
includes = find_directories( "PCBAC_INCLUDE" )

if args.verbose:
	print_debug = "-debug-only spm_compiler "
else:
	print_debug = ""

opt_dynamic = "-num-dynamic-spms=" + str( args.dynamic )

if args.verbose:
	print "input:               " + input
	print "output:              " + output
	print "includes:            " + " ".join( includes )

cc = 'clang -emit-llvm -fPIC -fPIE -fno-common -fno-stack-protector -fno-builtin -nostdinc -fno-exceptions -fno-asynchronous-unwind-tables ' + defines + ' -DCOMPILING_SPM' + " ".join( map( lambda d : " -I " + d, includes ) ) + ' -c ' + input + ' -o ' + bc + ' &&\n ' + \
	'opt -O2 -load ' + find_path( 'Fides_Compiler.so', 'PCBAC_PASSES' ) + ' -compile_spm_object ' + opt_dynamic + ' ' + print_debug + ' ' + bc + ' -o ' + spmbc + ' &&\n ' + \
	'llc -mtriple=x86_64-linux -mattr=-avx,-sse2,-sse3,-sse  -relocation-model pic ' + spmbc + ' -o ' + spms + ' &&\n ' + \
	'as ' + spms + ' -o ' + output

if args.verbose:
	print cc

if  subprocess.call( cc, shell=True ) == 0:
	if args.verbose:
		print "Success!"
else:
	if args.verbose:
		print "Failed! - Could not compile " + args.i[0]
	
	sys.exit( -1 );

