[Mono.Debugger.Soft] Implement IsGenericType/Method for protocol < 2.12
[mono.git] / mcs / mcs / nullable.cs
index ab8d55c5b2436d93a28b497f964ac3261478902a..75048365c4ed5d25514508dafba7bcdd1fafac50 100644 (file)
@@ -9,96 +9,80 @@
 //
 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
 // Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
 //
 
 using System;
-using System.Reflection;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
 using System.Reflection.Emit;
+#endif
        
 namespace Mono.CSharp.Nullable
 {
        public class NullableType : TypeExpr
        {
-               TypeExpr underlying;
+               readonly TypeSpec underlying;
 
-               public NullableType (TypeExpr underlying, Location l)
+               public NullableType (TypeSpec type, Location loc)
                {
-                       this.underlying = underlying;
-                       loc = l;
-
-                       eclass = ExprClass.Type;
+                       this.underlying = type;
+                       this.loc = loc;
                }
 
-               public NullableType (Type type, Location loc)
-                       : this (new TypeExpression (type, loc), loc)
-               { }
-
-               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
+               public override TypeSpec ResolveAsType (IMemberContext ec)
                {
-                       if (TypeManager.generic_nullable_type == null) {
-                               TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
-                                       "System", "Nullable`1", Kind.Struct, true);
-                       }
+                       eclass = ExprClass.Type;
 
-                       TypeArguments args = new TypeArguments (underlying);
-                       GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
-                       return ctype.ResolveAsTypeTerminal (ec, false);
-               }
+                       var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
+                       if (otype == null)
+                               return null;
 
-               public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
-               {
-                       return ResolveAsBaseTerminal (ec, silent);
-               }               
+                       TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
+                       GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
+                       
+                       type = ctype.ResolveAsType (ec);
+                       return type;
+               }
        }
 
-       public sealed class NullableInfo
+       static class NullableInfo
        {
-               public readonly Type Type;
-               public readonly Type UnderlyingType;
-               public MethodSpec HasValue;
-               public MethodSpec Value;
-               public MethodSpec GetValueOrDefault;
-               public MethodSpec Constructor;
-
-               public NullableInfo (Type type)
+               public static MethodSpec GetConstructor (TypeSpec nullableType)
                {
-                       Type = type;
-                       UnderlyingType = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0]);
-
-                       var has_value_pi = TypeManager.GetPredefinedProperty (type, "HasValue", Location.Null, Type.EmptyTypes);
-                       var value_pi = TypeManager.GetPredefinedProperty (type, "Value", Location.Null, Type.EmptyTypes);
-                       GetValueOrDefault = TypeManager.GetPredefinedMethod (type, "GetValueOrDefault", Location.Null, Type.EmptyTypes);
-
-                       HasValue = Import.CreateMethod (has_value_pi.MetaInfo.GetGetMethod (false));
-                       Value = Import.CreateMethod (value_pi.MetaInfo.GetGetMethod (false));
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
+               }
 
-                       // When compiling corlib
-                       if (TypeManager.IsBeingCompiled (type)) {
-                               TypeContainer tc = TypeManager.LookupGenericTypeContainer (type);
-                               
-                               // TODO: check for correct overload
-                               Constructor c = ((Constructor) tc.InstanceConstructors [0]);
+               public static MethodSpec GetHasValue (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-                               Constructor = Import.CreateMethod (TypeBuilder.GetConstructor (type, c.ConstructorBuilder));
-                               return;
-                       }
+               public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-#if MS_COMPATIBLE
-//                     if (TypeManager.IsBeingCompiled (UnderlyingType)) {
-//                             ConstructorInfo cinfo = TypeManager.DropGenericTypeArguments (type).GetConstructors ()[0];
-//                             Constructor = TypeBuilder.GetConstructor (type, cinfo);
-//                             return;
-//                     }
-#endif
+               public static MethodSpec GetValue (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-                       Constructor = Import.CreateMethod (type.GetConstructor (new Type[] { UnderlyingType }));
+               public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
+               {
+                       return ((InflatedTypeSpec) nullableType).TypeArguments[0];
                }
        }
 
-       public class Unwrap : Expression, IMemoryLocation, IAssignMethod
+       public class Unwrap : Expression, IMemoryLocation
        {
                Expression expr;
-               NullableInfo info;
 
                LocalTemporary temp;
                readonly bool useDefaultValue;
@@ -109,11 +93,15 @@ namespace Mono.CSharp.Nullable
                        this.loc = expr.Location;
                        this.useDefaultValue = useDefaultValue;
 
-                       info = new NullableInfo (expr.Type);
-                       type = info.UnderlyingType;
+                       type = NullableInfo.GetUnderlyingType (expr.Type);
                        eclass = expr.eclass;
                }
 
+               public override bool ContainsEmitWithAwait ()
+               {
+                       return expr.ContainsEmitWithAwait ();
+               }
+
                public static Expression Create (Expression expr)
                {
                        //
@@ -143,22 +131,31 @@ namespace Mono.CSharp.Nullable
 
                public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
                {
-                       return DoResolve (ec);
+                       expr = expr.DoResolveLValue (ec, right_side);
+                       return this;
                }
 
                public override void Emit (EmitContext ec)
                {
                        Store (ec);
+
+                       var call = new CallEmitter ();
+                       call.InstanceExpression = this;
+
                        if (useDefaultValue)
-                               Invocation.EmitCall (ec, false, this, info.GetValueOrDefault, null, loc);
+                               call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
                        else
-                               Invocation.EmitCall (ec, false, this, info.Value, null, loc);
+                               call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
                }
 
                public void EmitCheck (EmitContext ec)
                {
                        Store (ec);
-                       Invocation.EmitCall (ec, false, this, info.HasValue, null, loc);
+
+                       var call = new CallEmitter ();
+                       call.InstanceExpression = this;
+
+                       call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
                }
 
                public override bool Equals (object obj)
@@ -186,10 +183,10 @@ namespace Mono.CSharp.Nullable
 
                void Store (EmitContext ec)
                {
-                       if (expr is VariableReference)
+                       if (temp != null)
                                return;
 
-                       if (temp != null)
+                       if (expr is VariableReference)
                                return;
 
                        expr.Emit (ec);
@@ -209,19 +206,10 @@ namespace Mono.CSharp.Nullable
                        return expr.MakeExpression (ctx);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       storey.MutateConstructor (info.Constructor);
-                       storey.MutateGenericMethod (info.HasValue);
-                       storey.MutateGenericMethod (info.GetValueOrDefault);
-                       storey.MutateGenericMethod (info.Value);
-               }
-
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
                        IMemoryLocation ml = expr as VariableReference;
-                       if (ml != null) 
+                       if (ml != null)
                                ml.AddressOf (ec, mode);
                        else
                                LocalVariable.AddressOf (ec, mode);
@@ -233,74 +221,48 @@ namespace Mono.CSharp.Nullable
                LocalTemporary LocalVariable {
                        get {
                                if (temp == null)
-                                       temp = new LocalTemporary (info.Type);
+                                       temp = new LocalTemporary (expr.Type);
                                return temp;
                        }
                }
+       }
 
-               public void Emit (EmitContext ec, bool leave_copy)
-               {
-                       if (leave_copy)
-                               Load (ec);
-
-                       Emit (ec);
-               }
-
-               public void EmitAssign (EmitContext ec, Expression source,
-                                       bool leave_copy, bool prepare_for_load)
+       //
+       // Calls get_Value method on nullable expression
+       //
+       public class UnwrapCall : CompositeExpression
+       {
+               public UnwrapCall (Expression expr)
+                       : base (expr)
                {
-                       InternalWrap wrap = new InternalWrap (source, info, loc);
-                       ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
                }
 
-               protected class InternalWrap : Expression
+               protected override Expression DoResolve (ResolveContext rc)
                {
-                       public Expression expr;
-                       public NullableInfo info;
-
-                       public InternalWrap (Expression expr, NullableInfo info, Location loc)
-                       {
-                               this.expr = expr;
-                               this.info = info;
-                               this.loc = loc;
+                       base.DoResolve (rc);
 
-                               type = info.Type;
-                               eclass = ExprClass.Value;
-                       }
+                       if (type != null)
+                               type = NullableInfo.GetUnderlyingType (type);
 
-                       public override Expression CreateExpressionTree (ResolveContext ec)
-                       {
-                               throw new NotSupportedException ("ET");
-                       }
-
-                       protected override Expression DoResolve (ResolveContext ec)
-                       {
-                               return this;
-                       }
+                       return this;
+               }
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               expr.Emit (ec);
-                               ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) info.Constructor.MetaInfo);
-                       }
+               public override void Emit (EmitContext ec)
+               {
+                       var call = new CallEmitter ();
+                       call.InstanceExpression = Child;
+                       call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
                }
        }
 
        public class Wrap : TypeCast
        {
-               readonly NullableInfo info;
-
-               protected Wrap (Expression expr, Type type)
+               private Wrap (Expression expr, TypeSpec type)
                        : base (expr, type)
                {
-                       info = new NullableInfo (type);
                        eclass = ExprClass.Value;
                }
 
-               public Expression Child {
-                       get { return child; }
-               }
-
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        TypeCast child_cast = child as TypeCast;
@@ -312,13 +274,13 @@ namespace Mono.CSharp.Nullable
                        return base.CreateExpressionTree (ec);
                }
 
-               public static Expression Create (Expression expr, Type type)
+               public static Expression Create (Expression expr, TypeSpec type)
                {
                        //
                        // Avoid unwraping and wraping of the same type
                        //
                        Unwrap unwrap = expr as Unwrap;
-                       if (unwrap != null && TypeManager.IsEqual (expr.Type, TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0])))
+                       if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
                                return unwrap.Original;
                
                        return new Wrap (expr, type);
@@ -327,7 +289,7 @@ namespace Mono.CSharp.Nullable
                public override void Emit (EmitContext ec)
                {
                        child.Emit (ec);
-                       ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) info.Constructor.MetaInfo);
+                       ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
                }
        }
 
@@ -336,18 +298,18 @@ namespace Mono.CSharp.Nullable
        //
        public class LiftedNull : NullConstant, IMemoryLocation
        {
-               private LiftedNull (Type nullable_type, Location loc)
+               private LiftedNull (TypeSpec nullable_type, Location loc)
                        : base (nullable_type, loc)
                {
                        eclass = ExprClass.Value;
                }
 
-               public static Constant Create (Type nullable, Location loc)
+               public static Constant Create (TypeSpec nullable, Location loc)
                {
                        return new LiftedNull (nullable, loc);
                }
 
-               public static Expression CreateFromExpression (ResolveContext ec, Expression e)
+               public static Constant CreateFromExpression (ResolveContext ec, Expression e)
                {
                        ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
                                TypeManager.CSharpName (e.Type));
@@ -361,8 +323,9 @@ namespace Mono.CSharp.Nullable
                        LocalTemporary value_target = new LocalTemporary (type);
 
                        value_target.AddressOf (ec, AddressOp.Store);
-                       ec.ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
                        value_target.Emit (ec);
+                       value_target.Release (ec);
                }
 
                public void AddressOf (EmitContext ec, AddressOp Mode)
@@ -370,7 +333,7 @@ namespace Mono.CSharp.Nullable
                        LocalTemporary value_target = new LocalTemporary (type);
                                
                        value_target.AddressOf (ec, AddressOp.Store);
-                       ec.ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
                        ((IMemoryLocation) value_target).AddressOf (ec, Mode);
                }
        }
@@ -383,7 +346,7 @@ namespace Mono.CSharp.Nullable
                Expression expr, null_value;
                Unwrap unwrap;
 
-               public Lifted (Expression expr, Unwrap unwrap, Type type)
+               public Lifted (Expression expr, Unwrap unwrap, TypeSpec type)
                {
                        this.expr = expr;
                        this.unwrap = unwrap;
@@ -391,10 +354,15 @@ namespace Mono.CSharp.Nullable
                        this.type = type;
                }
 
-               public Lifted (Expression expr, Expression unwrap, Type type)
+               public Lifted (Expression expr, Expression unwrap, TypeSpec type)
                        : this (expr, unwrap as Unwrap, type)
                {
                }
+
+               public override bool ContainsEmitWithAwait ()
+               {
+                       return unwrap.ContainsEmitWithAwait ();
+               }
                
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
@@ -408,7 +376,7 @@ namespace Mono.CSharp.Nullable
                        //
                        if (unwrap == null) {
                                // S -> T? is wrap only
-                               if (TypeManager.IsNullableType (type))
+                               if (type.IsNullableType)
                                        return Wrap.Create (expr, type);
 
                                // S -> T can be simplified
@@ -416,11 +384,13 @@ namespace Mono.CSharp.Nullable
                        }
 
                        // Wrap target for T?
-                       if (TypeManager.IsNullableType (type)) {
+                       if (type.IsNullableType) {
                                expr = Wrap.Create (expr, type);
                                if (expr == null)
                                        return null;
 
+                               null_value = LiftedNull.Create (type, loc);
+                       } else if (TypeSpec.IsValueType (type)) {
                                null_value = LiftedNull.Create (type, loc);
                        } else {
                                null_value = new NullConstant (type, loc);
@@ -432,20 +402,19 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
                        expr.Emit (ec);
 
-                       ig.Emit (OpCodes.Br, end_label);
-                       ig.MarkLabel (is_null_label);
+                       ec.Emit (OpCodes.Br, end_label);
+                       ec.MarkLabel (is_null_label);
 
                        null_value.Emit (ec);
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
@@ -459,8 +428,8 @@ namespace Mono.CSharp.Nullable
                Unwrap unwrap;
                Expression user_operator;
 
-               public LiftedUnaryOperator (Unary.Operator op, Expression expr)
-                       : base (op, expr)
+               public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
+                       : base (op, expr, loc)
                {
                }
 
@@ -504,44 +473,40 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
-
-                       NullableInfo ni = new NullableInfo (type);
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
                        if (user_operator != null) {
                                user_operator.Emit (ec);
                        } else {
-                               EmitOperator (ec, ni.UnderlyingType);
+                               EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
                        }
 
-                       ig.Emit (OpCodes.Newobj, (ConstructorInfo) ni.Constructor.MetaInfo);
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+                       ec.Emit (OpCodes.Br_S, end_label);
 
-                       ig.MarkLabel (is_null_label);
+                       ec.MarkLabel (is_null_label);
                        LiftedNull.Create (type, loc).Emit (ec);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                Expression LiftExpression (ResolveContext ec, Expression expr)
                {
-                       TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
-                       lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
-                       if (lifted_type == null)
+                       var lifted_type = new NullableType (expr.Type, expr.Location);
+                       if (lifted_type.ResolveAsType (ec) == null)
                                return null;
 
                        expr.Type = lifted_type.Type;
                        return expr;
                }
 
-               protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
+               protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
                {
-                       expr = base.ResolveEnumOperator (ec, expr);
+                       expr = base.ResolveEnumOperator (ec, expr, predefined);
                        if (expr == null)
                                return null;
 
@@ -570,16 +535,33 @@ namespace Mono.CSharp.Nullable
        public class LiftedBinaryOperator : Binary
        {
                Unwrap left_unwrap, right_unwrap;
-               bool left_null_lifted, right_null_lifted;
                Expression left_orig, right_orig;
                Expression user_operator;
                MethodSpec wrap_ctor;
 
-               public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
-                                            Location loc)
-                       : base (op, left, right)
+               public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right, Location loc)
+                       : base (op, left, right, loc)
                {
-                       this.loc = loc;
+               }
+
+               bool IsBitwiseBoolean {
+                       get {
+                               return (Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) &&
+                               ((left_unwrap != null && left_unwrap.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
+                                (right_unwrap != null && right_unwrap.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
+                       }
+               }
+
+               bool IsLeftNullLifted {
+                       get {
+                               return (state & State.LeftNullLifted) != 0;
+                       }
+               }
+
+               bool IsRightNullLifted {
+                       get {
+                               return (state & State.RightNullLifted) != 0;
+                       }
                }
 
                public override Expression CreateExpressionTree (ResolveContext ec)
@@ -595,17 +577,17 @@ namespace Mono.CSharp.Nullable
                // with the null literal *outside* of a generics context and
                // inlines that as true or false.
                //
-               Expression CreateNullConstant (ResolveContext ec, Expression expr)
+               Constant CreateNullConstant (ResolveContext ec, Expression expr)
                {
                        // FIXME: Handle side effect constants
-                       Constant c = new BoolConstant (Oper == Operator.Inequality, loc).Resolve (ec);
+                       Constant c = new BoolConstant (ec.BuiltinTypes, Oper == Operator.Inequality, loc);
 
                        if ((Oper & Operator.EqualityMask) != 0) {
                                ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
-                                       TypeManager.CSharpName (expr.Type), c.AsString ());
+                                       TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
                        } else {
                                ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
-                                       TypeManager.CSharpName (expr.Type), c.AsString ());
+                                       TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
                        }
 
                        return ReducedExpression.Create (c, this);
@@ -620,14 +602,14 @@ namespace Mono.CSharp.Nullable
 
                        bool use_default_call = (Oper & (Operator.BitwiseMask | Operator.EqualityMask)) != 0;
                        left_orig = left;
-                       if (TypeManager.IsNullableType (left.Type)) {
+                       if (left.Type.IsNullableType) {
                                left = left_unwrap = Unwrap.Create (left, use_default_call);
                                if (left == null)
                                        return null;
                        }
 
                        right_orig = right;
-                       if (TypeManager.IsNullableType (right.Type)) {
+                       if (right.Type.IsNullableType) {
                                right = right_unwrap = Unwrap.Create (right, use_default_call);
                                if (right == null)
                                        return null;
@@ -638,16 +620,20 @@ namespace Mono.CSharp.Nullable
                        // Arguments can be lifted for equal operators when the return type is bool and both
                        // arguments are of same type
                        //      
-                       if (left_orig.IsNull) {
+                       if (left_orig is NullLiteral) {
                                left = right;
-                               left_null_lifted = true;
-                               type = TypeManager.bool_type;
+                               state |= State.LeftNullLifted;
+                               type = ec.BuiltinTypes.Bool;
                        }
 
                        if (right_orig.IsNull) {
-                               right = left;
-                               right_null_lifted = true;
-                               type = TypeManager.bool_type;
+                               if ((Oper & Operator.ShiftMask) != 0)
+                                       right = new EmptyExpression (ec.BuiltinTypes.Int);
+                               else
+                                       right = left;
+
+                               state |= State.RightNullLifted;
+                               type = ec.BuiltinTypes.Bool;
                        }
 
                        eclass = ExprClass.Value;
@@ -656,37 +642,61 @@ namespace Mono.CSharp.Nullable
 
                void EmitBitwiseBoolean (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
+                       Label load_left = ec.DefineLabel ();
+                       Label load_right = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
-                       Label load_left = ig.DefineLabel ();
-                       Label load_right = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       // null & value, null | value
+                       if (left_unwrap == null) {
+                               left_unwrap = right_unwrap;
+                               right_unwrap = null;
+                               right = left;
+                       }
 
                        left_unwrap.Emit (ec);
-                       ig.Emit (OpCodes.Brtrue_S, load_right);
+                       ec.Emit (OpCodes.Brtrue, load_right);
 
-                       right_unwrap.Emit (ec);
-                       ig.Emit (OpCodes.Brtrue_S, load_left);
+                       // value & null, value | null
+                       if (right_unwrap != null) {
+                               right_unwrap.Emit (ec);
+                               ec.Emit (OpCodes.Brtrue_S, load_left);
+                       }
 
                        left_unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse_S, load_right);
+                       ec.Emit (OpCodes.Brfalse_S, load_right);
 
                        // load left
-                       ig.MarkLabel (load_left);
+                       ec.MarkLabel (load_left);
 
                        if (Oper == Operator.BitwiseAnd) {
                                left_unwrap.Load (ec);
                        } else {
-                               right_unwrap.Load (ec);
-                               right_unwrap = left_unwrap;
+                               if (right_unwrap == null) {
+                                       right.Emit (ec);
+                                       if (right is EmptyConstantCast || right is EmptyCast)
+                                               ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+                               } else {
+                                       right_unwrap.Load (ec);
+                                       right_unwrap = left_unwrap;
+                               }
                        }
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
 
                        // load right
-                       ig.MarkLabel (load_right);
-                       right_unwrap.Load (ec);
+                       ec.MarkLabel (load_right);
+                       if (right_unwrap == null) {
+                               if (Oper == Operator.BitwiseAnd) {
+                                       right.Emit (ec);
+                                       if (right is EmptyConstantCast || right is EmptyCast)
+                                               ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+                               } else {
+                                       left_unwrap.Load (ec);
+                               }
+                       } else {
+                               right_unwrap.Load (ec);
+                       }
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                //
@@ -694,40 +704,43 @@ namespace Mono.CSharp.Nullable
                //
                void EmitEquality (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        //
                        // Either left or right is null
                        //
-                       if (left_unwrap != null && (right_null_lifted || right.IsNull)) {
+                       if (left_unwrap != null && (IsRightNullLifted || right.IsNull)) {
                                left_unwrap.EmitCheck (ec);
                                if (Oper == Binary.Operator.Equality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.EmitInt (0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                                return;
                        }
 
-                       if (right_unwrap != null && (left_null_lifted || left.IsNull)) {
+                       if (right_unwrap != null && (IsLeftNullLifted || left.IsNull)) {
                                right_unwrap.EmitCheck (ec);
                                if (Oper == Binary.Operator.Equality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.EmitInt (0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                                return;
                        }
 
-                       Label dissimilar_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label dissimilar_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (user_operator != null) {
                                user_operator.Emit (ec);
-                               ig.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
+                               ec.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
                        } else {
+                               if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
+                                       left = left.EmitToField (ec);
+                                       right = right.EmitToField (ec);
+                               }
+
                                left.Emit (ec);
                                right.Emit (ec);
 
-                               ig.Emit (OpCodes.Bne_Un_S, dissimilar_label);
+                               ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
                        }
 
                        if (left_unwrap != null)
@@ -738,31 +751,31 @@ namespace Mono.CSharp.Nullable
 
                        if (left_unwrap != null && right_unwrap != null) {
                                if (Oper == Operator.Inequality)
-                                       ig.Emit (OpCodes.Xor);
+                                       ec.Emit (OpCodes.Xor);
                                else
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.Emit (OpCodes.Ceq);
                        } else {
                                if (Oper == Operator.Inequality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.EmitInt (0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                        }
 
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
 
-                       ig.MarkLabel (dissimilar_label);
+                       ec.MarkLabel (dissimilar_label);
                        if (Oper == Operator.Inequality)
-                               ig.Emit (OpCodes.Ldc_I4_1);
+                               ec.EmitInt (1);
                        else
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.EmitInt (0);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
                
                public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
                {
                        Emit (ec);
-                       ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+                       ec.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
                }                       
 
                public override void Emit (EmitContext ec)
@@ -783,14 +796,12 @@ namespace Mono.CSharp.Nullable
                                return;
                        }
 
-                       ILGenerator ig = ec.ig;
-
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (left_unwrap != null) {
                                left_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
                        //
@@ -798,90 +809,97 @@ namespace Mono.CSharp.Nullable
                        //
                        if (right_unwrap != null && !left.Equals (right)) {
                                right_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
                        EmitOperator (ec, left.Type);
 
                        if (wrap_ctor != null)
-                               ig.Emit (OpCodes.Newobj, (ConstructorInfo) wrap_ctor.MetaInfo);
+                               ec.Emit (OpCodes.Newobj, wrap_ctor);
 
-                       ig.Emit (OpCodes.Br_S, end_label);
-                       ig.MarkLabel (is_null_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
+                       ec.MarkLabel (is_null_label);
 
                        if ((Oper & Operator.ComparisonMask) != 0) {
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.EmitInt (0);
                        } else {
                                LiftedNull.Create (type, loc).Emit (ec);
                        }
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
-               protected override void EmitOperator (EmitContext ec, Type l)
+               protected override void EmitOperator (EmitContext ec, TypeSpec l)
                {
                        if (user_operator != null) {
                                user_operator.Emit (ec);
                                return;
                        }
 
-                       if (TypeManager.IsNullableType (l))
-                               l = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (l) [0]);
-
-                       base.EmitOperator (ec, l);
-               }
+                       if (left.Type.IsNullableType) {
+                               l = NullableInfo.GetUnderlyingType (left.Type);
+                               left = EmptyCast.Create (left, l);
+                       }
 
-               bool IsBitwiseBoolean {
-                       get {
-                               return (Oper & Operator.BitwiseMask) != 0 && left_unwrap != null && right_unwrap != null &&
-                               left_unwrap.Type == TypeManager.bool_type && right_unwrap.Type == TypeManager.bool_type;
+                       if (right.Type.IsNullableType) {
+                               right = EmptyCast.Create (right, NullableInfo.GetUnderlyingType (right.Type));
                        }
+
+                       base.EmitOperator (ec, l);
                }
 
                Expression LiftResult (ResolveContext ec, Expression res_expr)
                {
-                       TypeExpr lifted_type;
+                       TypeSpec lifted_type;
 
                        //
                        // Avoid double conversion
                        //
-                       if (left_unwrap == null || left_null_lifted || !TypeManager.IsEqual (left_unwrap.Type, left.Type) || (left_unwrap != null && right_null_lifted)) {
-                               lifted_type = new NullableType (left.Type, loc);
-                               lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
+                       if (left_unwrap == null || IsLeftNullLifted || left_unwrap.Type != left.Type || (left_unwrap != null && IsRightNullLifted)) {
+                               lifted_type = new NullableType (left.Type, loc).ResolveAsType (ec);
                                if (lifted_type == null)
                                        return null;
 
                                if (left is UserCast || left is TypeCast)
-                                       left.Type = lifted_type.Type;
+                                       left.Type = lifted_type;
                                else
-                                       left = EmptyCast.Create (left, lifted_type.Type);
+                                       left = EmptyCast.Create (left, lifted_type);
                        }
 
-                       if (right_unwrap == null || right_null_lifted || !TypeManager.IsEqual (right_unwrap.Type, right.Type) || (right_unwrap != null && left_null_lifted)) {
-                               lifted_type = new NullableType (right.Type, loc);
-                               lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
+                       if (left != right && (right_unwrap == null || IsRightNullLifted || right_unwrap.Type != right.Type || (right_unwrap != null && IsLeftNullLifted))) {
+                               lifted_type = new NullableType (right.Type, loc).ResolveAsType (ec);
                                if (lifted_type == null)
                                        return null;
 
-                               if (right is UserCast || right is TypeCast)
-                                       right.Type = lifted_type.Type;
+                               var r = right;
+                               if (r is ReducedExpression)
+                                       r = ((ReducedExpression) r).OriginalExpression;
+
+                               if (r is UserCast || r is TypeCast)
+                                       r.Type = lifted_type;
                                else
-                                       right = EmptyCast.Create (right, lifted_type.Type);
+                                       right = EmptyCast.Create (right, lifted_type);
                        }
 
                        if ((Oper & Operator.ComparisonMask) == 0) {
-                               lifted_type = new NullableType (res_expr.Type, loc);
-                               lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
+                               lifted_type = new NullableType (res_expr.Type, loc).ResolveAsType (ec);
                                if (lifted_type == null)
                                        return null;
 
-                               wrap_ctor = new NullableInfo (lifted_type.Type).Constructor;
-                               type = res_expr.Type = lifted_type.Type;
+                               wrap_ctor = NullableInfo.GetConstructor (lifted_type);
+                               type = res_expr.Type = lifted_type;
                        }
 
-                       if (left_null_lifted) {
+                       if (IsLeftNullLifted) {
                                left = LiftedNull.Create (right.Type, left.Location);
 
+                               //
+                               // Special case for bool?, the result depends on both null right side and left side value
+                               //
+                               if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuiltinType == BuiltinTypeSpec.Type.Bool) {
+                                       return res_expr;
+                               }
+
                                if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
                                        return LiftedNull.CreateFromExpression (ec, res_expr);
 
@@ -889,12 +907,19 @@ namespace Mono.CSharp.Nullable
                                // Value types and null comparison
                                //
                                if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
-                                       return CreateNullConstant (ec, right_orig).Resolve (ec);
+                                       return CreateNullConstant (ec, right_orig);
                        }
 
-                       if (right_null_lifted) {
+                       if (IsRightNullLifted) {
                                right = LiftedNull.Create (left.Type, right.Location);
 
+                               //
+                               // Special case for bool?, the result depends on both null right side and left side value
+                               //
+                               if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuiltinType == BuiltinTypeSpec.Type.Bool) {
+                                       return res_expr;
+                               }
+
                                if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
                                        return LiftedNull.CreateFromExpression (ec, res_expr);
 
@@ -908,7 +933,7 @@ namespace Mono.CSharp.Nullable
                        return res_expr;
                }
 
-               protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, Type enum_type)
+               protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
                {
                        Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
 
@@ -923,19 +948,44 @@ namespace Mono.CSharp.Nullable
                        // (in unlifted or lifted form) exists for the operation.
                        //
                        if (e == null && (Oper & Operator.EqualityMask) != 0) {
-                               if ((left_null_lifted && right_unwrap != null) || (right_null_lifted && left_unwrap != null))
+                               if ((IsLeftNullLifted && right_unwrap != null) || (IsRightNullLifted && left_unwrap != null))
                                        return LiftResult (ec, this);
                        }
 
                        return e;
                }
 
-               protected override Expression ResolveUserOperator (ResolveContext ec, Type l, Type r)
+               protected override Expression ResolveUserOperator (ResolveContext ec, Expression left, Expression right)
                {
-                       Expression expr = base.ResolveUserOperator (ec, l, r);
+                       //
+                       // Try original types first for exact match without unwrapping
+                       //
+                       Expression expr = base.ResolveUserOperator (ec, left_orig, right_orig);
+                       if (expr != null)
+                               return expr;
+
+                       State orig_state = state;
+
+                       //
+                       // One side is a nullable type, try to match underlying types
+                       //
+                       if (left_unwrap != null || right_unwrap != null || (state & (State.RightNullLifted | State.LeftNullLifted)) != 0) {
+                               expr = base.ResolveUserOperator (ec, left, right);
+                       }
+
                        if (expr == null)
                                return null;
 
+                       //
+                       // Lift the result in the case it can be null and predefined or user operator
+                       // result type is of a value type
+                       //
+                       if (!TypeSpec.IsValueType (expr.Type))
+                               return null;
+
+                       if (state != orig_state)
+                               return expr;
+
                        expr = LiftResult (ec, expr);
                        if (expr is Constant)
                                return expr;
@@ -957,10 +1007,22 @@ namespace Mono.CSharp.Nullable
                        this.right = right;
                        this.loc = loc;
                }
+
+               public Expression LeftExpression {
+                       get {
+                               return left;
+                       }
+               }
+
+               public Expression RightExpression {
+                       get {
+                               return right;
+                       }
+               }
                
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
-                       if (left.Type == TypeManager.null_type)
+                       if (left is NullLiteral)
                                ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
 
                        UserCast uc = left as UserCast;
@@ -989,31 +1051,58 @@ namespace Mono.CSharp.Nullable
                        if (left.eclass == ExprClass.MethodGroup)
                                return null;
 
-                       Type ltype = left.Type;
+                       TypeSpec ltype = left.Type;
 
                        //
                        // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
                        // the result is underlying type of left
                        //
-                       if (TypeManager.IsNullableType (ltype)) {
+                       if (ltype.IsNullableType) {
                                unwrap = Unwrap.Create (left, false);
                                if (unwrap == null)
                                        return null;
 
+                               //
+                               // Reduce (left ?? null) to left
+                               //
+                               if (right.IsNull)
+                                       return ReducedExpression.Create (left, this);
+
                                if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
                                        left = unwrap;
-                                       type = left.Type;
-                                       right = Convert.ImplicitConversion (ec, right, type, loc);
+                                       ltype = left.Type;
+
+                                       //
+                                       // If right is a dynamic expression, the result type is dynamic
+                                       //
+                                       if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+                                               type = right.Type;
+
+                                               // Need to box underlying value type
+                                               left = Convert.ImplicitBoxingConversion (left, ltype, type);
+                                               return this;
+                                       }
+
+                                       right = Convert.ImplicitConversion (ec, right, ltype, loc);
+                                       type = ltype;
                                        return this;
                                }
-                       } else if (TypeManager.IsReferenceType (ltype)) {
+                       } else if (TypeSpec.IsReferenceType (ltype)) {
                                if (Convert.ImplicitConversionExists (ec, right, ltype)) {
                                        //
-                                       // Reduce (constant ?? expr) to constant
+                                       // If right is a dynamic expression, the result type is dynamic
+                                       //
+                                       if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+                                               type = right.Type;
+                                               return this;
+                                       }
+
+                                       //
+                                       // Reduce ("foo" ?? expr) to expression
                                        //
                                        Constant lc = left as Constant;
                                        if (lc != null && !lc.IsDefaultValue)
-                                               return new SideEffectConstant (lc, right, loc).Resolve (ec);
+                                               return ReducedExpression.Create (lc, this);
 
                                        //
                                        // Reduce (left ?? null) to left OR (null-constant ?? right) to right
@@ -1022,14 +1111,22 @@ namespace Mono.CSharp.Nullable
                                                return ReducedExpression.Create (lc != null ? right : left, this);
 
                                        right = Convert.ImplicitConversion (ec, right, ltype, loc);
-                                       type = left.Type;
+                                       type = ltype;
+                                       return this;
+                               }
+
+                               //
+                               // Special case null ?? null
+                               //
+                               if (ltype == right.Type) {
+                                       type = ltype;
                                        return this;
                                }
                        } else {
                                return null;
                        }
 
-                       Type rtype = right.Type;
+                       TypeSpec rtype = right.Type;
                        if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
                                return null;
 
@@ -1037,13 +1134,21 @@ namespace Mono.CSharp.Nullable
                        // Reduce (null ?? right) to right
                        //
                        if (left.IsNull)
-                               return ReducedExpression.Create (right, this);
+                               return ReducedExpression.Create (right, this).Resolve (ec);
 
                        left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
                        type = rtype;
                        return this;
                }
 
+               public override bool ContainsEmitWithAwait ()
+               {
+                       if (unwrap != null)
+                               return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
+
+                       return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
+               }
+
                protected override Expression DoResolve (ResolveContext ec)
                {
                        left = left.Resolve (ec);
@@ -1065,42 +1170,37 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label end_label = ig.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (unwrap != null) {
-                               Label is_null_label = ig.DefineLabel ();
+                               Label is_null_label = ec.DefineLabel ();
 
                                unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
 
                                left.Emit (ec);
-                               ig.Emit (OpCodes.Br, end_label);
+                               ec.Emit (OpCodes.Br, end_label);
 
-                               ig.MarkLabel (is_null_label);
+                               ec.MarkLabel (is_null_label);
                                right.Emit (ec);
 
-                               ig.MarkLabel (end_label);
+                               ec.MarkLabel (end_label);
                                return;
                        }
 
                        left.Emit (ec);
+                       ec.Emit (OpCodes.Dup);
 
-                       ig.Emit (OpCodes.Dup);
-                       ig.Emit (OpCodes.Brtrue, end_label);
+                       // Only to make verifier happy
+                       if (left.Type.IsGenericParameter)
+                               ec.Emit (OpCodes.Box, left.Type);
 
-                       ig.Emit (OpCodes.Pop);
-                       right.Emit (ec);
+                       ec.Emit (OpCodes.Brtrue, end_label);
 
-                       ig.MarkLabel (end_label);
-               }
+                       ec.Emit (OpCodes.Pop);
+                       right.Emit (ec);
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       left.MutateHoistedGenericType (storey);
-                       right.MutateHoistedGenericType (storey);
-                       type = storey.MutateType (type);
+                       ec.MarkLabel (end_label);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -1110,78 +1210,65 @@ namespace Mono.CSharp.Nullable
                        target.left = left.Clone (clonectx);
                        target.right = right.Clone (clonectx);
                }
-       }
-
-       public class LiftedUnaryMutator : ExpressionStatement
-       {
-               public readonly UnaryMutator.Mode Mode;
-               Expression expr;
-               UnaryMutator underlying;
-               Unwrap unwrap;
-
-               public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
+               
+               public override object Accept (StructuralVisitor visitor)
                {
-                       this.expr = expr;
-                       this.Mode = mode;
-                       this.loc = loc;
+                       return visitor.Visit (this);
                }
+       }
 
-               public override Expression CreateExpressionTree (ResolveContext ec)
+       class LiftedUnaryMutator : UnaryMutator
+       {
+               public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
+                       : base (mode, expr, loc)
                {
-                       return new SimpleAssign (this, this).CreateExpressionTree (ec);
                }
 
                protected override Expression DoResolve (ResolveContext ec)
                {
-                       expr = expr.Resolve (ec);
-                       if (expr == null)
-                               return null;
+                       var orig_expr = expr;
 
-                       unwrap = Unwrap.Create (expr, false);
-                       if (unwrap == null)
-                               return null;
+                       expr = Unwrap.Create (expr);
 
-                       underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap).Resolve (ec);
-                       if (underlying == null)
-                               return null;
+                       var res = base.DoResolveOperation (ec);
 
-
-                       eclass = ExprClass.Value;
+                       expr = orig_expr;
                        type = expr.Type;
-                       return this;
+
+                       return res;
                }
 
-               void DoEmit (EmitContext ec, bool is_expr)
+               protected override void EmitOperation (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
-                       unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                       LocalTemporary lt = new LocalTemporary (type);
 
-                       if (is_expr) {
-                               underlying.Emit (ec);
-                               ig.Emit (OpCodes.Br_S, end_label);
-                       } else {
-                               underlying.EmitStatement (ec);
-                       }
+                       // Value is on the stack
+                       lt.Store (ec);
 
-                       ig.MarkLabel (is_null_label);
-                       if (is_expr)
-                               LiftedNull.Create (type, loc).Emit (ec);
+                       var call = new CallEmitter ();
+                       call.InstanceExpression = lt;
+                       call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
 
-                       ig.MarkLabel (end_label);
-               }
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
-               public override void Emit (EmitContext ec)
-               {
-                       DoEmit (ec, true);
-               }
+                       call = new CallEmitter ();
+                       call.InstanceExpression = lt;
+                       call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
 
-               public override void EmitStatement (EmitContext ec)
-               {
-                       DoEmit (ec, false);
+                       lt.Release (ec);
+
+                       base.EmitOperation (ec);
+
+                       ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+                       ec.Emit (OpCodes.Br_S, end_label);
+
+                       ec.MarkLabel (is_null_label);
+                       LiftedNull.Create (type, loc).Emit (ec);
+
+                       ec.MarkLabel (end_label);
                }
        }
 }