//
// 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.
//
// Lvalue.cc --
//
// Author           : Richard C. Bilson
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Fri Mar 17 09:11:18 2017
// Update Count     : 5
//

#include <cassert>

#include "Lvalue.h"

#include "GenPoly.h"

#include "SynTree/Declaration.h"
#include "SynTree/Type.h"
#include "SynTree/Expression.h"
#include "SynTree/Statement.h"
#include "SynTree/Visitor.h"
#include "SynTree/Mutator.h"
#include "SymTab/Indexer.h"
#include "SymTab/Autogen.h"
#include "ResolvExpr/Resolver.h"
#include "ResolvExpr/typeops.h"

#include "Common/UniqueName.h"
#include "Common/utility.h"
#include "InitTweak/InitTweak.h"

#include "Common/PassVisitor.h"

// need to be careful about polymorphic references... e.g. in *? (___operator_deref__A0_1_0_0__Fd0_Pd0_intrinsic___1)
// the variable is automatically dereferenced and this causes errors dereferencing void*.

#if 0
#define PRINT(x) x
#else
#define PRINT(x)
#endif

namespace GenPoly {
	namespace {
		// TODO: fold this into the general createDeref function??
		Expression * mkDeref( Expression * arg ) {
			if ( SymTab::dereferenceOperator ) {
				VariableExpr * deref = new VariableExpr( SymTab::dereferenceOperator );
				deref->set_result( new PointerType( Type::Qualifiers(), deref->get_result() ) );
				Type * base = InitTweak::getPointerBase( arg->get_result() );
				assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->get_result() ).c_str() );
				ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
				delete ret->get_result();
				ret->set_result( new ReferenceType( Type::Qualifiers(), base->clone() ) );
				return ret;
			} else {
				return UntypedExpr::createDeref( arg );
			}
		}

		struct ReferenceConversions final {
			Expression * postmutate( CastExpr * castExpr );
		};

		/// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
		struct FixIntrinsicArgs final {
			Expression * postmutate( ApplicationExpr *appExpr );
		};


		/// Replace reference types with pointer types
		struct ReferenceTypeElimination final {
			Type * postmutate( ReferenceType * refType );
		};

		/// GCC-like Generalized Lvalues (which have since been removed from GCC)
		/// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
		/// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
		struct GeneralizedLvalue final {
			Expression * postmutate( AddressExpr * addressExpr );
		};

		/// Removes redundant &*/*& pattern that this pass can generate
		struct CollapseAddrDeref final {
			Expression * postmutate( AddressExpr * addressExpr );
			Expression * postmutate( ApplicationExpr * appExpr );
		};
	} // namespace

	void convertLvalue( std::list< Declaration* >& translationUnit ) {
		std::cerr << "convertLvalue" << std::endl;
		PassVisitor<ReferenceConversions> refCvt;
		PassVisitor<ReferenceTypeElimination> elim;
		PassVisitor<GeneralizedLvalue> genLval;
		PassVisitor<FixIntrinsicArgs> fixer;
		PassVisitor<CollapseAddrDeref> collapser;
		mutateAll( translationUnit, refCvt );
		mutateAll( translationUnit, fixer );
		mutateAll( translationUnit, elim );
		mutateAll( translationUnit, genLval );
		mutateAll( translationUnit, collapser );
	}

	namespace {
		Type* isLvalueRet( FunctionType *function ) {
			if ( function->get_returnVals().empty() ) return 0;
			Type *ty = function->get_returnVals().front()->get_type();
			return dynamic_cast< ReferenceType * >( ty ) ;
		}

		bool isIntrinsicApp( ApplicationExpr *appExpr ) {
			if ( VariableExpr *varExpr = dynamic_cast< VariableExpr* >( appExpr->get_function() ) ) {
				return varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic;
			} else {
				return false;
			} // if
		}

		bool isDeref( Expression * expr ) {
			if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
				return InitTweak::getFunctionName( untyped ) == "*?";
			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
				if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
					return func->get_linkage() == LinkageSpec::Intrinsic && InitTweak::getFunctionName( appExpr ) == "*?";
				}
			}
			return false;
		}

		bool isIntrinsicReference( Expression * expr ) {
			if ( isDeref( expr ) ) return true;
			else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
				return InitTweak::getFunctionName( untyped ) == "?[?]";
			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
				if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
					return func->get_linkage() == LinkageSpec::Intrinsic && InitTweak::getFunctionName( appExpr ) == "?[?]";
				}
			}
			return false;
		}

		void fixArg( Expression *& arg, Type * formal ) {
			if ( dynamic_cast<ReferenceType*>( formal ) ) {
				// if the parameter is a reference, add a dereference to the reference-typed argument.
				Type * baseType = InitTweak::getPointerBase( arg->get_result() );
				assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->get_result() ) );
				PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
				delete arg->get_result();
				arg->set_result( ptrType );
				arg = mkDeref( arg );
			}
		}

		// xxx - might need to & every * (or every * that is an arg to non-intrinsic function??)
		Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
			// intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
			if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
				if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
					FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
					assertf( ftype, "Function declaration does not have function type." );
					for ( auto p : group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
						Expression *& arg = std::get<0>( p );
						DeclarationWithType * formal = std::get<1>( p );
						PRINT(
							std::cerr << "pair<0>: " << arg << std::endl;
							std::cerr << "pair<1>: " << formal->get_type() << std::endl;
						)
						if ( isIntrinsicReference( arg ) ) { // intrinsic functions that turn pointers into references
							// if argument is dereference or array subscript, the result isn't REALLY a reference, so it's not necessary to fix the argument
							PRINT( std::cerr << "skipping intrinsic reference" << std::endl; )
							continue;
						} else {
							fixArg( arg, formal->get_type() );
						}
					}
				}
			}
			return appExpr;
		}

		Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
			// xxx - is it possible to convert directly between reference types with a different base? E.g.,
			//   int x;
			//   (double&)x;
			// At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
			// after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
			// pointer casts in the right places.

			// conversion to reference type
			if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_result() ) ) {
				(void)refType;
				if ( ReferenceType * otherRef = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
					// nothing to do if casting from reference to reference.
					(void)otherRef;
					PRINT( std::cerr << "convert reference to reference -- nop" << std::endl; )
					if ( isIntrinsicReference( castExpr->get_arg() ) ) {
						Expression * callExpr = castExpr->get_arg();
						PRINT(
							std::cerr << "but arg is deref -- &" << std::endl;
							std::cerr << callExpr << std::endl;
						)
						// move environment out to new top-level
						callExpr->set_env( castExpr->get_env() );
						castExpr->set_arg( nullptr );
						castExpr->set_env( nullptr );
						delete castExpr;
						return callExpr;
					}
					assertf( false, "non-intrinsic reference with cast of reference to reference not yet supported: ", toString( castExpr ) );
					PRINT( std::cerr << castExpr << std::endl; )
					return castExpr;
				} else if ( castExpr->get_arg()->get_result()->get_lvalue() ) {
					// conversion from lvalue to reference
					// xxx - keep cast, but turn into pointer cast??
					// xxx - memory
					PRINT(
						std::cerr << "convert lvalue to reference -- &" << std::endl;
						std::cerr << castExpr->get_arg() << std::endl;
					)
					AddressExpr * ret = new AddressExpr( castExpr->get_arg() );
					if ( refType->get_base()->get_qualifiers() != castExpr->get_arg()->get_result()->get_qualifiers() ) {
						// must keep cast if cast-to type is different from the actual type
						castExpr->set_arg( ret );

						return castExpr;
					}
					ret->set_env( castExpr->get_env() );
					castExpr->set_env( nullptr );
					castExpr->set_arg( nullptr );
					delete castExpr;
					return ret;
				} else {
					// rvalue to reference conversion -- introduce temporary
				}
				assertf( false, "Only conversions to reference from lvalue are currently supported: %s", toString( castExpr ).c_str() );
			} else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
				// conversion from reference to rvalue
				// should be easy, just need to move deref code up here?
				PRINT( std::cerr << "convert reference to rvalue -- *" << std::endl; )
				if ( isIntrinsicReference( castExpr->get_arg() ) ) {
					PRINT( std::cerr << "but arg is intrinsic reference -- nop" << std::endl; )
					return castExpr;
				}
				PRINT( std::cerr << "was = " << castExpr << std::endl; )

				Expression * deref = mkDeref( castExpr->get_arg() );
				deref->set_env( castExpr->get_env() );
				castExpr->set_arg( nullptr );
				castExpr->set_env( nullptr );
				delete castExpr;
				PRINT( std::cerr << "now: " << deref << std::endl; )
				return deref;
			}
			return castExpr;
		}

		Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
			Type * base = refType->get_base();
			refType->set_base( nullptr );
			delete refType;
			return new PointerType( Type::Qualifiers(), base );
		}

		Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
			if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( addrExpr->get_arg() ) ) {
				Expression * arg1 = commaExpr->get_arg1()->clone();
				Expression * arg2 = commaExpr->get_arg2()->clone();
				delete addrExpr;
				return new CommaExpr( arg1, new AddressExpr( arg2 ) );
			} else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( addrExpr->get_arg() ) ) {
				Expression * arg1 = condExpr->get_arg1()->clone();
				Expression * arg2 = condExpr->get_arg2()->clone();
				Expression * arg3 = condExpr->get_arg3()->clone();
				delete addrExpr;
				return new ConditionalExpr( arg1, new AddressExpr( arg2 ), new AddressExpr( arg3 ) );
			}
			return addrExpr;
		}

		Expression * CollapseAddrDeref::postmutate( AddressExpr * addressExpr ) {
			Expression * arg = addressExpr->get_arg();
			if ( isIntrinsicReference( arg ) ) {
				std::string fname = InitTweak::getFunctionName( arg );
				if ( fname == "*?" ) {
					Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
					Expression * ret = arg0;
					ret->set_env( addressExpr->get_env() );
					arg0 = nullptr;
					addressExpr->set_env( nullptr );
					delete addressExpr;
					return ret;
				}
			}
			return addressExpr;
		}

		Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
			if ( isIntrinsicReference( appExpr ) ) {
				std::string fname = InitTweak::getFunctionName( appExpr );
				if ( fname == "*?" ) {
					Expression * arg = InitTweak::getCallArg( appExpr, 0 );
					// xxx - this isn't right, because it can remove casts that should be there...
					// while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
					// 	arg = castExpr->get_arg();
					// }
					if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
						Expression * ret = addrExpr->get_arg();
						ret->set_env( appExpr->get_env() );
						addrExpr->set_arg( nullptr );
						appExpr->set_env( nullptr );
						delete appExpr;
						return ret;
					}
				}
			}
			return appExpr;
		}
	} // namespace
} // namespace GenPoly

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