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