//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// GenInit.cc --
//
// Author           : Rob Schluntz
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Rob Schluntz
// Last Modified On : Fri May 13 11:37:48 2016
// Update Count     : 166
//

#include <stack>
#include <list>
#include "GenInit.h"
#include "InitTweak.h"
#include "SynTree/Declaration.h"
#include "SynTree/Type.h"
#include "SynTree/Expression.h"
#include "SynTree/Statement.h"
#include "SynTree/Initializer.h"
#include "SynTree/Mutator.h"
#include "SymTab/Autogen.h"
#include "GenPoly/PolyMutator.h"

namespace InitTweak {
	namespace {
		const std::list<Label> noLabels;
		const std::list<Expression *> noDesignators;
	}

	class ReturnFixer : public GenPoly::PolyMutator {
	  public:
		/// consistently allocates a temporary variable for the return value
		/// of a function so that anything which the resolver decides can be constructed
		/// into the return type of a function can be returned.
		static void makeReturnTemp( std::list< Declaration * > &translationUnit );

		ReturnFixer();

		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );

		virtual Statement * mutate( ReturnStmt * returnStmt );

	  protected:
		std::list<DeclarationWithType*> returnVals;
		UniqueName tempNamer;
		std::string funcName;
	};

	class CtorDtor : public GenPoly::PolyMutator {
	  public:
		/// create constructor and destructor statements for object declarations.
		/// Destructors are inserted directly into the code, whereas constructors
		/// will be added in after the resolver has run so that the initializer expression
		/// is only removed if a constructor is found
		static void generateCtorDtor( std::list< Declaration * > &translationUnit );

		CtorDtor() : inFunction( false ) {}

		virtual DeclarationWithType * mutate( ObjectDecl * );
		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
		virtual Declaration* mutate( StructDecl *aggregateDecl );
		virtual Declaration* mutate( UnionDecl *aggregateDecl );
		virtual Declaration* mutate( EnumDecl *aggregateDecl );
		virtual Declaration* mutate( TraitDecl *aggregateDecl );
		virtual TypeDecl* mutate( TypeDecl *typeDecl );
		virtual Declaration* mutate( TypedefDecl *typeDecl );

		virtual Type * mutate( FunctionType *funcType );

	  protected:
		bool inFunction;
	};

	void genInit( std::list< Declaration * > & translationUnit ) {
		ReturnFixer::makeReturnTemp( translationUnit );
		CtorDtor::generateCtorDtor( translationUnit );
	}

	void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) {
		ReturnFixer fixer;
		mutateAll( translationUnit, fixer );
	}

	ReturnFixer::ReturnFixer() : tempNamer( "_retVal" ) {}

	Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) {
		// update for multiple return values
		assert( returnVals.size() == 0 || returnVals.size() == 1 );
		// hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address
		// is being returned
		if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue() ) {
			// ensure return value is not destructed by explicitly creating
			// an empty SingleInit node wherein maybeConstruct is false
			ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, returnVals.front()->get_type()->clone(), new ListInit( std::list<Initializer*>(), noDesignators, false ) );
			stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );

			// and explicitly create the constructor expression separately
			UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) );
			construct->get_args().push_back( new AddressExpr( new VariableExpr( newObj ) ) );
			construct->get_args().push_back( returnStmt->get_expr() );
			stmtsToAdd.push_back(new ExprStmt(noLabels, construct));

			returnStmt->set_expr( new VariableExpr( newObj ) );
		} // if
		return returnStmt;
	}

	DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) {
		std::list<DeclarationWithType*> oldReturnVals = returnVals;
		std::string oldFuncName = funcName;

		FunctionType * type = functionDecl->get_functionType();
		returnVals = type->get_returnVals();
		funcName = functionDecl->get_name();
		DeclarationWithType * decl = Mutator::mutate( functionDecl );
		returnVals = oldReturnVals;
		funcName = oldFuncName;
		return decl;
	}


	void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
		CtorDtor ctordtor;
		mutateAll( translationUnit, ctordtor );
	}

	namespace {
		Expression * makeCtorDtorExpr( std::string name, ObjectDecl * objDecl, std::list< Expression * > args ) {
			UntypedExpr * expr = new UntypedExpr( new NameExpr( name ) );
			expr->get_args().push_back( new AddressExpr( new VariableExpr( objDecl ) ) );
			expr->get_args().splice( expr->get_args().end(), args );
			return expr;
		}
	}

	DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
		// hands off if designated or if @=
		if ( tryConstruct( objDecl ) ) {
			if ( inFunction ) {
				if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
					// call into makeArrayFunction from validate.cc to generate calls to ctor/dtor for each element of array
					// TODO: walk initializer and generate appropriate copy ctor if element has initializer
					std::list< Expression * > args = makeInitList( objDecl->get_init() );
					if ( args.empty() ) {
						std::list< Statement * > ctor;
						std::list< Statement * > dtor;

						SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "?{}", back_inserter( ctor ) );
						SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "^?{}", front_inserter( dtor ), false );

						// Currently makeArrayFunction produces a single Statement - a CompoundStmt
						// which  wraps everything that needs to happen. As such, it's technically
						// possible to use a Statement ** in the above calls, but this is inherently
						// unsafe, so instead we take the slightly less efficient route, but will be
						// immediately informed if somehow the above assumption is broken. In this case,
						// we could always wrap the list of statements at this point with a CompoundStmt,
						// but it seems reasonable at the moment for this to be done by makeArrayFunction
						// itself
						assert( ctor.size() == 1 );
						assert( dtor.size() == 1 );
						objDecl->set_init( new ConstructorInit( new ImplicitCtorDtorStmt( ctor.front() ), new ImplicitCtorDtorStmt( dtor.front() ), objDecl->get_init() ) );
					} else {
						// array came with an initializer list: initialize each element
						// may have more initializers than elements in the array - need to check at each index that
						// we haven't exceeded size. This requires precomputing the size because it might be a side-effecting
						// computation.
						// may have fewer initializers than eleemnts in the array - need to default construct
						// remaining elements.
						// might be able to merge this with the case above.
					}
				} else {
					// it's sufficient to attempt to call the ctor/dtor for the given object and its initializer
					Expression * ctor = makeCtorDtorExpr( "?{}", objDecl, makeInitList( objDecl->get_init() ) );
					Expression * dtor = makeCtorDtorExpr( "^?{}", objDecl, std::list< Expression * >() );

					// need to remember init expression, in case no ctors exist
					// if ctor does exist, want to use ctor expression instead of init
					// push this decision to the resolver
					ExprStmt * ctorStmt = new ExprStmt( noLabels, ctor );
					ExprStmt * dtorStmt = new ExprStmt( noLabels, dtor );
					objDecl->set_init( new ConstructorInit( new ImplicitCtorDtorStmt( ctorStmt ), new ImplicitCtorDtorStmt( dtorStmt ), objDecl->get_init() ) );
				}
			}
		}
		return Mutator::mutate( objDecl );
	}

	DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
		// parameters should not be constructed and destructed, so don't mutate FunctionType
		bool oldInFunc = inFunction;
		mutateAll( functionDecl->get_oldDecls(), *this );
		inFunction = true;
		functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
		inFunction = oldInFunc;
		return functionDecl;
	}

	// should not traverse into any of these declarations to find objects
	// that need to be constructed or destructed
	Declaration* CtorDtor::mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
	Declaration* CtorDtor::mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
	Declaration* CtorDtor::mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
	Declaration* CtorDtor::mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
	TypeDecl* CtorDtor::mutate( TypeDecl *typeDecl ) { return typeDecl; }
	Declaration* CtorDtor::mutate( TypedefDecl *typeDecl ) { return typeDecl; }
	Type* CtorDtor::mutate( FunctionType *funcType ) { return funcType; }

} // namespace InitTweak

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
