//
// 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.
//
// FixGlobalInit.cc --
//
// Author           : Rob Schluntz
// Created On       : Mon May 04 15:14:56 2016
// Last Modified By : Peter A. Buhr
// Last Modified On : Wed Jun 29 22:33:15 2016
// Update Count     : 4
//

#include "FixGlobalInit.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/Visitor.h"
#include "SynTree/Attribute.h"
#include <algorithm>

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

	class GlobalFixer : public Visitor {
	  public:
		GlobalFixer( const std::string & name, bool inLibrary );

		virtual void visit( ObjectDecl *objDecl );
		virtual void visit( FunctionDecl *functionDecl );
		virtual void visit( StructDecl *aggregateDecl );
		virtual void visit( UnionDecl *aggregateDecl );
		virtual void visit( EnumDecl *aggregateDecl );
		virtual void visit( TraitDecl *aggregateDecl );
		virtual void visit( TypeDecl *typeDecl );

		UniqueName tempNamer;
		FunctionDecl * initFunction;
		FunctionDecl * destroyFunction;
	};

	void fixGlobalInit( std::list< Declaration * > & translationUnit, const std::string & name, bool inLibrary ) {
		GlobalFixer fixer( name, inLibrary );
		acceptAll( translationUnit, fixer );
		// don't need to include function if it's empty
		if ( fixer.initFunction->get_statements()->get_kids().empty() ) {
			delete fixer.initFunction;
		} else {
			translationUnit.push_back( fixer.initFunction );
		} // if

		if ( fixer.destroyFunction->get_statements()->get_kids().empty() ) {
			delete fixer.destroyFunction;
		} else {
			translationUnit.push_back( fixer.destroyFunction );
		} // if
	}

  std::string globalFunctionName( const std::string & name ) {
  	// get basename
  	std::string ret = name.substr( 0, name.find( '.' ) );
  	// replace invalid characters with _
		static std::string invalid = "/-";
  	replace_if( ret.begin(), ret.end(), []( char c ) { return invalid.find(c) != std::string::npos; }, '_' );
  	return ret;
  }

	GlobalFixer::GlobalFixer( const std::string & name, bool inLibrary ) : tempNamer( "_global_init" ) {
		std::string fixedName = globalFunctionName( name );
		std::list< Expression * > ctorParameters;
		std::list< Expression * > dtorParameters;
		if ( inLibrary ) {
			// Constructor/destructor attributes take a single parameter which
			// is the priority, with lower numbers meaning higher priority.
			// Functions specified with priority are guaranteed to run before
			// functions without a priority. To ensure that constructors and destructors
			// for library code are run before constructors and destructors for user code,
			// specify a priority when building the library. Priorities 0-100 are reserved by gcc.
			ctorParameters.push_back( new ConstantExpr( Constant::from_int( 101 ) ) );
			dtorParameters.push_back( new ConstantExpr( Constant::from_int( 101 ) ) );
		}
		initFunction = new FunctionDecl( "_init_" + fixedName, DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
		initFunction->get_attributes().push_back( new Attribute( "constructor", ctorParameters ) );
		destroyFunction = new FunctionDecl( "_destroy_" + fixedName, DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
		destroyFunction->get_attributes().push_back( new Attribute( "destructor", dtorParameters ) );
	}

	void GlobalFixer::visit( ObjectDecl *objDecl ) {
		std::list< Statement * > & initStatements = initFunction->get_statements()->get_kids();
		std::list< Statement * > & destroyStatements = destroyFunction->get_statements()->get_kids();

		// C allows you to initialize objects with constant expressions
		// xxx - this is an optimization. Need to first resolve constructors before we decide
		// to keep C-style initializer.
		// if ( isConstExpr( objDecl->get_init() ) ) return;

		if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
			// a decision should have been made by the resolver, so ctor and init are not both non-NULL
			assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );

			Statement * dtor = ctorInit->get_dtor();
			if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
				// don't need to call intrinsic dtor, because it does nothing, but
				// non-intrinsic dtors must be called
				destroyStatements.push_front( dtor );
				ctorInit->set_dtor( NULL );
			} // if
			if ( Statement * ctor = ctorInit->get_ctor() ) {
				initStatements.push_back( ctor );
				objDecl->set_init( NULL );
				ctorInit->set_ctor( NULL );
			} else if ( Initializer * init = ctorInit->get_init() ) {
				objDecl->set_init( init );
				ctorInit->set_init( NULL );
			} else {
				// no constructor and no initializer, which is okay
				objDecl->set_init( NULL );
			} // if
			delete ctorInit;
		} // if
	}

	// only modify global variables
	void GlobalFixer::visit( FunctionDecl *functionDecl ) {}
	void GlobalFixer::visit( StructDecl *aggregateDecl ) {}
	void GlobalFixer::visit( UnionDecl *aggregateDecl ) {}
	void GlobalFixer::visit( EnumDecl *aggregateDecl ) {}
	void GlobalFixer::visit( TraitDecl *aggregateDecl ) {}
	void GlobalFixer::visit( TypeDecl *typeDecl ) {}

} // namespace InitTweak

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

