Merge pull request #2237 from xmcclure/container-owner
[mono.git] / mcs / mcs / nullable.cs
1 //
2 // nullable.cs: Nullable types support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using SLE = System.Linq.Expressions;
17
18 #if STATIC
19 using IKVM.Reflection.Emit;
20 #else
21 using System.Reflection.Emit;
22 #endif
23         
24 namespace Mono.CSharp.Nullable
25 {
26         public class NullableType : TypeExpr
27         {
28                 readonly TypeSpec underlying;
29
30                 public NullableType (TypeSpec type, Location loc)
31                 {
32                         this.underlying = type;
33                         this.loc = loc;
34                 }
35
36                 public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments = false)
37                 {
38                         eclass = ExprClass.Type;
39
40                         var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
41                         if (otype == null)
42                                 return null;
43
44                         TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
45                         GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
46                         
47                         type = ctype.ResolveAsType (ec);
48                         return type;
49                 }
50         }
51
52         static class NullableInfo
53         {
54                 public static MethodSpec GetConstructor (TypeSpec nullableType)
55                 {
56                         return (MethodSpec) MemberCache.FindMember (nullableType,
57                                 MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
58                 }
59
60                 public static MethodSpec GetHasValue (TypeSpec nullableType)
61                 {
62                         return (MethodSpec) MemberCache.FindMember (nullableType,
63                                 MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
64                 }
65
66                 public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
67                 {
68                         return (MethodSpec) MemberCache.FindMember (nullableType,
69                                 MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
70                 }
71
72                 //
73                 // Don't use unless really required for correctness, see Unwrap::Emit
74                 //
75                 public static MethodSpec GetValue (TypeSpec nullableType)
76                 {
77                         return (MethodSpec) MemberCache.FindMember (nullableType,
78                                 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
79                 }
80
81                 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
82                 {
83                         return ((InflatedTypeSpec) nullableType).TypeArguments[0];
84                 }
85
86                 public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum)
87                 {
88                         return MakeType (module, EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)));
89                 }
90
91                 public static TypeSpec MakeType (ModuleContainer module, TypeSpec underlyingType)
92                 {
93                         return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module,
94                                 new[] { underlyingType });
95
96                 }
97         }
98
99         public class Unwrap : Expression, IMemoryLocation
100         {
101                 Expression expr;
102
103                 LocalTemporary temp;
104                 Expression temp_field;
105                 readonly bool useDefaultValue;
106
107                 public Unwrap (Expression expr, bool useDefaultValue = true)
108                 {
109                         this.expr = expr;
110                         this.loc = expr.Location;
111                         this.useDefaultValue = useDefaultValue;
112
113                         type = NullableInfo.GetUnderlyingType (expr.Type);
114                         eclass = expr.eclass;
115                 }
116
117                 public override bool ContainsEmitWithAwait ()
118                 {
119                         return expr.ContainsEmitWithAwait ();
120                 }
121
122                 // TODO: REMOVE
123                 public static Expression Create (Expression expr)
124                 {
125                         //
126                         // Avoid unwraping and wraping of same type
127                         //
128                         Wrap wrap = expr as Wrap;
129                         if (wrap != null)
130                                 return wrap.Child;
131
132                         return Create (expr, false);
133                 }
134
135                 public static Expression CreateUnwrapped (Expression expr)
136                 {
137                         //
138                         // Avoid unwraping and wraping of same type
139                         //
140                         Wrap wrap = expr as Wrap;
141                         if (wrap != null)
142                                 return wrap.Child;
143
144                         return Create (expr, true);
145                 }
146
147                 public static Unwrap Create (Expression expr, bool useDefaultValue)
148                 {
149                         return new Unwrap (expr, useDefaultValue);
150                 }
151                 
152                 public override Expression CreateExpressionTree (ResolveContext ec)
153                 {
154                         return expr.CreateExpressionTree (ec);
155                 }
156
157                 protected override Expression DoResolve (ResolveContext ec)
158                 {
159                         return this;
160                 }
161
162                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
163                 {
164                         expr = expr.DoResolveLValue (ec, right_side);
165                         return this;
166                 }
167
168                 public override void Emit (EmitContext ec)
169                 {
170                         Store (ec);
171
172                         var call = new CallEmitter ();
173                         call.InstanceExpression = this;
174
175                         //
176                         // Using GetGetValueOrDefault is prefered because JIT can possibly
177                         // inline it whereas Value property contains a throw which is very
178                         // unlikely to be inlined
179                         //
180                         if (useDefaultValue)
181                                 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
182                         else
183                                 call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
184                 }
185
186                 public void EmitCheck (EmitContext ec)
187                 {
188                         Store (ec);
189
190                         var call = new CallEmitter ();
191                         call.InstanceExpression = this;
192
193                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
194                 }
195
196                 public override void EmitSideEffect (EmitContext ec)
197                 {
198                         expr.EmitSideEffect (ec);
199                 }
200
201                 public override Expression EmitToField (EmitContext ec)
202                 {
203                         if (temp_field == null)
204                                 temp_field = this.expr.EmitToField (ec);
205                         
206                         return this;
207                 }
208
209                 public override bool Equals (object obj)
210                 {
211                         Unwrap uw = obj as Unwrap;
212                         return uw != null && expr.Equals (uw.expr);
213                 }
214
215                 public override void FlowAnalysis (FlowAnalysisContext fc)
216                 {
217                         expr.FlowAnalysis (fc);
218                 }
219
220                 public Expression Original {
221                         get {
222                                 return expr;
223                         }
224                 }
225                 
226                 public override int GetHashCode ()
227                 {
228                         return expr.GetHashCode ();
229                 }
230
231                 public override bool IsNull {
232                         get {
233                                 return expr.IsNull;
234                         }
235                 }
236
237                 public void Store (EmitContext ec)
238                 {
239                         if (temp != null || temp_field != null)
240                                 return;
241
242                         if (expr is VariableReference)
243                                 return;
244
245                         expr.Emit (ec);
246                         LocalVariable.Store (ec);
247                 }
248
249                 public void Load (EmitContext ec)
250                 {
251                         if (temp_field != null)
252                                 temp_field.Emit (ec);
253                         else if (expr is VariableReference)
254                                 expr.Emit (ec);
255                         else
256                                 LocalVariable.Emit (ec);
257                 }
258
259                 public override SLE.Expression MakeExpression (BuilderContext ctx)
260                 {
261                         return expr.MakeExpression (ctx);
262                 }
263
264                 public void AddressOf (EmitContext ec, AddressOp mode)
265                 {
266                         IMemoryLocation ml;
267
268                         if (temp_field != null) {
269                                 ml = temp_field as IMemoryLocation;
270                                 if (ml == null) {
271                                         var lt = new LocalTemporary (temp_field.Type);
272                                         temp_field.Emit (ec);
273                                         lt.Store (ec);
274                                         ml = lt;
275                                 }
276                         } else {
277                                 ml = expr as VariableReference;
278                         }
279
280                         if (ml != null)
281                                 ml.AddressOf (ec, mode);
282                         else
283                                 LocalVariable.AddressOf (ec, mode);
284                 }
285
286                 //
287                 // Keeps result of non-variable expression
288                 //
289                 LocalTemporary LocalVariable {
290                         get {
291                                 if (temp == null && temp_field == null)
292                                         temp = new LocalTemporary (expr.Type);
293                                 return temp;
294                         }
295                 }
296         }
297
298         //
299         // Calls get_Value method on nullable expression
300         //
301         public class UnwrapCall : CompositeExpression
302         {
303                 public UnwrapCall (Expression expr)
304                         : base (expr)
305                 {
306                 }
307
308                 protected override Expression DoResolve (ResolveContext rc)
309                 {
310                         base.DoResolve (rc);
311
312                         if (type != null)
313                                 type = NullableInfo.GetUnderlyingType (type);
314
315                         return this;
316                 }
317
318                 public override void Emit (EmitContext ec)
319                 {
320                         var call = new CallEmitter ();
321                         call.InstanceExpression = Child;
322                         call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
323                 }
324         }
325
326         public class Wrap : TypeCast
327         {
328                 private Wrap (Expression expr, TypeSpec type)
329                         : base (expr, type)
330                 {
331                         eclass = ExprClass.Value;
332                 }
333
334                 public override Expression CreateExpressionTree (ResolveContext ec)
335                 {
336                         TypeCast child_cast = child as TypeCast;
337                         if (child_cast != null) {
338                                 child.Type = type;
339                                 return child_cast.CreateExpressionTree (ec);
340                         }
341
342                         var user_cast = child as UserCast;
343                         if (user_cast != null) {
344                                 child.Type = type;
345                                 return user_cast.CreateExpressionTree (ec);
346                         }
347
348                         return base.CreateExpressionTree (ec);
349                 }
350
351                 public static Expression Create (Expression expr, TypeSpec type)
352                 {
353                         //
354                         // Avoid unwraping and wraping of the same type
355                         //
356                         Unwrap unwrap = expr as Unwrap;
357                         if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
358                                 return unwrap.Original;
359                 
360                         return new Wrap (expr, type);
361                 }
362                 
363                 public override void Emit (EmitContext ec)
364                 {
365                         child.Emit (ec);
366                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
367                 }
368         }
369
370         //
371         // Represents null literal lifted to nullable type
372         //
373         public class LiftedNull : NullConstant, IMemoryLocation
374         {
375                 private LiftedNull (TypeSpec nullable_type, Location loc)
376                         : base (nullable_type, loc)
377                 {
378                         eclass = ExprClass.Value;
379                 }
380
381                 public static Constant Create (TypeSpec nullable, Location loc)
382                 {
383                         return new LiftedNull (nullable, loc);
384                 }
385
386                 public static Constant CreateFromExpression (ResolveContext rc, Expression e)
387                 {
388                         if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
389                                 rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
390                                         e.Type.GetSignatureForError ());
391                         }
392
393                         return ReducedExpression.Create (Create (e.Type, e.Location), e);
394                 }
395
396                 public override void Emit (EmitContext ec)
397                 {
398                         // TODO: generate less temporary variables
399                         LocalTemporary value_target = new LocalTemporary (type);
400
401                         value_target.AddressOf (ec, AddressOp.Store);
402                         ec.Emit (OpCodes.Initobj, type);
403                         value_target.Emit (ec);
404                         value_target.Release (ec);
405                 }
406
407                 public void AddressOf (EmitContext ec, AddressOp Mode)
408                 {
409                         LocalTemporary value_target = new LocalTemporary (type);
410                                 
411                         value_target.AddressOf (ec, AddressOp.Store);
412                         ec.Emit (OpCodes.Initobj, type);
413                         value_target.AddressOf (ec, Mode);
414                 }
415         }
416
417         //
418         // Generic lifting expression, supports all S/S? -> T/T? cases
419         //
420         public class LiftedConversion : Expression, IMemoryLocation
421         {
422                 Expression expr, null_value;
423                 Unwrap unwrap;
424
425                 public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
426                 {
427                         this.expr = expr;
428                         this.unwrap = unwrap;
429                         this.loc = expr.Location;
430                         this.type = type;
431                 }
432
433                 public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
434                         : this (expr, unwrap as Unwrap, type)
435                 {
436                 }
437
438                 public override bool IsNull {
439                         get {
440                                 return expr.IsNull;
441                         }
442                 }
443
444                 public override bool ContainsEmitWithAwait ()
445                 {
446                         return unwrap.ContainsEmitWithAwait ();
447                 }
448                 
449                 public override Expression CreateExpressionTree (ResolveContext ec)
450                 {
451                         return expr.CreateExpressionTree (ec);
452                 }                       
453
454                 protected override Expression DoResolve (ResolveContext ec)
455                 {
456                         //
457                         // It's null when lifting non-nullable type
458                         //
459                         if (unwrap == null) {
460                                 // S -> T? is wrap only
461                                 if (type.IsNullableType)
462                                         return Wrap.Create (expr, type);
463
464                                 // S -> T can be simplified
465                                 return expr;
466                         }
467
468                         // Wrap target for T?
469                         if (type.IsNullableType) {
470                                 if (!expr.Type.IsNullableType) {
471                                         expr = Wrap.Create (expr, type);
472                                         if (expr == null)
473                                                 return null;
474                                 }
475
476                                 null_value = LiftedNull.Create (type, loc);
477                         } else if (TypeSpec.IsValueType (type)) {
478                                 null_value = LiftedNull.Create (type, loc);
479                         } else {
480                                 null_value = new NullConstant (type, loc);
481                         }
482
483                         eclass = ExprClass.Value;
484                         return this;
485                 }
486
487                 public override void Emit (EmitContext ec)
488                 {
489                         Label is_null_label = ec.DefineLabel ();
490                         Label end_label = ec.DefineLabel ();
491
492                         unwrap.EmitCheck (ec);
493                         ec.Emit (OpCodes.Brfalse, is_null_label);
494
495                         expr.Emit (ec);
496
497                         ec.Emit (OpCodes.Br, end_label);
498                         ec.MarkLabel (is_null_label);
499
500                         null_value.Emit (ec);
501
502                         ec.MarkLabel (end_label);
503                 }
504
505                 public override void FlowAnalysis (FlowAnalysisContext fc)
506                 {
507                         expr.FlowAnalysis (fc);
508                 }
509
510                 public void AddressOf (EmitContext ec, AddressOp mode)
511                 {
512                         unwrap.AddressOf (ec, mode);
513                 }
514         }
515
516         public class LiftedUnaryOperator : Unary, IMemoryLocation
517         {
518                 Unwrap unwrap;
519                 Expression user_operator;
520
521                 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
522                         : base (op, expr, loc)
523                 {
524                 }
525
526                 public void AddressOf (EmitContext ec, AddressOp mode)
527                 {
528                         unwrap.AddressOf (ec, mode);
529                 }
530
531                 public override Expression CreateExpressionTree (ResolveContext ec)
532                 {
533                         if (user_operator != null)
534                                 return user_operator.CreateExpressionTree (ec);
535
536                         if (Oper == Operator.UnaryPlus)
537                                 return Expr.CreateExpressionTree (ec);
538
539                         return base.CreateExpressionTree (ec);
540                 }
541
542                 protected override Expression DoResolve (ResolveContext ec)
543                 {
544                         unwrap = Unwrap.Create (Expr, false);
545                         if (unwrap == null)
546                                 return null;
547
548                         Expression res = base.ResolveOperator (ec, unwrap);
549                         if (res == null) {
550                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
551                                 return null;
552                         }
553
554                         if (res != this) {
555                                 if (user_operator == null)
556                                         return res;
557                         } else {
558                                 res = Expr = LiftExpression (ec, Expr);
559                         }
560
561                         if (res == null)
562                                 return null;
563
564                         eclass = ExprClass.Value;
565                         type = res.Type;
566                         return this;
567                 }
568
569                 public override void Emit (EmitContext ec)
570                 {
571                         Label is_null_label = ec.DefineLabel ();
572                         Label end_label = ec.DefineLabel ();
573
574                         unwrap.EmitCheck (ec);
575                         ec.Emit (OpCodes.Brfalse, is_null_label);
576
577                         if (user_operator != null) {
578                                 user_operator.Emit (ec);
579                         } else {
580                                 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
581                         }
582
583                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
584                         ec.Emit (OpCodes.Br_S, end_label);
585
586                         ec.MarkLabel (is_null_label);
587                         LiftedNull.Create (type, loc).Emit (ec);
588
589                         ec.MarkLabel (end_label);
590                 }
591
592                 static Expression LiftExpression (ResolveContext ec, Expression expr)
593                 {
594                         var lifted_type = new NullableType (expr.Type, expr.Location);
595                         if (lifted_type.ResolveAsType (ec) == null)
596                                 return null;
597
598                         expr.Type = lifted_type.Type;
599                         return expr;
600                 }
601
602                 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
603                 {
604                         expr = base.ResolveEnumOperator (ec, expr, predefined);
605                         if (expr == null)
606                                 return null;
607
608                         Expr = LiftExpression (ec, Expr);
609                         return LiftExpression (ec, expr);
610                 }
611
612                 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
613                 {
614                         expr = base.ResolveUserOperator (ec, expr);
615                         if (expr == null)
616                                 return null;
617
618                         //
619                         // When a user operator is of non-nullable type
620                         //
621                         if (Expr is Unwrap) {
622                                 user_operator = LiftExpression (ec, expr);
623                                 return user_operator;
624                         }
625
626                         return expr;
627                 }
628         }
629
630         //
631         // Lifted version of binary operators
632         //
633         class LiftedBinaryOperator : Expression
634         {
635                 public LiftedBinaryOperator (Binary b)
636                 {
637                         this.Binary = b;
638                         this.loc = b.Location;
639                 }
640
641                 public Binary Binary { get; private set; }
642
643                 public Expression Left { get; set; }
644
645                 public Expression Right { get; set; }
646
647                 public Unwrap UnwrapLeft { get; set; }
648
649                 public Unwrap UnwrapRight { get; set; }
650
651                 public MethodSpec UserOperator { get; set; }
652
653                 bool IsBitwiseBoolean {
654                         get {
655                                 return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
656                                 ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
657                                  (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
658                         }
659                 }
660
661                 public override bool ContainsEmitWithAwait ()
662                 {
663                         return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
664                 }
665
666                 public override Expression CreateExpressionTree (ResolveContext rc)
667                 {
668                         if (UserOperator != null) {
669                                 Arguments args = new Arguments (2);
670                                 args.Add (new Argument (Binary.Left));
671                                 args.Add (new Argument (Binary.Right));
672
673                                 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
674                                 return method.CreateExpressionTree (rc);
675                         }
676
677                         return Binary.CreateExpressionTree (rc);
678                 }
679
680                 protected override Expression DoResolve (ResolveContext rc)
681                 {
682                         if (rc.IsRuntimeBinder) {
683                                 if (UnwrapLeft == null && !Left.Type.IsNullableType)
684                                         Left = LiftOperand (rc, Left);
685
686                                 if (UnwrapRight == null && !Right.Type.IsNullableType)
687                                         Right = LiftOperand (rc, Right);
688                         } else {
689                                 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
690                                         Left = Unwrap.CreateUnwrapped (Left);
691                                         UnwrapLeft = Left as Unwrap;
692                                 }
693
694                                 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
695                                         Right = Unwrap.CreateUnwrapped (Right);
696                                         UnwrapRight = Right as Unwrap;
697                                 }
698                         }
699
700                         type = Binary.Type;
701                         eclass = Binary.eclass; 
702
703                         return this;
704                 }
705
706                 Expression LiftOperand (ResolveContext rc, Expression expr)
707                 {
708                         TypeSpec type;
709                         if (expr.IsNull) {
710                                 type = Left.IsNull ? Right.Type : Left.Type;
711                         } else {
712                                 type = expr.Type;
713                         }
714
715                         if (!type.IsNullableType)
716                                 type = NullableInfo.MakeType (rc.Module, type);
717
718                         return Wrap.Create (expr, type);
719                 }
720
721                 public override void Emit (EmitContext ec)
722                 {
723                         if (IsBitwiseBoolean && UserOperator == null) {
724                                 EmitBitwiseBoolean (ec);
725                                 return;
726                         }
727
728                         if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
729                                 EmitEquality (ec);
730                                 return;
731                         }
732
733                         Label is_null_label = ec.DefineLabel ();
734                         Label end_label = ec.DefineLabel ();
735
736                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
737                                 Left = Left.EmitToField (ec);
738                                 Right = Right.EmitToField (ec);
739                         }
740
741                         if (UnwrapLeft != null) {
742                                 UnwrapLeft.EmitCheck (ec);
743                         }
744
745                         //
746                         // Don't emit HasValue check when left and right expressions are same
747                         //
748                         if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
749                                 UnwrapRight.EmitCheck (ec);
750                                 if (UnwrapLeft != null) {
751                                         ec.Emit (OpCodes.And);
752                                 }
753                         }
754
755                         ec.Emit (OpCodes.Brfalse, is_null_label);
756
757                         if (UserOperator != null) {
758                                 var args = new Arguments (2);
759                                 args.Add (new Argument (Left));
760                                 args.Add (new Argument (Right));
761
762                                 var call = new CallEmitter ();
763                                 call.EmitPredefined (ec, UserOperator, args);
764                         } else {
765                                 Binary.EmitOperator (ec, Left, Right);
766                         }
767
768                         //
769                         // Wrap the result when the operator return type is nullable type
770                         //
771                         if (type.IsNullableType)
772                                 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
773
774                         ec.Emit (OpCodes.Br_S, end_label);
775                         ec.MarkLabel (is_null_label);
776
777                         if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
778                                 ec.EmitInt (0);
779                         } else {
780                                 LiftedNull.Create (type, loc).Emit (ec);
781                         }
782
783                         ec.MarkLabel (end_label);
784                 }
785
786                 void EmitBitwiseBoolean (EmitContext ec)
787                 {
788                         Label load_left = ec.DefineLabel ();
789                         Label load_right = ec.DefineLabel ();
790                         Label end_label = ec.DefineLabel ();
791                         Label is_null_label = ec.DefineLabel ();
792
793                         bool or = Binary.Oper == Binary.Operator.BitwiseOr;
794
795                         //
796                         // Both operands are bool? types
797                         //
798                         if ((UnwrapLeft != null && !Left.IsNull) && (UnwrapRight != null && !Right.IsNull)) {
799                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
800                                         Left = Left.EmitToField (ec);
801                                         Right = Right.EmitToField (ec);
802                                 } else {
803                                         UnwrapLeft.Store (ec);
804                                         UnwrapRight.Store (ec);
805                                 }
806
807                                 Left.Emit (ec);
808                                 ec.Emit (OpCodes.Brtrue_S, load_right);
809
810                                 Right.Emit (ec);
811                                 ec.Emit (OpCodes.Brtrue_S, load_left);
812
813                                 UnwrapLeft.EmitCheck (ec);
814                                 ec.Emit (OpCodes.Brfalse_S, load_right);
815
816                                 // load left
817                                 ec.MarkLabel (load_left);
818                                 if (or)
819                                         UnwrapRight.Load (ec);
820                                 else
821                                         UnwrapLeft.Load (ec);
822
823                                 ec.Emit (OpCodes.Br_S, end_label);
824
825                                 // load right
826                                 ec.MarkLabel (load_right);
827                                 if (or)
828                                         UnwrapLeft.Load (ec);
829                                 else
830                                         UnwrapRight.Load (ec);
831
832                                 ec.MarkLabel (end_label);
833                                 return;
834                         }
835
836                         //
837                         // Faster version when one operand is bool
838                         //
839                         if (UnwrapLeft == null) {
840                                 //
841                                 // (bool, bool?)
842                                 //
843                                 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
844                                 // in binary expression reduction
845                                 //
846                                 var c = Left as BoolConstant;
847                                 if (c != null) {
848                                         // Keep evaluation order
849                                         UnwrapRight.Store (ec);
850
851                                         ec.EmitInt (or ? 1 : 0);
852                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
853                                 } else if (Left.IsNull) {
854                                         UnwrapRight.Emit (ec);
855                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
856
857                                         UnwrapRight.Load (ec);
858                                         ec.Emit (OpCodes.Br_S, end_label);
859
860                                         ec.MarkLabel (is_null_label);
861                                         LiftedNull.Create (type, loc).Emit (ec);
862                                 } else {
863                                         Left.Emit (ec);
864                                         UnwrapRight.Store (ec);
865
866                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
867
868                                         ec.EmitInt (or ? 1 : 0);
869                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
870
871                                         ec.Emit (OpCodes.Br_S, end_label);
872
873                                         ec.MarkLabel (load_right);
874                                         UnwrapRight.Load (ec);
875                                 }
876                         } else {
877                                 //
878                                 // (bool?, bool)
879                                 //
880                                 // Keep left-right evaluation order
881                                 UnwrapLeft.Store (ec);
882
883                                 //
884                                 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
885                                 // in binary expression reduction
886                                 //
887                                 var c = Right as BoolConstant;
888                                 if (c != null) {
889                                         ec.EmitInt (or ? 1 : 0);
890                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
891                                 } else if (Right.IsNull) {
892                                         UnwrapLeft.Emit (ec);
893                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
894
895                                         UnwrapLeft.Load (ec);
896                                         ec.Emit (OpCodes.Br_S, end_label);
897
898                                         ec.MarkLabel (is_null_label);
899                                         LiftedNull.Create (type, loc).Emit (ec);
900                                 } else {
901                                         Right.Emit (ec);
902                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_left);
903
904                                         ec.EmitInt (or ? 1 : 0);
905                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
906
907                                         ec.Emit (OpCodes.Br_S, end_label);
908
909                                         ec.MarkLabel (load_left);
910
911                                         UnwrapLeft.Load (ec);
912                                 }
913                         }
914
915                         ec.MarkLabel (end_label);
916                 }
917
918                 //
919                 // Emits optimized equality or inequality operator when possible
920                 //
921                 void EmitEquality (EmitContext ec)
922                 {
923                         //
924                         // Either left or right is null
925                         // 
926                         if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
927                                 //
928                                 // left.HasValue == false 
929                                 //
930                                 UnwrapLeft.EmitCheck (ec);
931                                 if (Binary.Oper == Binary.Operator.Equality) {
932                                         ec.EmitInt (0);
933                                         ec.Emit (OpCodes.Ceq);
934                                 }
935                                 return;
936                         }
937
938                         if (UnwrapRight != null && Binary.Left.IsNull) {
939                                 //
940                                 // right.HasValue == false 
941                                 //
942                                 UnwrapRight.EmitCheck (ec);
943                                 if (Binary.Oper == Binary.Operator.Equality) {
944                                         ec.EmitInt (0);
945                                         ec.Emit (OpCodes.Ceq);
946                                 }
947                                 return;
948                         }
949
950                         Label dissimilar_label = ec.DefineLabel ();
951                         Label end_label = ec.DefineLabel ();
952
953                         if (UserOperator != null) {
954                                 var left = Left;
955
956                                 if (UnwrapLeft != null) {
957                                         UnwrapLeft.EmitCheck (ec);
958                                 } else {
959                                         // Keep evaluation order same
960                                         if (!(Left is VariableReference)) {
961                                                 Left.Emit (ec);
962                                                 var lt = new LocalTemporary (Left.Type);
963                                                 lt.Store (ec);
964                                                 left = lt;
965                                         }
966                                 }
967
968                                 if (UnwrapRight != null) {
969                                         UnwrapRight.EmitCheck (ec);
970
971                                         if (UnwrapLeft != null) {
972                                                 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
973
974                                                 Label compare_label = ec.DefineLabel ();
975                                                 UnwrapLeft.EmitCheck (ec);
976                                                 ec.Emit (OpCodes.Brtrue, compare_label);
977
978                                                 if (Binary.Oper == Binary.Operator.Equality)
979                                                         ec.EmitInt (1);
980                                                 else
981                                                         ec.EmitInt (0);
982
983                                                 ec.Emit (OpCodes.Br, end_label);
984
985                                                 ec.MarkLabel (compare_label);
986                                         } else {
987                                                 ec.Emit (OpCodes.Brfalse, dissimilar_label);
988                                         }
989                                 } else {
990                                         ec.Emit (OpCodes.Brfalse, dissimilar_label);
991                                 }
992
993                                 var args = new Arguments (2);
994                                 args.Add (new Argument (left));
995                                 args.Add (new Argument (Right));
996
997                                 var call = new CallEmitter ();
998                                 call.EmitPredefined (ec, UserOperator, args);
999                         } else {
1000                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
1001                                         Left = Left.EmitToField (ec);
1002                                         Right = Right.EmitToField (ec);
1003                                 }
1004
1005                                 //
1006                                 // Emit underlying value comparison first.
1007                                 //
1008                                 // For this code: int? a = 1; bool b = a == 1;
1009                                 //
1010                                 // We emit something similar to this. Expressions with side effects have local
1011                                 // variable created by Unwrap expression
1012                                 //
1013                                 //      left.GetValueOrDefault ()
1014                                 //      right
1015                                 //      bne.un.s   dissimilar_label
1016                                 //  left.HasValue
1017                                 //      br.s       end_label
1018                                 // dissimilar_label:
1019                                 //      ldc.i4.0
1020                                 // end_label:
1021                                 //
1022
1023                                 Left.Emit (ec);
1024                                 Right.Emit (ec);
1025
1026                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
1027
1028                                 //
1029                                 // Check both left and right expressions for Unwrap call in which
1030                                 // case we need to run get_HasValue() check because the type is
1031                                 // nullable and could have null value
1032                                 //
1033                                 if (UnwrapLeft != null)
1034                                         UnwrapLeft.EmitCheck (ec);
1035
1036                                 if (UnwrapRight != null)
1037                                         UnwrapRight.EmitCheck (ec);
1038
1039                                 if (UnwrapLeft != null && UnwrapRight != null) {
1040                                         if (Binary.Oper == Binary.Operator.Inequality)
1041                                                 ec.Emit (OpCodes.Xor);
1042                                         else
1043                                                 ec.Emit (OpCodes.Ceq);
1044                                 } else {
1045                                         if (Binary.Oper == Binary.Operator.Inequality) {
1046                                                 ec.EmitInt (0);
1047                                                 ec.Emit (OpCodes.Ceq);
1048                                         }
1049                                 }
1050                         }
1051
1052                         ec.Emit (OpCodes.Br_S, end_label);
1053
1054                         ec.MarkLabel (dissimilar_label);
1055                         if (Binary.Oper == Binary.Operator.Inequality)
1056                                 ec.EmitInt (1);
1057                         else
1058                                 ec.EmitInt (0);
1059
1060                         ec.MarkLabel (end_label);
1061                 }
1062
1063                 public override void FlowAnalysis (FlowAnalysisContext fc)
1064                 {
1065                         Binary.FlowAnalysis (fc);
1066                 }
1067
1068                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1069                 {
1070                         return Binary.MakeExpression (ctx, Left, Right);
1071                 }
1072         }
1073
1074         public class NullCoalescingOperator : Expression
1075         {
1076                 Expression left, right;
1077                 Unwrap unwrap;
1078                 bool user_conversion_left;
1079
1080                 public NullCoalescingOperator (Expression left, Expression right)
1081                 {
1082                         this.left = left;
1083                         this.right = right;
1084                         this.loc = left.Location;
1085                 }
1086
1087                 public Expression LeftExpression {
1088                         get {
1089                                 return left;
1090                         }
1091                 }
1092
1093                 public Expression RightExpression {
1094                         get {
1095                                 return right;
1096                         }
1097                 }
1098                 
1099                 public override Expression CreateExpressionTree (ResolveContext ec)
1100                 {
1101                         if (left is NullLiteral)
1102                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1103
1104                         UserCast uc = left as UserCast;
1105                         Expression conversion = null;
1106                         if (uc != null) {
1107                                 left = uc.Source;
1108
1109                                 Arguments c_args = new Arguments (2);
1110                                 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1111                                 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1112                                 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1113                         }
1114
1115                         Arguments args = new Arguments (3);
1116                         args.Add (new Argument (left.CreateExpressionTree (ec)));
1117                         args.Add (new Argument (right.CreateExpressionTree (ec)));
1118                         if (conversion != null)
1119                                 args.Add (new Argument (conversion));
1120                         
1121                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
1122                 }
1123
1124                 Expression ConvertExpression (ResolveContext ec)
1125                 {
1126                         // TODO: ImplicitConversionExists should take care of this
1127                         if (left.eclass == ExprClass.MethodGroup)
1128                                 return null;
1129
1130                         TypeSpec ltype = left.Type;
1131
1132                         //
1133                         // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1134                         // the result is underlying type of left
1135                         //
1136                         if (ltype.IsNullableType) {
1137                                 unwrap = Unwrap.Create (left, false);
1138                                 if (unwrap == null)
1139                                         return null;
1140
1141                                 //
1142                                 // Reduce (left ?? null) to left
1143                                 //
1144                                 if (right.IsNull)
1145                                         return ReducedExpression.Create (left, this);
1146
1147                                 Expression conv;
1148                                 if (right.Type.IsNullableType) {
1149                                         conv = right.Type == ltype ? right : Convert.ImplicitNulableConversion (ec, right, ltype);
1150                                         if (conv != null) {
1151                                                 right = conv;
1152                                                 type = ltype;
1153                                                 return this;
1154                                         }
1155                                 } else {
1156                                         conv = Convert.ImplicitConversion (ec, right, unwrap.Type, loc);
1157                                         if (conv != null) {
1158                                                 left = unwrap;
1159                                                 ltype = left.Type;
1160
1161                                                 //
1162                                                 // If right is a dynamic expression, the result type is dynamic
1163                                                 //
1164                                                 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1165                                                         type = right.Type;
1166
1167                                                         // Need to box underlying value type
1168                                                         left = Convert.ImplicitBoxingConversion (left, ltype, type);
1169                                                         return this;
1170                                                 }
1171
1172                                                 right = conv;
1173                                                 type = ltype;
1174                                                 return this;
1175                                         }
1176                                 }
1177                         } else if (TypeSpec.IsReferenceType (ltype)) {
1178                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1179                                         //
1180                                         // If right is a dynamic expression, the result type is dynamic
1181                                         //
1182                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1183                                                 type = right.Type;
1184                                                 return this;
1185                                         }
1186
1187                                         //
1188                                         // Reduce ("foo" ?? expr) to expression
1189                                         //
1190                                         Constant lc = left as Constant;
1191                                         if (lc != null && !lc.IsDefaultValue)
1192                                                 return ReducedExpression.Create (lc, this, false);
1193
1194                                         //
1195                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1196                                         //
1197                                         if (right.IsNull || lc != null) {
1198                                                 //
1199                                                 // Special case null ?? null
1200                                                 //
1201                                                 if (right.IsNull && ltype == right.Type)
1202                                                         return null;
1203
1204                                                 return ReducedExpression.Create (lc != null ? right : left, this, false);
1205                                         }
1206
1207                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1208                                         type = ltype;
1209                                         return this;
1210                                 }
1211                         } else {
1212                                 return null;
1213                         }
1214
1215                         TypeSpec rtype = right.Type;
1216                         if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1217                                 return null;
1218
1219                         //
1220                         // Reduce (null ?? right) to right
1221                         //
1222                         if (left.IsNull)
1223                                 return ReducedExpression.Create (right, this, false).Resolve (ec);
1224
1225                         left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1226                         user_conversion_left = left is UserCast;
1227                         type = rtype;
1228                         return this;
1229                 }
1230
1231                 public override bool ContainsEmitWithAwait ()
1232                 {
1233                         if (unwrap != null)
1234                                 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1235
1236                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1237                 }
1238
1239                 protected override Expression DoResolve (ResolveContext ec)
1240                 {
1241                         left = left.Resolve (ec);
1242                         right = right.Resolve (ec);
1243
1244                         if (left == null || right == null)
1245                                 return null;
1246
1247                         eclass = ExprClass.Value;
1248
1249                         Expression e = ConvertExpression (ec);
1250                         if (e == null) {
1251                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1252                                 return null;
1253                         }
1254
1255                         return e;
1256                 }
1257
1258                 public override void Emit (EmitContext ec)
1259                 {
1260                         Label end_label = ec.DefineLabel ();
1261
1262                         if (unwrap != null) {
1263                                 Label is_null_label = ec.DefineLabel ();
1264
1265                                 unwrap.EmitCheck (ec);
1266                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1267
1268                                 //
1269                                 // When both expressions are nullable the unwrap
1270                                 // is needed only for null check not for value uwrap
1271                                 //
1272                                 if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type))
1273                                         unwrap.Load (ec);
1274                                 else
1275                                         left.Emit (ec);
1276
1277                                 ec.Emit (OpCodes.Br, end_label);
1278
1279                                 ec.MarkLabel (is_null_label);
1280                                 right.Emit (ec);
1281
1282                                 ec.MarkLabel (end_label);
1283                                 return;
1284                         }
1285
1286                         //
1287                         // Null check is done on original expression not after expression is converted to
1288                         // result type. This is in most cases same but when user conversion is involved
1289                         // we can end up in situation when user operator does the null handling which is
1290                         // not what the operator is supposed to do.
1291                         // There is tricky case where cast of left expression is meant to be cast of
1292                         // whole source expression (null check is done on it) and cast from right-to-left
1293                         // conversion needs to do null check on unconverted source expression.
1294                         //
1295                         if (user_conversion_left) {
1296                                 var op_expr = (UserCast) left;
1297
1298                                 op_expr.Source.Emit (ec);
1299                                 LocalTemporary temp;
1300
1301                                 // TODO: More load kinds can be special cased
1302                                 if (!(op_expr.Source is VariableReference)) {
1303                                         temp = new LocalTemporary (op_expr.Source.Type);
1304                                         temp.Store (ec);
1305                                         temp.Emit (ec);
1306                                         op_expr.Source = temp;
1307                                 } else {
1308                                         temp = null;
1309                                 }
1310
1311                                 var right_label = ec.DefineLabel ();
1312                                 ec.Emit (OpCodes.Brfalse_S, right_label);
1313                                 left.Emit (ec);
1314                                 ec.Emit (OpCodes.Br, end_label);
1315                                 ec.MarkLabel (right_label);
1316
1317                                 if (temp != null)
1318                                         temp.Release (ec);
1319                         } else {
1320                                 //
1321                                 // Common case where expression is not modified before null check and
1322                                 // we generate better/smaller code
1323                                 //
1324                                 left.Emit (ec);
1325                                 ec.Emit (OpCodes.Dup);
1326
1327                                 // Only to make verifier happy
1328                                 if (left.Type.IsGenericParameter)
1329                                         ec.Emit (OpCodes.Box, left.Type);
1330
1331                                 ec.Emit (OpCodes.Brtrue, end_label);
1332
1333                                 ec.Emit (OpCodes.Pop);
1334                         }
1335
1336                         right.Emit (ec);
1337
1338                         ec.MarkLabel (end_label);
1339                 }
1340
1341                 public override void FlowAnalysis (FlowAnalysisContext fc)
1342                 {
1343                         left.FlowAnalysis (fc);
1344                         var left_da = fc.BranchDefiniteAssignment ();
1345                         right.FlowAnalysis (fc);
1346                         fc.DefiniteAssignment = left_da;
1347                 }
1348
1349                 protected override void CloneTo (CloneContext clonectx, Expression t)
1350                 {
1351                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1352
1353                         target.left = left.Clone (clonectx);
1354                         target.right = right.Clone (clonectx);
1355                 }
1356                 
1357                 public override object Accept (StructuralVisitor visitor)
1358                 {
1359                         return visitor.Visit (this);
1360                 }
1361         }
1362
1363         class LiftedUnaryMutator : UnaryMutator
1364         {
1365                 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1366                         : base (mode, expr, loc)
1367                 {
1368                 }
1369
1370                 protected override Expression DoResolve (ResolveContext ec)
1371                 {
1372                         var orig_expr = expr;
1373
1374                         expr = Unwrap.Create (expr);
1375
1376                         var res = base.DoResolveOperation (ec);
1377
1378                         expr = orig_expr;
1379                         type = expr.Type;
1380
1381                         return res;
1382                 }
1383
1384                 protected override void EmitOperation (EmitContext ec)
1385                 {
1386                         Label is_null_label = ec.DefineLabel ();
1387                         Label end_label = ec.DefineLabel ();
1388
1389                         LocalTemporary lt = new LocalTemporary (type);
1390
1391                         // Value is on the stack
1392                         lt.Store (ec);
1393
1394                         var call = new CallEmitter ();
1395                         call.InstanceExpression = lt;
1396                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1397
1398                         ec.Emit (OpCodes.Brfalse, is_null_label);
1399
1400                         call = new CallEmitter ();
1401                         call.InstanceExpression = lt;
1402                         call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1403
1404                         lt.Release (ec);
1405
1406                         base.EmitOperation (ec);
1407
1408                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1409                         ec.Emit (OpCodes.Br_S, end_label);
1410
1411                         ec.MarkLabel (is_null_label);
1412                         LiftedNull.Create (type, loc).Emit (ec);
1413
1414                         ec.MarkLabel (end_label);
1415                 }
1416         }
1417 }
1418