Index: src/GenPoly/Lvalue.cc
===================================================================
--- src/GenPoly/Lvalue.cc	(revision 08fc48f4a5c70b7f3e402da3afef2763f754ff3a)
+++ src/GenPoly/Lvalue.cc	(revision 9aaac6e93085196ddc22e508c0fdfa1ee11ae660)
@@ -17,10 +17,14 @@
 #include <string>                        // for string
 
+#include "Common/PassVisitor.h"
 #include "Common/SemanticError.h"        // for SemanticError
 #include "GenPoly.h"                     // for isPolyType
 #include "Lvalue.h"
+
 #include "Parser/LinkageSpec.h"          // for Spec, isBuiltin, Intrinsic
 #include "ResolvExpr/TypeEnvironment.h"  // for AssertionSet, OpenVarSet
 #include "ResolvExpr/Unify.h"            // for unify
+#include "ResolvExpr/typeops.h"
+#include "SymTab/Autogen.h"
 #include "SymTab/Indexer.h"              // for Indexer
 #include "SynTree/Declaration.h"         // for Declaration, FunctionDecl
@@ -31,23 +35,48 @@
 #include "SynTree/Visitor.h"             // for Visitor, acceptAll
 
+#if 0
+#define PRINT(x) x
+#else
+#define PRINT(x)
+#endif
+
 namespace GenPoly {
 	namespace {
-		/// Replace uses of lvalue returns with appropriate pointers
-		class Pass1 : public Mutator {
-		  public:
-			Pass1();
-
-			virtual Expression *mutate( ApplicationExpr *appExpr );
-			virtual Statement *mutate( ReturnStmt *appExpr );
-			virtual DeclarationWithType *mutate( FunctionDecl *funDecl );
-		  private:
-			DeclarationWithType* retval;
-		};
-
-		/// Replace declarations of lvalue returns with appropriate pointers
-		class Pass2 : public Visitor {
-		  public:
-			virtual void visit( FunctionType *funType );
-		  private:
+		// 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( base->clone() );
+				ret->get_result()->set_lvalue( true );
+				return ret;
+			} else {
+				return UntypedExpr::createDeref( arg );
+			}
+		}
+
+		struct ReferenceConversions final {
+			Expression * postmutate( CastExpr * castExpr );
+			Expression * postmutate( AddressExpr * addrExpr );
+		};
+
+		/// 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 );
+		};
+
+		struct FixIntrinsicResult final : public WithGuards {
+			Expression * postmutate( ApplicationExpr * appExpr );
+			void premutate( FunctionDecl * funcDecl );
+			bool inIntrinsic = false;
+		};
+
+		/// Replace reference types with pointer types
+		struct ReferenceTypeElimination final {
+			Type * postmutate( ReferenceType * refType );
 		};
 
@@ -55,117 +84,325 @@
 		/// 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)
-		class GeneralizedLvalue : public Mutator {
-			typedef Mutator Parent;
-
-			virtual Expression * mutate( MemberExpr * memExpr );
-			virtual Expression * mutate( AddressExpr * addressExpr );
+		struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
+			Expression * postmutate( AddressExpr * addressExpr );
+			Expression * postmutate( MemberExpr * memExpr );
 
 			template<typename Func>
 			Expression * applyTransformation( Expression * expr, Expression * arg, Func mkExpr );
 		};
+
+		/// Removes redundant &*/*& pattern that this pass can generate
+		struct CollapseAddrDeref final {
+			Expression * postmutate( AddressExpr * addressExpr );
+			Expression * postmutate( ApplicationExpr * appExpr );
+		};
+
+		struct AddrRef final : public WithGuards {
+			void premutate( AddressExpr * addrExpr );
+			Expression * postmutate( AddressExpr * addrExpr );
+			void premutate( Expression * expr );
+
+			bool first = true;
+			bool current = false;
+			int refDepth = 0;
+		};
 	} // namespace
 
+	static bool referencesEliminated = false;
+	// used by UntypedExpr::createDeref to determine whether result type of dereference should be ReferenceType or value type.
+	bool referencesPermissable() {
+		return ! referencesEliminated;
+	}
+
 	void convertLvalue( std::list< Declaration* >& translationUnit ) {
-		Pass1 p1;
-		Pass2 p2;
-		GeneralizedLvalue genLval;
-		mutateAll( translationUnit, p1 );
-		acceptAll( translationUnit, p2 );
+		PassVisitor<ReferenceConversions> refCvt;
+		PassVisitor<ReferenceTypeElimination> elim;
+		PassVisitor<GeneralizedLvalue> genLval;
+		PassVisitor<FixIntrinsicArgs> fixer;
+		PassVisitor<CollapseAddrDeref> collapser;
+		PassVisitor<AddrRef> addrRef;
+		PassVisitor<FixIntrinsicResult> intrinsicResults;
+		mutateAll( translationUnit, intrinsicResults );
+		mutateAll( translationUnit, addrRef );
+		mutateAll( translationUnit, refCvt );
+		mutateAll( translationUnit, fixer );
+		mutateAll( translationUnit, collapser );
 		mutateAll( translationUnit, genLval );
+		mutateAll( translationUnit, elim );  // last because other passes need reference types to work
+
+		// from this point forward, no other pass should create reference types.
+		referencesEliminated = true;
 	}
 
 	Expression * generalizedLvalue( Expression * expr ) {
-		GeneralizedLvalue genLval;
+		PassVisitor<GeneralizedLvalue> genLval;
 		return expr->acceptMutator( genLval );
 	}
 
 	namespace {
-		Type* isLvalueRet( FunctionType *function ) {
-			if ( function->get_returnVals().empty() ) return 0;
-			Type *ty = function->get_returnVals().front()->get_type();
-			return ty->get_lvalue() ? ty : 0;
-		}
-
-		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
-		}
-
-		Pass1::Pass1() {
-		}
-
-		DeclarationWithType * Pass1::mutate( FunctionDecl *funcDecl ) {
-			if ( funcDecl->get_statements() ) {
-				DeclarationWithType* oldRetval = retval;
-				retval = 0;
-				if ( ! LinkageSpec::isBuiltin( funcDecl->get_linkage() ) && isLvalueRet( funcDecl->get_functionType() ) ) {
-					retval = funcDecl->get_functionType()->get_returnVals().front();
-				}
-				// fix expressions and return statements in this function
-				funcDecl->set_statements( funcDecl->get_statements()->acceptMutator( *this ) );
-				retval = oldRetval;
-			} // if
-			return funcDecl;
-		}
-
-		Expression * Pass1::mutate( ApplicationExpr *appExpr ) {
-			appExpr->get_function()->acceptMutator( *this );
-			mutateAll( appExpr->get_args(), *this );
-
-			PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
-			FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
-
-			Type *funType = isLvalueRet( function );
-			if ( funType && ! isIntrinsicApp( appExpr ) ) {
-				Expression *expr = appExpr;
-				Type *appType = appExpr->get_result();
-				if ( isPolyType( funType ) && ! isPolyType( appType ) ) {
-					// make sure cast for polymorphic type is inside dereference
-					expr = new CastExpr( appExpr, new PointerType( Type::Qualifiers(), appType->clone() ) );
-				}
-				UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
-				deref->set_result( appType->clone() );
-				appExpr->set_result( new PointerType( Type::Qualifiers(), appType ) );
-				deref->get_args().push_back( expr );
-				return deref;
-			} else {
-				return appExpr;
-			} // if
-		}
-
-		Statement * Pass1::mutate(ReturnStmt *retStmt) {
-			if ( retval && retStmt->get_expr() ) {
-				if ( retStmt->get_expr()->get_result()->get_lvalue() ) {
-					// ***** Code Removal ***** because casts may be stripped already
-
-					// strip casts because not allowed to take address of cast
-					// while ( CastExpr *castExpr = dynamic_cast< CastExpr* >( retStmt->get_expr() ) ) {
-					// 	retStmt->set_expr( castExpr->get_arg() );
-					// 	retStmt->get_expr()->set_env( castExpr->get_env() );
-					// 	castExpr->set_env( 0 );
-					// 	castExpr->set_arg( 0 );
-					// 	delete castExpr;
-					// } // while
-					retStmt->set_expr( new AddressExpr( retStmt->get_expr()->acceptMutator( *this ) ) );
+		// true for intrinsic function calls that return a reference
+		bool isIntrinsicReference( Expression * expr ) {
+			if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
+				std::string fname = InitTweak::getFunctionName( untyped );
+				// known intrinsic-reference prelude functions
+				return fname == "*?" || fname == "?[?]";
+			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
+				if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
+					// use type of return variable rather than expr result type, since it may have been changed to a pointer type
+					FunctionType * ftype = GenPoly::getFunctionType( func->get_type() );
+					Type * ret = ftype->get_returnVals().empty() ? nullptr : ftype->get_returnVals().front()->get_type();
+					return func->get_linkage() == LinkageSpec::Intrinsic && dynamic_cast<ReferenceType *>( ret );
+				}
+			}
+			return false;
+		}
+
+		Expression * FixIntrinsicResult::postmutate( ApplicationExpr * appExpr ) {
+			if ( isIntrinsicReference( appExpr ) ) {
+				// eliminate reference types from intrinsic applications - now they return lvalues
+				Type * result = appExpr->get_result();
+				appExpr->set_result( result->stripReferences()->clone() );
+				appExpr->get_result()->set_lvalue( true );
+				if ( ! inIntrinsic ) {
+					// when not in an intrinsic function, add a cast to
+					// don't add cast when in an intrinsic function, since they already have the cast
+					Expression * ret = new CastExpr( appExpr, result );
+					ret->set_env( appExpr->get_env() );
+					appExpr->set_env( nullptr );
+					return ret;
+				}
+				delete result;
+			}
+			return appExpr;
+		}
+
+		void FixIntrinsicResult::premutate( FunctionDecl * funcDecl ) {
+			GuardValue( inIntrinsic );
+			inIntrinsic =  funcDecl->linkage == LinkageSpec::Intrinsic;
+		}
+
+		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 ) ) {
+				FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
+				assertf( ftype, "Function declaration does not have function type." );
+				// can be of differing lengths only when function is variadic
+				assertf( ftype->get_parameters().size() == appExpr->get_args().size() || ftype->get_isVarArgs(), "ApplicationExpr args do not match formal parameter type." );
+
+
+				unsigned int i = 0;
+				const unsigned int end = ftype->get_parameters().size();
+				for ( auto p : unsafe_group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
+					if (i == end) break;
+					Expression *& arg = std::get<0>( p );
+					Type * formal = std::get<1>( p )->get_type();
+					PRINT(
+						std::cerr << "pair<0>: " << arg << std::endl;
+						std::cerr << "pair<1>: " << formal << std::endl;
+					)
+					if ( dynamic_cast<ReferenceType*>( formal ) ) {
+						if ( isIntrinsicReference( arg ) ) { // do not combine conditions, because that changes the meaning of the else if
+							if ( function->get_linkage() != LinkageSpec::Intrinsic ) { // 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 << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
+								)
+								arg = new AddressExpr( arg );
+							}
+						} else if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
+							// std::cerr << "===adding deref to arg" << std::endl;
+							// 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() ).c_str() );
+							PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
+							delete arg->get_result();
+							arg->set_result( ptrType );
+							arg = mkDeref( arg );
+						}
+					}
+					++i;
+				}
+			}
+			return appExpr;
+		}
+
+		// idea: &&&E: get outer &, inner &
+		// at inner &, record depth D of reference type
+		// at outer &, add D derefs.
+		void AddrRef::premutate( Expression * ) {
+			GuardValue( current );
+			GuardValue( first );
+			current = false;
+			first = true;
+		}
+
+		void AddrRef::premutate( AddressExpr * ) {
+			GuardValue( current );
+			GuardValue( first );
+			current = first;
+			first = false;
+			if ( current ) {
+				GuardValue( refDepth );
+				refDepth = 0;
+			}
+		}
+
+		Expression * AddrRef::postmutate( AddressExpr * addrExpr ) {
+			if ( refDepth == 0 ) {
+				if ( ! isIntrinsicReference( addrExpr->get_arg() ) ) {
+					// try to avoid ?[?]
+					refDepth = addrExpr->get_arg()->get_result()->referenceDepth();
+				}
+			}
+			if ( current ) {
+				Expression * ret = addrExpr;
+				while ( refDepth ) {
+					ret = mkDeref( ret );
+					refDepth--;
+				}
+				return ret;
+			}
+			return addrExpr;
+		}
+
+		Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
+			// Inner expression may have been lvalue to reference conversion, which becomes an address expression.
+			// In this case, remove the outer address expression and return the argument.
+			// TODO: It's possible that this might catch too much and require a more sophisticated check.
+			return addrExpr;
+		}
+
+		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;
+						)
+						callExpr = new AddressExpr( callExpr ); // this doesn't work properly for multiple casts
+						delete callExpr->get_result();
+						callExpr->set_result( refType->clone() );
+						// 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;
+					}
+					int depth1 = refType->referenceDepth();
+					int depth2 = otherRef->referenceDepth();
+					int diff = depth1-depth2;
+					if ( diff == 0 ) {
+						assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
+						PRINT( std::cerr << castExpr << std::endl; )
+						return castExpr;
+					} else if ( diff < 0 ) {
+						Expression * ret = castExpr->get_arg();
+						for ( int i = 0; i < diff; ++i ) {
+							ret = mkDeref( ret );
+						}
+						ret->set_env( castExpr->get_env() );
+						delete ret->get_result();
+						ret->set_result( castExpr->get_result() );
+						castExpr->set_env( nullptr );
+						castExpr->set_arg( nullptr );
+						castExpr->set_result( nullptr );
+						delete castExpr;
+						return ret;
+					} else if ( diff > 0 ) {
+						Expression * ret = castExpr->get_arg();
+						for ( int i = 0; i < diff; ++i ) {
+							ret = new AddressExpr( ret );
+						}
+						ret->set_env( castExpr->get_env() );
+						delete ret->get_result();
+						ret->set_result( castExpr->get_result() );
+						castExpr->set_env( nullptr );
+						castExpr->set_arg( nullptr );
+						castExpr->set_result( nullptr );
+						delete castExpr;
+						return ret;
+					}
+
+					assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
+					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() );
+					delete ret->get_result();
+					ret->set_result( castExpr->get_result() );
+					castExpr->set_env( nullptr );
+					castExpr->set_arg( nullptr );
+					castExpr->set_result( nullptr );
+					delete castExpr;
+					return ret;
 				} else {
-					throw SemanticError( "Attempt to return non-lvalue from an lvalue-qualified function" );
-				} // if
-			} // if
-			return retStmt;
-		}
-
-		void Pass2::visit( FunctionType *funType ) {
-			std::string typeName;
-			if ( isLvalueRet( funType ) ) {
-				DeclarationWithType *retParm = funType->get_returnVals().front();
-
-				// make a new parameter that is a pointer to the type of the old return value
-				retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
-			} // if
-
-			Visitor::visit( funType );
+					// 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() ) ) {
+				(void)refType;
+				// conversion from reference to rvalue
+				PRINT(
+					std::cerr << "convert reference to rvalue -- *" << std::endl;
+					std::cerr << "was = " << castExpr << std::endl;
+				)
+				Expression * ret = castExpr->get_arg();
+				TypeSubstitution * env = castExpr->get_env();
+				castExpr->set_env( nullptr );
+				if ( ! isIntrinsicReference( ret ) ) {
+					// dereference if not already dereferenced
+					ret = mkDeref( ret );
+				}
+				if ( ResolvExpr::typesCompatibleIgnoreQualifiers( castExpr->get_result(), castExpr->get_arg()->get_result()->stripReferences(), SymTab::Indexer() ) ) {
+					// can remove cast if types are compatible, changing expression type to value type
+					ret->set_result( castExpr->get_result()->clone() );
+					castExpr->set_arg( nullptr );
+					delete castExpr;
+				} else {
+					// must keep cast if types are different
+					castExpr->set_arg( ret );
+					ret = castExpr;
+				}
+				ret->set_env( env );
+				PRINT( std::cerr << "now: " << ret << std::endl; )
+				return ret;
+			}
+			return castExpr;
+		}
+
+		Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
+			Type * base = refType->get_base();
+			Type::Qualifiers qualifiers = refType->get_qualifiers();
+			refType->set_base( nullptr );
+			delete refType;
+			return new PointerType( qualifiers, base );
 		}
 
@@ -175,14 +412,14 @@
 				Expression * arg1 = commaExpr->get_arg1()->clone();
 				Expression * arg2 = commaExpr->get_arg2()->clone();
-				Expression * ret = new CommaExpr( arg1, mkExpr( arg2 ) );
+				Expression * ret = new CommaExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ) );
 				ret->set_env( expr->get_env() );
 				expr->set_env( nullptr );
 				delete expr;
-				return ret->acceptMutator( *this );
+				return ret;
 			} else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( arg ) ) {
 				Expression * arg1 = condExpr->get_arg1()->clone();
 				Expression * arg2 = condExpr->get_arg2()->clone();
 				Expression * arg3 = condExpr->get_arg3()->clone();
-				ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 ), mkExpr( arg3 ) );
+				ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ), mkExpr( arg3 )->acceptMutator( *visitor ) );
 				ret->set_env( expr->get_env() );
 				expr->set_env( nullptr );
@@ -197,17 +434,54 @@
 				unify( ret->get_arg2()->get_result(), ret->get_arg3()->get_result(), newEnv, needAssertions, haveAssertions, openVars, SymTab::Indexer(), commonType );
 				ret->set_result( commonType ? commonType : ret->get_arg2()->get_result()->clone() );
-				return ret->acceptMutator( *this );
+				return ret;
 			}
 			return expr;
 		}
 
-		Expression * GeneralizedLvalue::mutate( MemberExpr * memExpr ) {
-			Parent::mutate( memExpr );
+		Expression * GeneralizedLvalue::postmutate( MemberExpr * memExpr ) {
 			return applyTransformation( memExpr, memExpr->get_aggregate(), [=]( Expression * aggr ) { return new MemberExpr( memExpr->get_member(), aggr ); } );
 		}
 
-		Expression * GeneralizedLvalue::mutate( AddressExpr * addrExpr ) {
-			addrExpr = safe_dynamic_cast< AddressExpr * >( Parent::mutate( addrExpr ) );
+		Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
 			return applyTransformation( addrExpr, addrExpr->get_arg(), []( Expression * arg ) { return new AddressExpr( arg ); } );
+		}
+
+		Expression * CollapseAddrDeref::postmutate( AddressExpr * addrExpr ) {
+			Expression * arg = addrExpr->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( addrExpr->get_env() );
+					arg0 = nullptr;
+					addrExpr->set_env( nullptr );
+					delete addrExpr;
+					return ret;
+				}
+			}
+			return addrExpr;
+		}
+
+		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
