/*

Testing nullcheck operation.

NULL checks the passed pointer, adds 4 to it
and returns.

*/

#include <stdio.h>
#include <jit/jit.h>


int test_null_check(jit_function_t function, int dummy_branch)
{
	jit_value_t arg;
	jit_value_t offset;
	jit_value_t temp1, temp2;
	jit_label_t label = jit_label_undefined;

	offset = jit_value_create_nint_constant(function, jit_type_void_ptr, (jit_nint) 4);

	arg = jit_value_get_param(function, 0);

	jit_insn_check_null(function, arg);

	if(dummy_branch)
	{
		jit_insn_branch_if(function, arg, &label); 

		/* jit_insn_check_null(function, arg); */

		jit_insn_label(function, &label);
	}

	temp2 = jit_insn_add(function, arg, offset);

	jit_insn_return(function, temp2);
	return 1;
}

int main(int argc, char **argv)
{
	jit_context_t context;
	jit_type_t params[1];
	jit_type_t signature;
	jit_function_t function;
	void *arg0;
	void *args[1];
	jit_int result;

	/* Create a context to hold the JIT's primary state */
	context = jit_context_create();

	/* Lock the context while we build and compile the function */
	jit_context_build_start(context);

	/* Build the function signature */
	params[0] = jit_type_void_ptr;
	signature = jit_type_create_signature
		(jit_abi_cdecl, jit_type_void_ptr, params, 1, 1);

	/* Create the function object */
	function = jit_function_create(context, signature);

	test_null_check(function, argc > 1 ? 0 : 1);

	jit_dump_function(stdout, function, NULL);

	/* Compile the function */
	jit_function_compile(function);

	jit_dump_function(stdout, function, NULL);


	/* Unlock the context */
	jit_context_build_end(context);

	/* Execute the function and print the result */
	arg0 = "*&%^Hello World";
	args[0] = &arg0;
	jit_function_apply(function, args, &result);
	printf("%s\n", result);

	/* Clean up */
	jit_context_destroy(context);

	/* Finished */
	return 0;
}
