[mono-api-html] Print string fields with no (or null) value without an NRE.
[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                                 } else {
781                                         UnwrapLeft.Store (ec);
782                                         UnwrapRight.Store (ec);
783                                 }
784
785                                 Left.Emit (ec);
786                                 ec.Emit (OpCodes.Brtrue_S, load_right);
787
788                                 Right.Emit (ec);
789                                 ec.Emit (OpCodes.Brtrue_S, load_left);
790
791                                 UnwrapLeft.EmitCheck (ec);
792                                 ec.Emit (OpCodes.Brfalse_S, load_right);
793
794                                 // load left
795                                 ec.MarkLabel (load_left);
796                                 if (or)
797                                         UnwrapRight.Load (ec);
798                                 else
799                                         UnwrapLeft.Load (ec);
800
801                                 ec.Emit (OpCodes.Br_S, end_label);
802
803                                 // load right
804                                 ec.MarkLabel (load_right);
805                                 if (or)
806                                         UnwrapLeft.Load (ec);
807                                 else
808                                         UnwrapRight.Load (ec);
809
810                                 ec.MarkLabel (end_label);
811                                 return;
812                         }
813
814                         //
815                         // Faster version when one operand is bool
816                         //
817                         if (UnwrapLeft == null) {
818                                 //
819                                 // (bool, bool?)
820                                 //
821                                 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
822                                 // in binary expression reduction
823                                 //
824                                 var c = Left as BoolConstant;
825                                 if (c != null) {
826                                         // Keep evaluation order
827                                         UnwrapRight.Store (ec);
828
829                                         ec.EmitInt (or ? 1 : 0);
830                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
831                                 } else if (Left.IsNull) {
832                                         UnwrapRight.Emit (ec);
833                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
834
835                                         UnwrapRight.Load (ec);
836                                         ec.Emit (OpCodes.Br_S, end_label);
837
838                                         ec.MarkLabel (is_null_label);
839                                         LiftedNull.Create (type, loc).Emit (ec);
840                                 } else {
841                                         Left.Emit (ec);
842                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
843
844                                         ec.EmitInt (or ? 1 : 0);
845                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
846
847                                         ec.Emit (OpCodes.Br_S, end_label);
848
849                                         ec.MarkLabel (load_right);
850                                         UnwrapRight.Original.Emit (ec);
851                                 }
852                         } else {
853                                 //
854                                 // (bool?, bool)
855                                 //
856                                 // Keep left-right evaluation order
857                                 UnwrapLeft.Store (ec);
858
859                                 //
860                                 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
861                                 // in binary expression reduction
862                                 //
863                                 var c = Right as BoolConstant;
864                                 if (c != null) {
865                                         ec.EmitInt (or ? 1 : 0);
866                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
867                                 } else if (Right.IsNull) {
868                                         UnwrapLeft.Emit (ec);
869                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
870
871                                         UnwrapLeft.Load (ec);
872                                         ec.Emit (OpCodes.Br_S, end_label);
873
874                                         ec.MarkLabel (is_null_label);
875                                         LiftedNull.Create (type, loc).Emit (ec);
876                                 } else {
877                                         Right.Emit (ec);
878                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
879
880                                         ec.EmitInt (or ? 1 : 0);
881                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
882
883                                         ec.Emit (OpCodes.Br_S, end_label);
884
885                                         ec.MarkLabel (load_right);
886
887                                         UnwrapLeft.Load (ec);
888                                 }
889                         }
890
891                         ec.MarkLabel (end_label);
892                 }
893
894                 //
895                 // Emits optimized equality or inequality operator when possible
896                 //
897                 void EmitEquality (EmitContext ec)
898                 {
899                         //
900                         // Either left or right is null
901                         // 
902                         if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
903                                 //
904                                 // left.HasValue == false 
905                                 //
906                                 UnwrapLeft.EmitCheck (ec);
907                                 if (Binary.Oper == Binary.Operator.Equality) {
908                                         ec.EmitInt (0);
909                                         ec.Emit (OpCodes.Ceq);
910                                 }
911                                 return;
912                         }
913
914                         if (UnwrapRight != null && Binary.Left.IsNull) {
915                                 //
916                                 // right.HasValue == false 
917                                 //
918                                 UnwrapRight.EmitCheck (ec);
919                                 if (Binary.Oper == Binary.Operator.Equality) {
920                                         ec.EmitInt (0);
921                                         ec.Emit (OpCodes.Ceq);
922                                 }
923                                 return;
924                         }
925
926                         Label dissimilar_label = ec.DefineLabel ();
927                         Label end_label = ec.DefineLabel ();
928
929                         if (UserOperator != null) {
930                                 var left = Left;
931
932                                 if (UnwrapLeft != null) {
933                                         UnwrapLeft.EmitCheck (ec);
934                                 } else {
935                                         // Keep evaluation order same
936                                         if (!(Left is VariableReference)) {
937                                                 Left.Emit (ec);
938                                                 var lt = new LocalTemporary (Left.Type);
939                                                 lt.Store (ec);
940                                                 left = lt;
941                                         }
942                                 }
943
944                                 if (UnwrapRight != null) {
945                                         UnwrapRight.EmitCheck (ec);
946
947                                         if (UnwrapLeft != null) {
948                                                 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
949
950                                                 Label compare_label = ec.DefineLabel ();
951                                                 UnwrapLeft.EmitCheck (ec);
952                                                 ec.Emit (OpCodes.Brtrue, compare_label);
953
954                                                 if (Binary.Oper == Binary.Operator.Equality)
955                                                         ec.EmitInt (1);
956                                                 else
957                                                         ec.EmitInt (0);
958
959                                                 ec.Emit (OpCodes.Br, end_label);
960
961                                                 ec.MarkLabel (compare_label);
962                                         } else {
963                                                 ec.Emit (OpCodes.Brfalse, dissimilar_label);
964                                         }
965                                 } else {
966                                         ec.Emit (OpCodes.Brfalse, dissimilar_label);
967                                 }
968
969                                 var args = new Arguments (2);
970                                 args.Add (new Argument (left));
971                                 args.Add (new Argument (Right));
972
973                                 var call = new CallEmitter ();
974                                 call.EmitPredefined (ec, UserOperator, args);
975                         } else {
976                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
977                                         Left = Left.EmitToField (ec);
978                                         Right = Right.EmitToField (ec);
979                                 }
980
981                                 //
982                                 // Emit underlying value comparison first.
983                                 //
984                                 // For this code: int? a = 1; bool b = a == 1;
985                                 //
986                                 // We emit something similar to this. Expressions with side effects have local
987                                 // variable created by Unwrap expression
988                                 //
989                                 //      left.GetValueOrDefault ()
990                                 //      right
991                                 //      bne.un.s   dissimilar_label
992                                 //  left.HasValue
993                                 //      br.s       end_label
994                                 // dissimilar_label:
995                                 //      ldc.i4.0
996                                 // end_label:
997                                 //
998
999                                 Left.Emit (ec);
1000                                 Right.Emit (ec);
1001
1002                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
1003
1004                                 //
1005                                 // Check both left and right expressions for Unwrap call in which
1006                                 // case we need to run get_HasValue() check because the type is
1007                                 // nullable and could have null value
1008                                 //
1009                                 if (UnwrapLeft != null)
1010                                         UnwrapLeft.EmitCheck (ec);
1011
1012                                 if (UnwrapRight != null)
1013                                         UnwrapRight.EmitCheck (ec);
1014
1015                                 if (UnwrapLeft != null && UnwrapRight != null) {
1016                                         if (Binary.Oper == Binary.Operator.Inequality)
1017                                                 ec.Emit (OpCodes.Xor);
1018                                         else
1019                                                 ec.Emit (OpCodes.Ceq);
1020                                 } else {
1021                                         if (Binary.Oper == Binary.Operator.Inequality) {
1022                                                 ec.EmitInt (0);
1023                                                 ec.Emit (OpCodes.Ceq);
1024                                         }
1025                                 }
1026                         }
1027
1028                         ec.Emit (OpCodes.Br_S, end_label);
1029
1030                         ec.MarkLabel (dissimilar_label);
1031                         if (Binary.Oper == Binary.Operator.Inequality)
1032                                 ec.EmitInt (1);
1033                         else
1034                                 ec.EmitInt (0);
1035
1036                         ec.MarkLabel (end_label);
1037                 }
1038
1039                 public override void FlowAnalysis (FlowAnalysisContext fc)
1040                 {
1041                         Binary.FlowAnalysis (fc);
1042                 }
1043
1044                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1045                 {
1046                         return Binary.MakeExpression (ctx, Left, Right);
1047                 }
1048         }
1049
1050         public class NullCoalescingOperator : Expression
1051         {
1052                 Expression left, right;
1053                 Unwrap unwrap;
1054
1055                 public NullCoalescingOperator (Expression left, Expression right)
1056                 {
1057                         this.left = left;
1058                         this.right = right;
1059                         this.loc = left.Location;
1060                 }
1061
1062                 public Expression LeftExpression {
1063                         get {
1064                                 return left;
1065                         }
1066                 }
1067
1068                 public Expression RightExpression {
1069                         get {
1070                                 return right;
1071                         }
1072                 }
1073                 
1074                 public override Expression CreateExpressionTree (ResolveContext ec)
1075                 {
1076                         if (left is NullLiteral)
1077                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1078
1079                         UserCast uc = left as UserCast;
1080                         Expression conversion = null;
1081                         if (uc != null) {
1082                                 left = uc.Source;
1083
1084                                 Arguments c_args = new Arguments (2);
1085                                 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1086                                 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1087                                 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1088                         }
1089
1090                         Arguments args = new Arguments (3);
1091                         args.Add (new Argument (left.CreateExpressionTree (ec)));
1092                         args.Add (new Argument (right.CreateExpressionTree (ec)));
1093                         if (conversion != null)
1094                                 args.Add (new Argument (conversion));
1095                         
1096                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
1097                 }
1098
1099                 Expression ConvertExpression (ResolveContext ec)
1100                 {
1101                         // TODO: ImplicitConversionExists should take care of this
1102                         if (left.eclass == ExprClass.MethodGroup)
1103                                 return null;
1104
1105                         TypeSpec ltype = left.Type;
1106
1107                         //
1108                         // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1109                         // the result is underlying type of left
1110                         //
1111                         if (ltype.IsNullableType) {
1112                                 unwrap = Unwrap.Create (left, false);
1113                                 if (unwrap == null)
1114                                         return null;
1115
1116                                 //
1117                                 // Reduce (left ?? null) to left
1118                                 //
1119                                 if (right.IsNull)
1120                                         return ReducedExpression.Create (left, this);
1121
1122                                 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1123                                         left = unwrap;
1124                                         ltype = left.Type;
1125
1126                                         //
1127                                         // If right is a dynamic expression, the result type is dynamic
1128                                         //
1129                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1130                                                 type = right.Type;
1131
1132                                                 // Need to box underlying value type
1133                                                 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1134                                                 return this;
1135                                         }
1136
1137                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1138                                         type = ltype;
1139                                         return this;
1140                                 }
1141                         } else if (TypeSpec.IsReferenceType (ltype)) {
1142                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1143                                         //
1144                                         // If right is a dynamic expression, the result type is dynamic
1145                                         //
1146                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1147                                                 type = right.Type;
1148                                                 return this;
1149                                         }
1150
1151                                         //
1152                                         // Reduce ("foo" ?? expr) to expression
1153                                         //
1154                                         Constant lc = left as Constant;
1155                                         if (lc != null && !lc.IsDefaultValue)
1156                                                 return ReducedExpression.Create (lc, this);
1157
1158                                         //
1159                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1160                                         //
1161                                         if (right.IsNull || lc != null)
1162                                                 return ReducedExpression.Create (lc != null ? right : left, this);
1163
1164                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1165                                         type = ltype;
1166                                         return this;
1167                                 }
1168
1169                                 //
1170                                 // Special case null ?? null
1171                                 //
1172                                 if (ltype == right.Type) {
1173                                         type = ltype;
1174                                         return this;
1175                                 }
1176                         } else {
1177                                 return null;
1178                         }
1179
1180                         TypeSpec rtype = right.Type;
1181                         if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1182                                 return null;
1183
1184                         //
1185                         // Reduce (null ?? right) to right
1186                         //
1187                         if (left.IsNull)
1188                                 return ReducedExpression.Create (right, this).Resolve (ec);
1189
1190                         left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1191                         type = rtype;
1192                         return this;
1193                 }
1194
1195                 public override bool ContainsEmitWithAwait ()
1196                 {
1197                         if (unwrap != null)
1198                                 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1199
1200                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1201                 }
1202
1203                 protected override Expression DoResolve (ResolveContext ec)
1204                 {
1205                         left = left.Resolve (ec);
1206                         right = right.Resolve (ec);
1207
1208                         if (left == null || right == null)
1209                                 return null;
1210
1211                         eclass = ExprClass.Value;
1212
1213                         Expression e = ConvertExpression (ec);
1214                         if (e == null) {
1215                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1216                                 return null;
1217                         }
1218
1219                         return e;
1220                 }
1221
1222                 public override void Emit (EmitContext ec)
1223                 {
1224                         Label end_label = ec.DefineLabel ();
1225
1226                         if (unwrap != null) {
1227                                 Label is_null_label = ec.DefineLabel ();
1228
1229                                 unwrap.EmitCheck (ec);
1230                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1231
1232                                 left.Emit (ec);
1233                                 ec.Emit (OpCodes.Br, end_label);
1234
1235                                 ec.MarkLabel (is_null_label);
1236                                 right.Emit (ec);
1237
1238                                 ec.MarkLabel (end_label);
1239                                 return;
1240                         }
1241
1242                         left.Emit (ec);
1243                         ec.Emit (OpCodes.Dup);
1244
1245                         // Only to make verifier happy
1246                         if (left.Type.IsGenericParameter)
1247                                 ec.Emit (OpCodes.Box, left.Type);
1248
1249                         ec.Emit (OpCodes.Brtrue, end_label);
1250
1251                         ec.Emit (OpCodes.Pop);
1252                         right.Emit (ec);
1253
1254                         ec.MarkLabel (end_label);
1255                 }
1256
1257                 public override void FlowAnalysis (FlowAnalysisContext fc)
1258                 {
1259                         left.FlowAnalysis (fc);
1260                         var left_da = fc.BranchDefiniteAssignment ();
1261                         right.FlowAnalysis (fc);
1262                         fc.DefiniteAssignment = left_da;
1263                 }
1264
1265                 protected override void CloneTo (CloneContext clonectx, Expression t)
1266                 {
1267                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1268
1269                         target.left = left.Clone (clonectx);
1270                         target.right = right.Clone (clonectx);
1271                 }
1272                 
1273                 public override object Accept (StructuralVisitor visitor)
1274                 {
1275                         return visitor.Visit (this);
1276                 }
1277         }
1278
1279         class LiftedUnaryMutator : UnaryMutator
1280         {
1281                 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1282                         : base (mode, expr, loc)
1283                 {
1284                 }
1285
1286                 protected override Expression DoResolve (ResolveContext ec)
1287                 {
1288                         var orig_expr = expr;
1289
1290                         expr = Unwrap.Create (expr);
1291
1292                         var res = base.DoResolveOperation (ec);
1293
1294                         expr = orig_expr;
1295                         type = expr.Type;
1296
1297                         return res;
1298                 }
1299
1300                 protected override void EmitOperation (EmitContext ec)
1301                 {
1302                         Label is_null_label = ec.DefineLabel ();
1303                         Label end_label = ec.DefineLabel ();
1304
1305                         LocalTemporary lt = new LocalTemporary (type);
1306
1307                         // Value is on the stack
1308                         lt.Store (ec);
1309
1310                         var call = new CallEmitter ();
1311                         call.InstanceExpression = lt;
1312                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1313
1314                         ec.Emit (OpCodes.Brfalse, is_null_label);
1315
1316                         call = new CallEmitter ();
1317                         call.InstanceExpression = lt;
1318                         call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1319
1320                         lt.Release (ec);
1321
1322                         base.EmitOperation (ec);
1323
1324                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1325                         ec.Emit (OpCodes.Br_S, end_label);
1326
1327                         ec.MarkLabel (is_null_label);
1328                         LiftedNull.Create (type, loc).Emit (ec);
1329
1330                         ec.MarkLabel (end_label);
1331                 }
1332         }
1333 }
1334