[corlib] ParseNumber.StringToInt now check for overflows.
[mono.git] / mcs / mcs / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //   Marek Safar (marek.safar@gmail.com)
8 //
9 // Copyright 2001, 2002, 2003 Ximian, Inc.
10 // Copyright 2003, 2004 Novell, Inc.
11 // Copyright 2011 Xamarin Inc.
12 //
13
14 using System;
15 using System.Collections.Generic;
16
17 #if STATIC
18 using IKVM.Reflection.Emit;
19 #else
20 using System.Reflection.Emit;
21 #endif
22
23 namespace Mono.CSharp {
24         
25         public abstract class Statement {
26                 public Location loc;
27                 protected bool reachable;
28
29                 public bool IsUnreachable {
30                         get {
31                                 return !reachable;
32                         }
33                 }
34                 
35                 /// <summary>
36                 ///   Resolves the statement, true means that all sub-statements
37                 ///   did resolve ok.
38                 ///  </summary>
39                 public virtual bool Resolve (BlockContext bc)
40                 {
41                         return true;
42                 }
43
44                 /// <summary>
45                 ///   Return value indicates whether all code paths emitted return.
46                 /// </summary>
47                 protected abstract void DoEmit (EmitContext ec);
48
49                 public virtual void Emit (EmitContext ec)
50                 {
51                         ec.Mark (loc);
52                         DoEmit (ec);
53
54                         if (ec.StatementEpilogue != null) {
55                                 ec.EmitEpilogue ();
56                         }
57                 }
58
59                 //
60                 // This routine must be overrided in derived classes and make copies
61                 // of all the data that might be modified if resolved
62                 // 
63                 protected abstract void CloneTo (CloneContext clonectx, Statement target);
64
65                 public Statement Clone (CloneContext clonectx)
66                 {
67                         Statement s = (Statement) this.MemberwiseClone ();
68                         CloneTo (clonectx, s);
69                         return s;
70                 }
71
72                 public virtual Expression CreateExpressionTree (ResolveContext ec)
73                 {
74                         ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
75                         return null;
76                 }
77                 
78                 public virtual object Accept (StructuralVisitor visitor)
79                 {
80                         return visitor.Visit (this);
81                 }
82
83                 //
84                 // Return value indicates whether statement has unreachable end
85                 //
86                 protected abstract bool DoFlowAnalysis (FlowAnalysisContext fc);
87
88                 public bool FlowAnalysis (FlowAnalysisContext fc)
89                 {
90                         if (reachable) {
91                                 fc.UnreachableReported = false;
92                                 var res = DoFlowAnalysis (fc);
93                                 return res;
94                         }
95
96                         //
97                         // Special handling cases
98                         //
99                         if (this is Block) {
100                                 return DoFlowAnalysis (fc);
101                         }
102
103                         if (this is EmptyStatement || loc.IsNull)
104                                 return true;
105
106                         if (fc.UnreachableReported)
107                                 return true;
108
109                         fc.Report.Warning (162, 2, loc, "Unreachable code detected");
110                         fc.UnreachableReported = true;
111                         return true;
112                 }
113
114                 public virtual Reachability MarkReachable (Reachability rc)
115                 {
116                         if (!rc.IsUnreachable)
117                                 reachable = true;
118
119                         return rc;
120                 }
121
122                 protected void CheckExitBoundaries (BlockContext bc, Block scope)
123                 {
124                         if (bc.CurrentBlock.ParametersBlock.Original != scope.ParametersBlock.Original) {
125                                 bc.Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
126                                 return;
127                         }
128
129                         for (var b = bc.CurrentBlock; b != null && b != scope; b = b.Parent) {
130                                 if (b.IsFinallyBlock) {
131                                         Error_FinallyClauseExit (bc);
132                                         break;
133                                 }
134                         }
135                 }
136
137                 protected void Error_FinallyClauseExit (BlockContext bc)
138                 {
139                         bc.Report.Error (157, loc, "Control cannot leave the body of a finally clause");
140                 }
141         }
142
143         public sealed class EmptyStatement : Statement
144         {
145                 public EmptyStatement (Location loc)
146                 {
147                         this.loc = loc;
148                 }
149
150                 public override bool Resolve (BlockContext ec)
151                 {
152                         return true;
153                 }
154
155                 public override void Emit (EmitContext ec)
156                 {
157                 }
158
159                 protected override void DoEmit (EmitContext ec)
160                 {
161                         throw new NotSupportedException ();
162                 }
163
164                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
165                 {
166                         return false;
167                 }
168
169                 protected override void CloneTo (CloneContext clonectx, Statement target)
170                 {
171                         // nothing needed.
172                 }
173                 
174                 public override object Accept (StructuralVisitor visitor)
175                 {
176                         return visitor.Visit (this);
177                 }
178         }
179
180         public class If : Statement {
181                 Expression expr;
182                 public Statement TrueStatement;
183                 public Statement FalseStatement;
184
185                 bool true_returns, false_returns;
186
187                 public If (Expression bool_expr, Statement true_statement, Location l)
188                         : this (bool_expr, true_statement, null, l)
189                 {
190                 }
191
192                 public If (Expression bool_expr,
193                            Statement true_statement,
194                            Statement false_statement,
195                            Location l)
196                 {
197                         this.expr = bool_expr;
198                         TrueStatement = true_statement;
199                         FalseStatement = false_statement;
200                         loc = l;
201                 }
202
203                 public Expression Expr {
204                         get {
205                                 return this.expr;
206                         }
207                 }
208                 
209                 public override bool Resolve (BlockContext ec)
210                 {
211                         expr = expr.Resolve (ec);
212
213                         var ok = TrueStatement.Resolve (ec);
214
215                         if (FalseStatement != null) {
216                                 ok &= FalseStatement.Resolve (ec);
217                         }
218
219                         return ok;
220                 }
221                 
222                 protected override void DoEmit (EmitContext ec)
223                 {
224                         Label false_target = ec.DefineLabel ();
225                         Label end;
226
227                         //
228                         // If we're a boolean constant, Resolve() already
229                         // eliminated dead code for us.
230                         //
231                         Constant c = expr as Constant;
232                         if (c != null){
233                                 c.EmitSideEffect (ec);
234
235                                 if (!c.IsDefaultValue)
236                                         TrueStatement.Emit (ec);
237                                 else if (FalseStatement != null)
238                                         FalseStatement.Emit (ec);
239
240                                 return;
241                         }                       
242                         
243                         expr.EmitBranchable (ec, false_target, false);
244                         
245                         TrueStatement.Emit (ec);
246
247                         if (FalseStatement != null){
248                                 bool branch_emitted = false;
249                                 
250                                 end = ec.DefineLabel ();
251                                 if (!true_returns){
252                                         ec.Emit (OpCodes.Br, end);
253                                         branch_emitted = true;
254                                 }
255
256                                 ec.MarkLabel (false_target);
257                                 FalseStatement.Emit (ec);
258
259                                 if (branch_emitted)
260                                         ec.MarkLabel (end);
261                         } else {
262                                 ec.MarkLabel (false_target);
263                         }
264                 }
265
266                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
267                 {
268                         expr.FlowAnalysisConditional (fc);
269
270                         var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
271
272                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
273
274                         var res = TrueStatement.FlowAnalysis (fc);
275
276                         if (FalseStatement == null) {
277                                 var c = expr as Constant;
278                                 if (c != null && !c.IsDefaultValue)
279                                         return true_returns;
280
281                                 if (true_returns)
282                                         fc.DefiniteAssignment = da_false;
283                                 else
284                                         fc.DefiniteAssignment &= da_false;
285  
286                                 return false;
287                         }
288
289                         if (true_returns) {
290                                 fc.DefiniteAssignment = da_false;
291                                 return FalseStatement.FlowAnalysis (fc);
292                         }
293
294                         var da_true = fc.DefiniteAssignment;
295
296                         fc.DefiniteAssignment = da_false;
297                         res &= FalseStatement.FlowAnalysis (fc);
298
299                         if (!TrueStatement.IsUnreachable) {
300                                 if (false_returns || FalseStatement.IsUnreachable)
301                                         fc.DefiniteAssignment = da_true;
302                                 else
303                                         fc.DefiniteAssignment &= da_true;
304                         }
305
306                         return res;
307                 }
308
309                 public override Reachability MarkReachable (Reachability rc)
310                 {
311                         if (rc.IsUnreachable)
312                                 return rc;
313
314                         base.MarkReachable (rc);
315
316                         var c = expr as Constant;
317                         if (c != null) {
318                                 bool take = !c.IsDefaultValue;
319                                 if (take) {
320                                         rc = TrueStatement.MarkReachable (rc);
321                                 } else {
322                                         if (FalseStatement != null)
323                                                 rc = FalseStatement.MarkReachable (rc);
324                                 }
325
326                                 return rc;
327                         }
328
329                         var true_rc = TrueStatement.MarkReachable (rc);
330                         true_returns = true_rc.IsUnreachable;
331         
332                         if (FalseStatement == null)
333                                 return rc;
334
335                         var false_rc = FalseStatement.MarkReachable (rc);
336                         false_returns = false_rc.IsUnreachable;
337
338                         return true_rc & false_rc;
339                 }
340
341                 protected override void CloneTo (CloneContext clonectx, Statement t)
342                 {
343                         If target = (If) t;
344
345                         target.expr = expr.Clone (clonectx);
346                         target.TrueStatement = TrueStatement.Clone (clonectx);
347                         if (FalseStatement != null)
348                                 target.FalseStatement = FalseStatement.Clone (clonectx);
349                 }
350                 
351                 public override object Accept (StructuralVisitor visitor)
352                 {
353                         return visitor.Visit (this);
354                 }
355         }
356
357         public class Do : LoopStatement
358         {
359                 public Expression expr;
360                 bool iterator_reachable, end_reachable;
361
362                 public Do (Statement statement, BooleanExpression bool_expr, Location doLocation, Location whileLocation)
363                         : base (statement)
364                 {
365                         expr = bool_expr;
366                         loc = doLocation;
367                         WhileLocation = whileLocation;
368                 }
369
370                 public Location WhileLocation {
371                         get; private set;
372                 }
373
374                 public override bool Resolve (BlockContext bc)
375                 {
376                         var ok = base.Resolve (bc);
377
378                         expr = expr.Resolve (bc);
379
380                         return ok;
381                 }
382                 
383                 protected override void DoEmit (EmitContext ec)
384                 {
385                         Label loop = ec.DefineLabel ();
386                         Label old_begin = ec.LoopBegin;
387                         Label old_end = ec.LoopEnd;
388                         
389                         ec.LoopBegin = ec.DefineLabel ();
390                         ec.LoopEnd = ec.DefineLabel ();
391                                 
392                         ec.MarkLabel (loop);
393                         Statement.Emit (ec);
394                         ec.MarkLabel (ec.LoopBegin);
395
396                         // Mark start of while condition
397                         ec.Mark (WhileLocation);
398
399                         //
400                         // Dead code elimination
401                         //
402                         if (expr is Constant) {
403                                 bool res = !((Constant) expr).IsDefaultValue;
404
405                                 expr.EmitSideEffect (ec);
406                                 if (res)
407                                         ec.Emit (OpCodes.Br, loop);
408                         } else {
409                                 expr.EmitBranchable (ec, loop, true);
410                         }
411                         
412                         ec.MarkLabel (ec.LoopEnd);
413
414                         ec.LoopBegin = old_begin;
415                         ec.LoopEnd = old_end;
416                 }
417
418                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
419                 {
420                         var res = Statement.FlowAnalysis (fc);
421
422                         expr.FlowAnalysisConditional (fc);
423
424                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnFalse;
425
426                         if (res && !iterator_reachable)
427                                 return !end_reachable;
428
429                         if (!end_reachable) {
430                                 var c = expr as Constant;
431                                 if (c != null && !c.IsDefaultValue)
432                                         return true;
433                         }
434
435                         return false;
436                 }
437                 
438                 public override Reachability MarkReachable (Reachability rc)
439                 {
440                         base.MarkReachable (rc);
441                         
442                         var body_rc = Statement.MarkReachable (rc);
443
444                         if (body_rc.IsUnreachable && !iterator_reachable) {
445                                 expr = new UnreachableExpression (expr);
446                                 return end_reachable ? rc : Reachability.CreateUnreachable ();
447                         }
448
449                         if (!end_reachable) {
450                                 var c = expr as Constant;
451                                 if (c != null && !c.IsDefaultValue)
452                                         return Reachability.CreateUnreachable ();
453                         }
454
455                         return rc;
456                 }
457
458                 protected override void CloneTo (CloneContext clonectx, Statement t)
459                 {
460                         Do target = (Do) t;
461
462                         target.Statement = Statement.Clone (clonectx);
463                         target.expr = expr.Clone (clonectx);
464                 }
465                 
466                 public override object Accept (StructuralVisitor visitor)
467                 {
468                         return visitor.Visit (this);
469                 }
470
471                 public override void SetEndReachable ()
472                 {
473                         end_reachable = true;
474                 }
475
476                 public override void SetIteratorReachable ()
477                 {
478                         iterator_reachable = true;
479                 }
480         }
481
482         public class While : LoopStatement
483         {
484                 public Expression expr;
485                 bool empty, infinite, end_reachable;
486                 List<DefiniteAssignmentBitSet> end_reachable_das;
487
488                 public While (BooleanExpression bool_expr, Statement statement, Location l)
489                         : base (statement)
490                 {
491                         this.expr = bool_expr;
492                         loc = l;
493                 }
494
495                 public override bool Resolve (BlockContext bc)
496                 {
497                         bool ok = true;
498
499                         expr = expr.Resolve (bc);
500                         if (expr == null)
501                                 ok = false;
502
503                         var c = expr as Constant;
504                         if (c != null) {
505                                 empty = c.IsDefaultValue;
506                                 infinite = !empty;
507                         }
508
509                         ok &= base.Resolve (bc);
510                         return ok;
511                 }
512                 
513                 protected override void DoEmit (EmitContext ec)
514                 {
515                         if (empty) {
516                                 expr.EmitSideEffect (ec);
517                                 return;
518                         }
519
520                         Label old_begin = ec.LoopBegin;
521                         Label old_end = ec.LoopEnd;
522                         
523                         ec.LoopBegin = ec.DefineLabel ();
524                         ec.LoopEnd = ec.DefineLabel ();
525
526                         //
527                         // Inform whether we are infinite or not
528                         //
529                         if (expr is Constant) {
530                                 // expr is 'true', since the 'empty' case above handles the 'false' case
531                                 ec.MarkLabel (ec.LoopBegin);
532
533                                 if (ec.EmitAccurateDebugInfo)
534                                         ec.Emit (OpCodes.Nop);
535
536                                 expr.EmitSideEffect (ec);
537                                 Statement.Emit (ec);
538                                 ec.Emit (OpCodes.Br, ec.LoopBegin);
539                                         
540                                 //
541                                 // Inform that we are infinite (ie, `we return'), only
542                                 // if we do not `break' inside the code.
543                                 //
544                                 ec.MarkLabel (ec.LoopEnd);
545                         } else {
546                                 Label while_loop = ec.DefineLabel ();
547
548                                 ec.Emit (OpCodes.Br, ec.LoopBegin);
549                                 ec.MarkLabel (while_loop);
550
551                                 Statement.Emit (ec);
552                         
553                                 ec.MarkLabel (ec.LoopBegin);
554
555                                 ec.Mark (loc);
556                                 expr.EmitBranchable (ec, while_loop, true);
557                                 
558                                 ec.MarkLabel (ec.LoopEnd);
559                         }       
560
561                         ec.LoopBegin = old_begin;
562                         ec.LoopEnd = old_end;
563                 }
564
565                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
566                 {
567                         expr.FlowAnalysisConditional (fc);
568
569                         fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
570                         var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
571
572                         Statement.FlowAnalysis (fc);
573
574                         //
575                         // Special case infinite while with breaks
576                         //
577                         if (end_reachable_das != null) {
578                                 da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
579                                 end_reachable_das = null;
580                         }
581
582                         fc.DefiniteAssignment = da_false;
583
584                         if (infinite && !end_reachable)
585                                 return true;
586
587                         return false;
588                 }
589
590                 public override Reachability MarkReachable (Reachability rc)
591                 {
592                         if (rc.IsUnreachable)
593                                 return rc;
594
595                         base.MarkReachable (rc);
596
597                         //
598                         // Special case unreachable while body
599                         //
600                         if (empty) {
601                                 Statement.MarkReachable (Reachability.CreateUnreachable ());
602                                 return rc;
603                         }
604
605                         Statement.MarkReachable (rc);
606
607                         //
608                         // When infinite while end is unreachable via break anything what follows is unreachable too
609                         //
610                         if (infinite && !end_reachable)
611                                 return Reachability.CreateUnreachable ();
612
613                         return rc;
614                 }
615
616                 protected override void CloneTo (CloneContext clonectx, Statement t)
617                 {
618                         While target = (While) t;
619
620                         target.expr = expr.Clone (clonectx);
621                         target.Statement = Statement.Clone (clonectx);
622                 }
623                 
624                 public override object Accept (StructuralVisitor visitor)
625                 {
626                         return visitor.Visit (this);
627                 }
628
629                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
630                 {
631                         if (!infinite)
632                                 return;
633
634                         if (end_reachable_das == null)
635                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
636
637                         end_reachable_das.Add (fc.DefiniteAssignment);
638                 }
639
640                 public override void SetEndReachable ()
641                 {
642                         end_reachable = true;
643                 }
644         }
645
646         public class For : LoopStatement
647         {
648                 bool infinite, empty, iterator_reachable, end_reachable;
649                 List<DefiniteAssignmentBitSet> end_reachable_das;
650                 
651                 public For (Location l)
652                         : base (null)
653                 {
654                         loc = l;
655                 }
656
657                 public Statement Initializer {
658                         get; set;
659                 }
660
661                 public Expression Condition {
662                         get; set;
663                 }
664
665                 public Statement Iterator {
666                         get; set;
667                 }
668
669                 public override bool Resolve (BlockContext bc)
670                 {
671                         Initializer.Resolve (bc);
672
673                         if (Condition != null) {
674                                 Condition = Condition.Resolve (bc);
675                                 var condition_constant = Condition as Constant;
676                                 if (condition_constant != null) {
677                                         if (condition_constant.IsDefaultValue) {
678                                                 empty = true;
679                                         } else {
680                                                 infinite = true;
681                                         }
682                                 }
683                         } else {
684                                 infinite = true;
685                         }
686
687                         return base.Resolve (bc) && Iterator.Resolve (bc);
688                 }
689
690                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
691                 {
692                         Initializer.FlowAnalysis (fc);
693
694                         DefiniteAssignmentBitSet da_false;
695                         if (Condition != null) {
696                                 Condition.FlowAnalysisConditional (fc);
697                                 fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
698                                 da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
699                         } else {
700                                 da_false = fc.BranchDefiniteAssignment ();
701                         }
702
703                         Statement.FlowAnalysis (fc);
704
705                         Iterator.FlowAnalysis (fc);
706
707                         //
708                         // Special case infinite for with breaks
709                         //
710                         if (end_reachable_das != null) {
711                                 da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
712                                 end_reachable_das = null;
713                         }
714
715                         fc.DefiniteAssignment = da_false;
716
717                         if (infinite && !end_reachable)
718                                 return true;
719
720                         return false;
721                 }
722
723                 public override Reachability MarkReachable (Reachability rc)
724                 {
725                         base.MarkReachable (rc);
726
727                         Initializer.MarkReachable (rc);
728
729                         var body_rc = Statement.MarkReachable (rc);
730                         if (!body_rc.IsUnreachable || iterator_reachable) {
731                                 Iterator.MarkReachable (rc);
732                         }
733
734                         //
735                         // When infinite for end is unreachable via break anything what follows is unreachable too
736                         //
737                         if (infinite && !end_reachable) {
738                                 return Reachability.CreateUnreachable ();
739                         }
740
741                         return rc;
742                 }
743
744                 protected override void DoEmit (EmitContext ec)
745                 {
746                         if (Initializer != null)
747                                 Initializer.Emit (ec);
748
749                         if (empty) {
750                                 Condition.EmitSideEffect (ec);
751                                 return;
752                         }
753
754                         Label old_begin = ec.LoopBegin;
755                         Label old_end = ec.LoopEnd;
756                         Label loop = ec.DefineLabel ();
757                         Label test = ec.DefineLabel ();
758
759                         ec.LoopBegin = ec.DefineLabel ();
760                         ec.LoopEnd = ec.DefineLabel ();
761
762                         ec.Emit (OpCodes.Br, test);
763                         ec.MarkLabel (loop);
764                         Statement.Emit (ec);
765
766                         ec.MarkLabel (ec.LoopBegin);
767                         Iterator.Emit (ec);
768
769                         ec.MarkLabel (test);
770                         //
771                         // If test is null, there is no test, and we are just
772                         // an infinite loop
773                         //
774                         if (Condition != null) {
775                                 ec.Mark (Condition.Location);
776
777                                 //
778                                 // The Resolve code already catches the case for
779                                 // Test == Constant (false) so we know that
780                                 // this is true
781                                 //
782                                 if (Condition is Constant) {
783                                         Condition.EmitSideEffect (ec);
784                                         ec.Emit (OpCodes.Br, loop);
785                                 } else {
786                                         Condition.EmitBranchable (ec, loop, true);
787                                 }
788                                 
789                         } else
790                                 ec.Emit (OpCodes.Br, loop);
791                         ec.MarkLabel (ec.LoopEnd);
792
793                         ec.LoopBegin = old_begin;
794                         ec.LoopEnd = old_end;
795                 }
796
797                 protected override void CloneTo (CloneContext clonectx, Statement t)
798                 {
799                         For target = (For) t;
800
801                         if (Initializer != null)
802                                 target.Initializer = Initializer.Clone (clonectx);
803                         if (Condition != null)
804                                 target.Condition = Condition.Clone (clonectx);
805                         if (Iterator != null)
806                                 target.Iterator = Iterator.Clone (clonectx);
807                         target.Statement = Statement.Clone (clonectx);
808                 }
809
810                 public override object Accept (StructuralVisitor visitor)
811                 {
812                         return visitor.Visit (this);
813                 }
814
815                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
816                 {
817                         if (!infinite)
818                                 return;
819
820                         if (end_reachable_das == null)
821                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
822
823                         end_reachable_das.Add (fc.DefiniteAssignment);
824                 }
825
826                 public override void SetEndReachable ()
827                 {
828                         end_reachable = true;
829                 }
830
831                 public override void SetIteratorReachable ()
832                 {
833                         iterator_reachable = true;
834                 }
835         }
836
837         public abstract class LoopStatement : Statement
838         {
839                 protected LoopStatement (Statement statement)
840                 {
841                         Statement = statement;
842                 }
843
844                 public Statement Statement { get; set; }
845
846                 public override bool Resolve (BlockContext bc)
847                 {
848                         var prev_loop = bc.EnclosingLoop;
849                         var prev_los = bc.EnclosingLoopOrSwitch;
850                         bc.EnclosingLoopOrSwitch = bc.EnclosingLoop = this;
851                         var ok = Statement.Resolve (bc);
852                         bc.EnclosingLoopOrSwitch = prev_los;
853                         bc.EnclosingLoop = prev_loop;
854
855                         return ok;
856                 }
857
858                 //
859                 // Needed by possibly infinite loops statements (for, while) and switch statment
860                 //
861                 public virtual void AddEndDefiniteAssignment (FlowAnalysisContext fc)
862                 {
863                 }
864
865                 public virtual void SetEndReachable ()
866                 {
867                 }
868
869                 public virtual void SetIteratorReachable ()
870                 {
871                 }
872         }
873         
874         public class StatementExpression : Statement
875         {
876                 ExpressionStatement expr;
877                 
878                 public StatementExpression (ExpressionStatement expr)
879                 {
880                         this.expr = expr;
881                         loc = expr.StartLocation;
882                 }
883
884                 public StatementExpression (ExpressionStatement expr, Location loc)
885                 {
886                         this.expr = expr;
887                         this.loc = loc;
888                 }
889
890                 public ExpressionStatement Expr {
891                         get {
892                                 return this.expr;
893                         }
894                 }
895                 
896                 protected override void CloneTo (CloneContext clonectx, Statement t)
897                 {
898                         StatementExpression target = (StatementExpression) t;
899                         target.expr = (ExpressionStatement) expr.Clone (clonectx);
900                 }
901                 
902                 protected override void DoEmit (EmitContext ec)
903                 {
904                         expr.EmitStatement (ec);
905                 }
906
907                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
908                 {
909                         expr.FlowAnalysis (fc);
910                         return false;
911                 }
912
913                 public override Reachability MarkReachable (Reachability rc)
914                 {
915                         base.MarkReachable (rc);
916                         expr.MarkReachable (rc);
917                         return rc;
918                 }
919
920                 public override bool Resolve (BlockContext ec)
921                 {
922                         expr = expr.ResolveStatement (ec);
923                         return expr != null;
924                 }
925                 
926                 public override object Accept (StructuralVisitor visitor)
927                 {
928                         return visitor.Visit (this);
929                 }
930         }
931
932         public class StatementErrorExpression : Statement
933         {
934                 Expression expr;
935
936                 public StatementErrorExpression (Expression expr)
937                 {
938                         this.expr = expr;
939                         this.loc = expr.StartLocation;
940                 }
941
942                 public Expression Expr {
943                         get {
944                                 return expr;
945                         }
946                 }
947
948                 public override bool Resolve (BlockContext bc)
949                 {
950                         expr.Error_InvalidExpressionStatement (bc);
951                         return true;
952                 }
953
954                 protected override void DoEmit (EmitContext ec)
955                 {
956                         throw new NotSupportedException ();
957                 }
958
959                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
960                 {
961                         return false;
962                 }
963
964                 protected override void CloneTo (CloneContext clonectx, Statement target)
965                 {
966                         var t = (StatementErrorExpression) target;
967
968                         t.expr = expr.Clone (clonectx);
969                 }
970                 
971                 public override object Accept (StructuralVisitor visitor)
972                 {
973                         return visitor.Visit (this);
974                 }
975         }
976
977         //
978         // Simple version of statement list not requiring a block
979         //
980         public class StatementList : Statement
981         {
982                 List<Statement> statements;
983
984                 public StatementList (Statement first, Statement second)
985                 {
986                         statements = new List<Statement> { first, second };
987                 }
988
989                 #region Properties
990                 public IList<Statement> Statements {
991                         get {
992                                 return statements;
993                         }
994                 }
995                 #endregion
996
997                 public void Add (Statement statement)
998                 {
999                         statements.Add (statement);
1000                 }
1001
1002                 public override bool Resolve (BlockContext ec)
1003                 {
1004                         foreach (var s in statements)
1005                                 s.Resolve (ec);
1006
1007                         return true;
1008                 }
1009
1010                 protected override void DoEmit (EmitContext ec)
1011                 {
1012                         foreach (var s in statements)
1013                                 s.Emit (ec);
1014                 }
1015
1016                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1017                 {
1018                         foreach (var s in statements)
1019                                 s.FlowAnalysis (fc);
1020
1021                         return false;
1022                 }
1023
1024                 public override Reachability MarkReachable (Reachability rc)
1025                 {
1026                         base.MarkReachable (rc);
1027
1028                         Reachability res = rc;
1029                         foreach (var s in statements)
1030                                 res = s.MarkReachable (rc);
1031
1032                         return res;
1033                 }
1034
1035                 protected override void CloneTo (CloneContext clonectx, Statement target)
1036                 {
1037                         StatementList t = (StatementList) target;
1038
1039                         t.statements = new List<Statement> (statements.Count);
1040                         foreach (Statement s in statements)
1041                                 t.statements.Add (s.Clone (clonectx));
1042                 }
1043                 
1044                 public override object Accept (StructuralVisitor visitor)
1045                 {
1046                         return visitor.Visit (this);
1047                 }
1048         }
1049
1050         //
1051         // For statements which require special handling when inside try or catch block
1052         //
1053         public abstract class ExitStatement : Statement
1054         {
1055                 protected bool unwind_protect;
1056
1057                 protected abstract bool DoResolve (BlockContext bc);
1058                 protected abstract bool IsLocalExit { get; }
1059
1060                 public override bool Resolve (BlockContext bc)
1061                 {
1062                         var res = DoResolve (bc);
1063
1064                         if (!IsLocalExit) {
1065                                 //
1066                                 // We are inside finally scope but is it the scope we are exiting
1067                                 //
1068                                 if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
1069
1070                                         for (var b = bc.CurrentBlock; b != null; b = b.Parent) {
1071                                                 if (b.IsFinallyBlock) {
1072                                                         Error_FinallyClauseExit (bc);
1073                                                         break;
1074                                                 }
1075
1076                                                 if (b is ParametersBlock)
1077                                                         break;
1078                                         }
1079                                 }
1080                         }
1081
1082                         unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
1083                         return res;
1084                 }
1085
1086                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1087                 {
1088                         if (IsLocalExit)
1089                                 return true;
1090
1091                         if (fc.TryFinally != null) {
1092                             fc.TryFinally.RegisterForControlExitCheck (new DefiniteAssignmentBitSet (fc.DefiniteAssignment));
1093                         } else {
1094                             fc.ParametersBlock.CheckControlExit (fc);
1095                         }
1096
1097                         return true;
1098                 }
1099         }
1100
1101         /// <summary>
1102         ///   Implements the return statement
1103         /// </summary>
1104         public class Return : ExitStatement
1105         {
1106                 Expression expr;
1107
1108                 public Return (Expression expr, Location l)
1109                 {
1110                         this.expr = expr;
1111                         loc = l;
1112                 }
1113
1114                 #region Properties
1115
1116                 public Expression Expr {
1117                         get {
1118                                 return expr;
1119                         }
1120                         protected set {
1121                                 expr = value;
1122                         }
1123                 }
1124
1125                 protected override bool IsLocalExit {
1126                         get {
1127                                 return false;
1128                         }
1129                 }
1130
1131                 #endregion
1132
1133                 protected override bool DoResolve (BlockContext ec)
1134                 {
1135                         var block_return_type = ec.ReturnType;
1136
1137                         if (expr == null) {
1138                                 if (block_return_type.Kind == MemberKind.Void || block_return_type == InternalType.ErrorType)
1139                                         return true;
1140
1141                                 //
1142                                 // Return must not be followed by an expression when
1143                                 // the method return type is Task
1144                                 //
1145                                 if (ec.CurrentAnonymousMethod is AsyncInitializer) {
1146                                         var storey = (AsyncTaskStorey) ec.CurrentAnonymousMethod.Storey;
1147                                         if (storey.ReturnType == ec.Module.PredefinedTypes.Task.TypeSpec) {
1148                                                 //
1149                                                 // Extra trick not to emit ret/leave inside awaiter body
1150                                                 //
1151                                                 expr = EmptyExpression.Null;
1152                                                 return true;
1153                                         }
1154
1155                                         if (storey.ReturnType.IsGenericTask)
1156                                                 block_return_type = storey.ReturnType.TypeArguments[0];
1157                                 }
1158
1159                                 if (ec.CurrentIterator != null) {
1160                                         Error_ReturnFromIterator (ec);
1161                                 } else if (block_return_type != InternalType.ErrorType) {
1162                                         ec.Report.Error (126, loc,
1163                                                 "An object of a type convertible to `{0}' is required for the return statement",
1164                                                 block_return_type.GetSignatureForError ());
1165                                 }
1166
1167                                 return false;
1168                         }
1169
1170                         expr = expr.Resolve (ec);
1171
1172                         AnonymousExpression am = ec.CurrentAnonymousMethod;
1173                         if (am == null) {
1174                                 if (block_return_type.Kind == MemberKind.Void) {
1175                                         ec.Report.Error (127, loc,
1176                                                 "`{0}': A return keyword must not be followed by any expression when method returns void",
1177                                                 ec.GetSignatureForError ());
1178
1179                                         return false;
1180                                 }
1181                         } else {
1182                                 if (am.IsIterator) {
1183                                         Error_ReturnFromIterator (ec);
1184                                         return false;
1185                                 }
1186
1187                                 var async_block = am as AsyncInitializer;
1188                                 if (async_block != null) {
1189                                         if (expr != null) {
1190                                                 var storey = (AsyncTaskStorey) am.Storey;
1191                                                 var async_type = storey.ReturnType;
1192
1193                                                 if (async_type == null && async_block.ReturnTypeInference != null) {
1194                                                         if (expr.Type.Kind == MemberKind.Void && !(this is ContextualReturn))
1195                                                                 ec.Report.Error (4029, loc, "Cannot return an expression of type `void'");
1196                                                         else
1197                                                                 async_block.ReturnTypeInference.AddCommonTypeBoundAsync (expr.Type);
1198                                                         return true;
1199                                                 }
1200
1201                                                 if (async_type.Kind == MemberKind.Void) {
1202                                                         ec.Report.Error (8030, loc,
1203                                                                 "Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
1204                                                         return false;
1205                                                 }
1206
1207                                                 if (!async_type.IsGenericTask) {
1208                                                         if (this is ContextualReturn)
1209                                                                 return true;
1210
1211                                                         if (async_block.DelegateType != null) {
1212                                                                 ec.Report.Error (8031, loc,
1213                                                                         "Async lambda expression or anonymous method converted to a `Task' cannot return a value. Consider returning `Task<T>'");
1214                                                         } else {
1215                                                                 ec.Report.Error (1997, loc,
1216                                                                         "`{0}': A return keyword must not be followed by an expression when async method returns `Task'. Consider using `Task<T>' return type",
1217                                                                         ec.GetSignatureForError ());
1218                                                         }
1219                                                         return false;
1220                                                 }
1221
1222                                                 //
1223                                                 // The return type is actually Task<T> type argument
1224                                                 //
1225                                                 if (expr.Type == async_type) {
1226                                                         ec.Report.Error (4016, loc,
1227                                                                 "`{0}': The return expression type of async method must be `{1}' rather than `Task<{1}>'",
1228                                                                 ec.GetSignatureForError (), async_type.TypeArguments[0].GetSignatureForError ());
1229                                                 } else {
1230                                                         block_return_type = async_type.TypeArguments[0];
1231                                                 }
1232                                         }
1233                                 } else {
1234                                         if (block_return_type.Kind == MemberKind.Void) {
1235                                                 ec.Report.Error (8030, loc,
1236                                                         "Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
1237                                                 return false;
1238                                         }
1239
1240                                         var l = am as AnonymousMethodBody;
1241                                         if (l != null && expr != null) {
1242                                                 if (l.ReturnTypeInference != null) {
1243                                                         l.ReturnTypeInference.AddCommonTypeBound (expr.Type);
1244                                                         return true;
1245                                                 }
1246
1247                                                 //
1248                                                 // Try to optimize simple lambda. Only when optimizations are enabled not to cause
1249                                                 // unexpected debugging experience
1250                                                 //
1251                                                 if (this is ContextualReturn && !ec.IsInProbingMode && ec.Module.Compiler.Settings.Optimize) {
1252                                                         l.DirectMethodGroupConversion = expr.CanReduceLambda (l);
1253                                                 }
1254                                         }
1255                                 }
1256                         }
1257
1258                         if (expr == null)
1259                                 return false;
1260
1261                         if (expr.Type != block_return_type && expr.Type != InternalType.ErrorType) {
1262                                 expr = Convert.ImplicitConversionRequired (ec, expr, block_return_type, loc);
1263
1264                                 if (expr == null) {
1265                                         if (am != null && block_return_type == ec.ReturnType) {
1266                                                 ec.Report.Error (1662, loc,
1267                                                         "Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
1268                                                         am.ContainerType, am.GetSignatureForError ());
1269                                         }
1270                                         return false;
1271                                 }
1272                         }
1273
1274                         return true;                    
1275                 }
1276                 
1277                 protected override void DoEmit (EmitContext ec)
1278                 {
1279                         if (expr != null) {
1280
1281                                 var async_body = ec.CurrentAnonymousMethod as AsyncInitializer;
1282                                 if (async_body != null) {
1283                                         var storey = (AsyncTaskStorey)async_body.Storey;
1284                                         Label exit_label = async_body.BodyEnd;
1285
1286                                         //
1287                                         // It's null for await without async
1288                                         //
1289                                         if (storey.HoistedReturnValue != null) {
1290                                                 //
1291                                                 // Special case hoisted return value (happens in try/finally scenario)
1292                                                 //
1293                                                 if (ec.TryFinallyUnwind != null) {
1294                                                         if (storey.HoistedReturnValue is VariableReference) {
1295                                                                 storey.HoistedReturnValue = ec.GetTemporaryField (storey.HoistedReturnValue.Type);
1296                                                         }
1297
1298                                                         exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
1299                                                 }
1300
1301                                                 var async_return = (IAssignMethod)storey.HoistedReturnValue;
1302                                                 async_return.EmitAssign (ec, expr, false, false);
1303                                                 ec.EmitEpilogue ();
1304                                         } else {
1305                                                 expr.Emit (ec);
1306
1307                                                 if (ec.TryFinallyUnwind != null)
1308                                                         exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
1309                                         }
1310
1311                                         ec.Emit (OpCodes.Leave, exit_label);
1312                                         return;
1313                                 }
1314
1315                                 expr.Emit (ec);
1316                                 ec.EmitEpilogue ();
1317
1318                                 if (unwind_protect || ec.EmitAccurateDebugInfo)
1319                                         ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
1320                         }
1321
1322                         if (unwind_protect) {
1323                                 ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
1324                         } else if (ec.EmitAccurateDebugInfo) {
1325                                 ec.Emit (OpCodes.Br, ec.CreateReturnLabel ());
1326                         } else {
1327                                 ec.Emit (OpCodes.Ret);
1328                         }
1329                 }
1330
1331                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1332                 {
1333                         if (expr != null)
1334                                 expr.FlowAnalysis (fc);
1335
1336                         base.DoFlowAnalysis (fc);
1337                         return true;
1338                 }
1339
1340                 void Error_ReturnFromIterator (ResolveContext rc)
1341                 {
1342                         rc.Report.Error (1622, loc,
1343                                 "Cannot return a value from iterators. Use the yield return statement to return a value, or yield break to end the iteration");
1344                 }
1345
1346                 public override Reachability MarkReachable (Reachability rc)
1347                 {
1348                         base.MarkReachable (rc);
1349                         return Reachability.CreateUnreachable ();
1350                 }
1351
1352                 protected override void CloneTo (CloneContext clonectx, Statement t)
1353                 {
1354                         Return target = (Return) t;
1355                         // It's null for simple return;
1356                         if (expr != null)
1357                                 target.expr = expr.Clone (clonectx);
1358                 }
1359
1360                 public override object Accept (StructuralVisitor visitor)
1361                 {
1362                         return visitor.Visit (this);
1363                 }
1364         }
1365
1366         public class Goto : ExitStatement
1367         {
1368                 string target;
1369                 LabeledStatement label;
1370                 TryFinally try_finally;
1371
1372                 public Goto (string label, Location l)
1373                 {
1374                         loc = l;
1375                         target = label;
1376                 }
1377
1378                 public string Target {
1379                         get { return target; }
1380                 }
1381
1382                 protected override bool IsLocalExit {
1383                         get {
1384                                 return true;
1385                         }
1386                 }
1387
1388                 protected override bool DoResolve (BlockContext bc)
1389                 {
1390                         label = bc.CurrentBlock.LookupLabel (target);
1391                         if (label == null) {
1392                                 Error_UnknownLabel (bc, target, loc);
1393                                 return false;
1394                         }
1395
1396                         try_finally = bc.CurrentTryBlock as TryFinally;
1397
1398                         CheckExitBoundaries (bc, label.Block);
1399
1400                         return true;
1401                 }
1402
1403                 public static void Error_UnknownLabel (BlockContext bc, string label, Location loc)
1404                 {
1405                         bc.Report.Error (159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
1406                                 label);
1407                 }
1408
1409                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1410                 {
1411                         if (fc.AddReachedLabel (label))
1412                                 return true;
1413
1414                         label.Block.ScanGotoJump (label, fc);
1415                         return true;
1416                 }
1417
1418                 public override Reachability MarkReachable (Reachability rc)
1419                 {
1420                         if (rc.IsUnreachable)
1421                                 return rc;
1422
1423                         base.MarkReachable (rc);
1424
1425                         if (try_finally != null) {
1426                                 if (try_finally.FinallyBlock.HasReachableClosingBrace) {
1427                                         label.AddGotoReference (rc, false);
1428                                 } else {
1429                                         label.AddGotoReference (rc, true);
1430                                 }
1431                         } else {
1432                                 label.AddGotoReference (rc, false);
1433                         }
1434
1435                         return Reachability.CreateUnreachable ();
1436                 }
1437
1438                 protected override void CloneTo (CloneContext clonectx, Statement target)
1439                 {
1440                         // Nothing to clone
1441                 }
1442
1443                 protected override void DoEmit (EmitContext ec)
1444                 {
1445                         if (label == null)
1446                                 throw new InternalErrorException ("goto emitted before target resolved");
1447
1448                         Label l = label.LabelTarget (ec);
1449
1450                         if (ec.TryFinallyUnwind != null && IsLeavingFinally (label.Block)) {
1451                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1452                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, label.Block);
1453                         }
1454
1455                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1456                 }
1457
1458                 bool IsLeavingFinally (Block labelBlock)
1459                 {
1460                         var b = try_finally.Statement as Block;
1461                         while (b != null) {
1462                                 if (b == labelBlock)
1463                                         return true;
1464
1465                                 b = b.Parent;
1466                         }
1467
1468                         return false;
1469                 }
1470                 
1471                 public override object Accept (StructuralVisitor visitor)
1472                 {
1473                         return visitor.Visit (this);
1474                 }
1475         }
1476
1477         public class LabeledStatement : Statement {
1478                 string name;
1479                 bool defined;
1480                 bool referenced;
1481                 bool finalTarget;
1482                 Label label;
1483                 Block block;
1484                 
1485                 public LabeledStatement (string name, Block block, Location l)
1486                 {
1487                         this.name = name;
1488                         this.block = block;
1489                         this.loc = l;
1490                 }
1491
1492                 public Label LabelTarget (EmitContext ec)
1493                 {
1494                         if (defined)
1495                                 return label;
1496
1497                         label = ec.DefineLabel ();
1498                         defined = true;
1499                         return label;
1500                 }
1501
1502                 public Block Block {
1503                         get {
1504                                 return block;
1505                         }
1506                 }
1507
1508                 public string Name {
1509                         get { return name; }
1510                 }
1511
1512                 protected override void CloneTo (CloneContext clonectx, Statement target)
1513                 {
1514                         var t = (LabeledStatement) target;
1515
1516                         t.block = clonectx.RemapBlockCopy (block);
1517                 }
1518
1519                 public override bool Resolve (BlockContext bc)
1520                 {
1521                         return true;
1522                 }
1523
1524                 protected override void DoEmit (EmitContext ec)
1525                 {
1526                         LabelTarget (ec);
1527                         ec.MarkLabel (label);
1528
1529                         if (finalTarget)
1530                                 ec.Emit (OpCodes.Br_S, label);
1531                 }
1532
1533                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1534                 {
1535                         if (!referenced) {
1536                                 fc.Report.Warning (164, 2, loc, "This label has not been referenced");
1537                         }
1538
1539                         return false;
1540                 }
1541
1542                 public override Reachability MarkReachable (Reachability rc)
1543                 {
1544                         base.MarkReachable (rc);
1545
1546                         if (referenced)
1547                                 rc = new Reachability ();
1548
1549                         return rc;
1550                 }
1551
1552                 public void AddGotoReference (Reachability rc, bool finalTarget)
1553                 {
1554                         if (referenced)
1555                                 return;
1556
1557                         referenced = true;
1558                         MarkReachable (rc);
1559
1560                         //
1561                         // Label is final target when goto jumps out of try block with
1562                         // finally clause. In that case we need leave with target but in C#
1563                         // terms the label is unreachable. Using finalTarget we emit
1564                         // explicit label not just marker
1565                         //
1566                         if (finalTarget) {
1567                                 this.finalTarget = true;
1568                                 return;
1569                         }
1570
1571                         block.ScanGotoJump (this);
1572                 }
1573
1574                 public override object Accept (StructuralVisitor visitor)
1575                 {
1576                         return visitor.Visit (this);
1577                 }
1578         }
1579         
1580
1581         /// <summary>
1582         ///   `goto default' statement
1583         /// </summary>
1584         public class GotoDefault : SwitchGoto
1585         {               
1586                 public GotoDefault (Location l)
1587                         : base (l)
1588                 {
1589                 }
1590
1591                 public override bool Resolve (BlockContext bc)
1592                 {
1593                         if (bc.Switch == null) {
1594                                 Error_GotoCaseRequiresSwitchBlock (bc);
1595                                 return false;
1596                         }
1597
1598                         bc.Switch.RegisterGotoCase (null, null);
1599                         base.Resolve (bc);
1600
1601                         return true;
1602                 }
1603
1604                 protected override void DoEmit (EmitContext ec)
1605                 {
1606                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.Switch.DefaultLabel.GetILLabel (ec));
1607                 }
1608
1609                 public override Reachability MarkReachable (Reachability rc)
1610                 {
1611                         if (!rc.IsUnreachable) {
1612                                 var label = switch_statement.DefaultLabel;
1613                                 if (label.IsUnreachable) {
1614                                         label.MarkReachable (rc);
1615                                         switch_statement.Block.ScanGotoJump (label);
1616                                 }
1617                         }
1618
1619                         return base.MarkReachable (rc);
1620                 }
1621
1622                 public override object Accept (StructuralVisitor visitor)
1623                 {
1624                         return visitor.Visit (this);
1625                 }
1626         }
1627
1628         /// <summary>
1629         ///   `goto case' statement
1630         /// </summary>
1631         public class GotoCase : SwitchGoto
1632         {
1633                 Expression expr;
1634                 
1635                 public GotoCase (Expression e, Location l)
1636                         : base (l)
1637                 {
1638                         expr = e;
1639                 }
1640
1641                 public Expression Expr {
1642                         get {
1643                                 return expr;
1644                         }
1645                 }
1646
1647                 public SwitchLabel Label { get; set; }
1648
1649                 public override bool Resolve (BlockContext ec)
1650                 {
1651                         if (ec.Switch == null) {
1652                                 Error_GotoCaseRequiresSwitchBlock (ec);
1653                                 return false;
1654                         }
1655
1656                         Constant c = expr.ResolveLabelConstant (ec);
1657                         if (c == null) {
1658                                 return false;
1659                         }
1660
1661                         Constant res;
1662                         if (ec.Switch.IsNullable && c is NullLiteral) {
1663                                 res = c;
1664                         } else {
1665                                 TypeSpec type = ec.Switch.SwitchType;
1666                                 res = c.Reduce (ec, type);
1667                                 if (res == null) {
1668                                         c.Error_ValueCannotBeConverted (ec, type, true);
1669                                         return false;
1670                                 }
1671
1672                                 if (!Convert.ImplicitStandardConversionExists (c, type))
1673                                         ec.Report.Warning (469, 2, loc,
1674                                                 "The `goto case' value is not implicitly convertible to type `{0}'",
1675                                                 type.GetSignatureForError ());
1676
1677                         }
1678
1679                         ec.Switch.RegisterGotoCase (this, res);
1680                         base.Resolve (ec);
1681                         expr = res;
1682
1683                         return true;
1684                 }
1685
1686                 protected override void DoEmit (EmitContext ec)
1687                 {
1688                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, Label.GetILLabel (ec));
1689                 }
1690
1691                 protected override void CloneTo (CloneContext clonectx, Statement t)
1692                 {
1693                         GotoCase target = (GotoCase) t;
1694
1695                         target.expr = expr.Clone (clonectx);
1696                 }
1697
1698                 public override Reachability MarkReachable (Reachability rc)
1699                 {
1700                         if (!rc.IsUnreachable) {
1701                                 var label = switch_statement.FindLabel ((Constant) expr);
1702                                 if (label.IsUnreachable) {
1703                                         label.MarkReachable (rc);
1704                                         switch_statement.Block.ScanGotoJump (label);
1705                                 }
1706                         }
1707
1708                         return base.MarkReachable (rc);
1709                 }
1710                 
1711                 public override object Accept (StructuralVisitor visitor)
1712                 {
1713                         return visitor.Visit (this);
1714                 }
1715         }
1716
1717         public abstract class SwitchGoto : Statement
1718         {
1719                 protected bool unwind_protect;
1720                 protected Switch switch_statement;
1721
1722                 protected SwitchGoto (Location loc)
1723                 {
1724                         this.loc = loc;
1725                 }
1726
1727                 protected override void CloneTo (CloneContext clonectx, Statement target)
1728                 {
1729                         // Nothing to clone
1730                 }
1731
1732                 public override bool Resolve (BlockContext bc)
1733                 {
1734                         CheckExitBoundaries (bc, bc.Switch.Block);
1735
1736                         unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
1737                         switch_statement = bc.Switch;
1738
1739                         return true;
1740                 }
1741
1742                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1743                 {
1744                         return true;
1745                 }
1746
1747                 public override Reachability MarkReachable (Reachability rc)
1748                 {
1749                         base.MarkReachable (rc);
1750                         return Reachability.CreateUnreachable ();
1751                 }
1752
1753                 protected void Error_GotoCaseRequiresSwitchBlock (BlockContext bc)
1754                 {
1755                         bc.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
1756                 }
1757         }
1758         
1759         public class Throw : Statement {
1760                 Expression expr;
1761                 
1762                 public Throw (Expression expr, Location l)
1763                 {
1764                         this.expr = expr;
1765                         loc = l;
1766                 }
1767
1768                 public Expression Expr {
1769                         get {
1770                                 return this.expr;
1771                         }
1772                 }
1773
1774                 public override bool Resolve (BlockContext ec)
1775                 {
1776                         if (expr == null) {
1777                                 if (!ec.HasSet (ResolveContext.Options.CatchScope)) {
1778                                         ec.Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
1779                                 } else if (ec.HasSet (ResolveContext.Options.FinallyScope)) {
1780                                         for (var b = ec.CurrentBlock; b != null && !b.IsCatchBlock; b = b.Parent) {
1781                                                 if (b.IsFinallyBlock) {
1782                                                         ec.Report.Error (724, loc,
1783                                                                 "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1784                                                         break;
1785                                                 }
1786                                         }
1787                                 }
1788
1789                                 return true;
1790                         }
1791
1792                         expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
1793
1794                         if (expr == null)
1795                                 return false;
1796
1797                         var et = ec.BuiltinTypes.Exception;
1798                         if (Convert.ImplicitConversionExists (ec, expr, et))
1799                                 expr = Convert.ImplicitConversion (ec, expr, et, loc);
1800                         else
1801                                 ec.Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
1802
1803                         return true;
1804                 }
1805                         
1806                 protected override void DoEmit (EmitContext ec)
1807                 {
1808                         if (expr == null) {
1809                                 var atv = ec.AsyncThrowVariable;
1810                                 if (atv != null) {
1811                                         if (atv.HoistedVariant != null) {
1812                                                 atv.HoistedVariant.Emit (ec);
1813                                         } else {
1814                                                 atv.Emit (ec);
1815                                         }
1816
1817                                         ec.Emit (OpCodes.Throw);
1818                                 } else {
1819                                         ec.Emit (OpCodes.Rethrow);
1820                                 }
1821                         } else {
1822                                 expr.Emit (ec);
1823
1824                                 ec.Emit (OpCodes.Throw);
1825                         }
1826                 }
1827
1828                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1829                 {
1830                         if (expr != null)
1831                                 expr.FlowAnalysis (fc);
1832
1833                         return true;
1834                 }
1835
1836                 public override Reachability MarkReachable (Reachability rc)
1837                 {
1838                         base.MarkReachable (rc);
1839                         return Reachability.CreateUnreachable ();
1840                 }
1841
1842                 protected override void CloneTo (CloneContext clonectx, Statement t)
1843                 {
1844                         Throw target = (Throw) t;
1845
1846                         if (expr != null)
1847                                 target.expr = expr.Clone (clonectx);
1848                 }
1849                 
1850                 public override object Accept (StructuralVisitor visitor)
1851                 {
1852                         return visitor.Visit (this);
1853                 }
1854         }
1855
1856         public class Break : LocalExitStatement
1857         {               
1858                 public Break (Location l)
1859                         : base (l)
1860                 {
1861                 }
1862                 
1863                 public override object Accept (StructuralVisitor visitor)
1864                 {
1865                         return visitor.Visit (this);
1866                 }
1867
1868                 protected override void DoEmit (EmitContext ec)
1869                 {
1870                         var l = ec.LoopEnd;
1871
1872                         if (ec.TryFinallyUnwind != null) {
1873                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1874                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
1875                         }
1876
1877                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1878                 }
1879
1880                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1881                 {
1882                         enclosing_loop.AddEndDefiniteAssignment (fc);
1883                         return true;
1884                 }
1885
1886                 protected override bool DoResolve (BlockContext bc)
1887                 {
1888                         enclosing_loop = bc.EnclosingLoopOrSwitch;
1889                         return base.DoResolve (bc);
1890                 }
1891
1892                 public override Reachability MarkReachable (Reachability rc)
1893                 {
1894                         base.MarkReachable (rc);
1895
1896                         if (!rc.IsUnreachable)
1897                                 enclosing_loop.SetEndReachable ();
1898
1899                         return Reachability.CreateUnreachable ();
1900                 }
1901         }
1902
1903         public class Continue : LocalExitStatement
1904         {               
1905                 public Continue (Location l)
1906                         : base (l)
1907                 {
1908                 }
1909
1910                 public override object Accept (StructuralVisitor visitor)
1911                 {
1912                         return visitor.Visit (this);
1913                 }
1914
1915
1916                 protected override void DoEmit (EmitContext ec)
1917                 {
1918                         var l = ec.LoopBegin;
1919
1920                         if (ec.TryFinallyUnwind != null) {
1921                                 var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
1922                                 l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
1923                         }
1924
1925                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
1926                 }
1927
1928                 protected override bool DoResolve (BlockContext bc)
1929                 {
1930                         enclosing_loop = bc.EnclosingLoop;
1931                         return base.DoResolve (bc);
1932                 }
1933
1934                 public override Reachability MarkReachable (Reachability rc)
1935                 {
1936                         base.MarkReachable (rc);
1937
1938                         if (!rc.IsUnreachable)
1939                                 enclosing_loop.SetIteratorReachable ();
1940
1941                         return Reachability.CreateUnreachable ();
1942                 }
1943         }
1944
1945         public abstract class LocalExitStatement : ExitStatement
1946         {
1947                 protected LoopStatement enclosing_loop;
1948
1949                 protected LocalExitStatement (Location loc)
1950                 {
1951                         this.loc = loc;
1952                 }
1953
1954                 protected override bool IsLocalExit {
1955                         get {
1956                                 return true;
1957                         }
1958                 }
1959
1960                 protected override void CloneTo (CloneContext clonectx, Statement t)
1961                 {
1962                         // nothing needed.
1963                 }
1964
1965                 protected override bool DoResolve (BlockContext bc)
1966                 {
1967                         if (enclosing_loop == null) {
1968                                 bc.Report.Error (139, loc, "No enclosing loop out of which to break or continue");
1969                                 return false;
1970                         }
1971
1972                         var block = enclosing_loop.Statement as Block;
1973
1974                         // Don't need to do extra checks for simple statements loops
1975                         if (block != null) {
1976                                 CheckExitBoundaries (bc, block);
1977                         }
1978
1979                         return true;
1980                 }
1981         }
1982
1983         public interface ILocalVariable
1984         {
1985                 void Emit (EmitContext ec);
1986                 void EmitAssign (EmitContext ec);
1987                 void EmitAddressOf (EmitContext ec);
1988         }
1989
1990         public interface INamedBlockVariable
1991         {
1992                 Block Block { get; }
1993                 Expression CreateReferenceExpression (ResolveContext rc, Location loc);
1994                 bool IsDeclared { get; }
1995                 bool IsParameter { get; }
1996                 Location Location { get; }
1997         }
1998
1999         public class BlockVariableDeclarator
2000         {
2001                 LocalVariable li;
2002                 Expression initializer;
2003
2004                 public BlockVariableDeclarator (LocalVariable li, Expression initializer)
2005                 {
2006                         if (li.Type != null)
2007                                 throw new ArgumentException ("Expected null variable type");
2008
2009                         this.li = li;
2010                         this.initializer = initializer;
2011                 }
2012
2013                 #region Properties
2014
2015                 public LocalVariable Variable {
2016                         get {
2017                                 return li;
2018                         }
2019                 }
2020
2021                 public Expression Initializer {
2022                         get {
2023                                 return initializer;
2024                         }
2025                         set {
2026                                 initializer = value;
2027                         }
2028                 }
2029
2030                 #endregion
2031
2032                 public virtual BlockVariableDeclarator Clone (CloneContext cloneCtx)
2033                 {
2034                         var t = (BlockVariableDeclarator) MemberwiseClone ();
2035                         if (initializer != null)
2036                                 t.initializer = initializer.Clone (cloneCtx);
2037
2038                         return t;
2039                 }
2040         }
2041
2042         public class BlockVariable : Statement
2043         {
2044                 Expression initializer;
2045                 protected FullNamedExpression type_expr;
2046                 protected LocalVariable li;
2047                 protected List<BlockVariableDeclarator> declarators;
2048                 TypeSpec type;
2049
2050                 public BlockVariable (FullNamedExpression type, LocalVariable li)
2051                 {
2052                         this.type_expr = type;
2053                         this.li = li;
2054                         this.loc = type_expr.Location;
2055                 }
2056
2057                 protected BlockVariable (LocalVariable li)
2058                 {
2059                         this.li = li;
2060                 }
2061
2062                 #region Properties
2063
2064                 public List<BlockVariableDeclarator> Declarators {
2065                         get {
2066                                 return declarators;
2067                         }
2068                 }
2069
2070                 public Expression Initializer {
2071                         get {
2072                                 return initializer;
2073                         }
2074                         set {
2075                                 initializer = value;
2076                         }
2077                 }
2078
2079                 public FullNamedExpression TypeExpression {
2080                         get {
2081                                 return type_expr;
2082                         }
2083                 }
2084
2085                 public LocalVariable Variable {
2086                         get {
2087                                 return li;
2088                         }
2089                 }
2090
2091                 #endregion
2092
2093                 public void AddDeclarator (BlockVariableDeclarator decl)
2094                 {
2095                         if (declarators == null)
2096                                 declarators = new List<BlockVariableDeclarator> ();
2097
2098                         declarators.Add (decl);
2099                 }
2100
2101                 static void CreateEvaluatorVariable (BlockContext bc, LocalVariable li)
2102                 {
2103                         if (bc.Report.Errors != 0)
2104                                 return;
2105
2106                         var container = bc.CurrentMemberDefinition.Parent.PartialContainer;
2107
2108                         Field f = new Field (container, new TypeExpression (li.Type, li.Location), Modifiers.PUBLIC | Modifiers.STATIC,
2109                                 new MemberName (li.Name, li.Location), null);
2110
2111                         container.AddField (f);
2112                         f.Define ();
2113
2114                         li.HoistedVariant = new HoistedEvaluatorVariable (f);
2115                         li.SetIsUsed ();
2116                 }
2117
2118                 public override bool Resolve (BlockContext bc)
2119                 {
2120                         return Resolve (bc, true);
2121                 }
2122
2123                 public bool Resolve (BlockContext bc, bool resolveDeclaratorInitializers)
2124                 {
2125                         if (type == null && !li.IsCompilerGenerated) {
2126                                 var vexpr = type_expr as VarExpr;
2127
2128                                 //
2129                                 // C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
2130                                 // same name exists or as a keyword when no type was found
2131                                 //
2132                                 if (vexpr != null && !vexpr.IsPossibleTypeOrNamespace (bc)) {
2133                                         if (bc.Module.Compiler.Settings.Version < LanguageVersion.V_3)
2134                                                 bc.Report.FeatureIsNotAvailable (bc.Module.Compiler, loc, "implicitly typed local variable");
2135
2136                                         if (li.IsFixed) {
2137                                                 bc.Report.Error (821, loc, "A fixed statement cannot use an implicitly typed local variable");
2138                                                 return false;
2139                                         }
2140
2141                                         if (li.IsConstant) {
2142                                                 bc.Report.Error (822, loc, "An implicitly typed local variable cannot be a constant");
2143                                                 return false;
2144                                         }
2145
2146                                         if (Initializer == null) {
2147                                                 bc.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
2148                                                 return false;
2149                                         }
2150
2151                                         if (declarators != null) {
2152                                                 bc.Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
2153                                                 declarators = null;
2154                                         }
2155
2156                                         Initializer = Initializer.Resolve (bc);
2157                                         if (Initializer != null) {
2158                                                 ((VarExpr) type_expr).InferType (bc, Initializer);
2159                                                 type = type_expr.Type;
2160                                         } else {
2161                                                 // Set error type to indicate the var was placed correctly but could
2162                                                 // not be infered
2163                                                 //
2164                                                 // var a = missing ();
2165                                                 //
2166                                                 type = InternalType.ErrorType;
2167                                         }
2168                                 }
2169
2170                                 if (type == null) {
2171                                         type = type_expr.ResolveAsType (bc);
2172                                         if (type == null)
2173                                                 return false;
2174
2175                                         if (li.IsConstant && !type.IsConstantCompatible) {
2176                                                 Const.Error_InvalidConstantType (type, loc, bc.Report);
2177                                         }
2178                                 }
2179
2180                                 if (type.IsStatic)
2181                                         FieldBase.Error_VariableOfStaticClass (loc, li.Name, type, bc.Report);
2182
2183                                 li.Type = type;
2184                         }
2185
2186                         bool eval_global = bc.Module.Compiler.Settings.StatementMode && bc.CurrentBlock is ToplevelBlock;
2187                         if (eval_global) {
2188                                 CreateEvaluatorVariable (bc, li);
2189                         } else if (type != InternalType.ErrorType) {
2190                                 li.PrepareAssignmentAnalysis (bc);
2191                         }
2192
2193                         if (initializer != null) {
2194                                 initializer = ResolveInitializer (bc, li, initializer);
2195                                 // li.Variable.DefinitelyAssigned 
2196                         }
2197
2198                         if (declarators != null) {
2199                                 foreach (var d in declarators) {
2200                                         d.Variable.Type = li.Type;
2201                                         if (eval_global) {
2202                                                 CreateEvaluatorVariable (bc, d.Variable);
2203                                         } else if (type != InternalType.ErrorType) {
2204                                                 d.Variable.PrepareAssignmentAnalysis (bc);
2205                                         }
2206
2207                                         if (d.Initializer != null && resolveDeclaratorInitializers) {
2208                                                 d.Initializer = ResolveInitializer (bc, d.Variable, d.Initializer);
2209                                                 // d.Variable.DefinitelyAssigned 
2210                                         } 
2211                                 }
2212                         }
2213
2214                         return true;
2215                 }
2216
2217                 protected virtual Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
2218                 {
2219                         var a = new SimpleAssign (li.CreateReferenceExpression (bc, li.Location), initializer, li.Location);
2220                         return a.ResolveStatement (bc);
2221                 }
2222
2223                 protected override void DoEmit (EmitContext ec)
2224                 {
2225                         li.CreateBuilder (ec);
2226
2227                         if (Initializer != null && !IsUnreachable)
2228                                 ((ExpressionStatement) Initializer).EmitStatement (ec);
2229
2230                         if (declarators != null) {
2231                                 foreach (var d in declarators) {
2232                                         d.Variable.CreateBuilder (ec);
2233                                         if (d.Initializer != null && !IsUnreachable) {
2234                                                 ec.Mark (d.Variable.Location);
2235                                                 ((ExpressionStatement) d.Initializer).EmitStatement (ec);
2236                                         }
2237                                 }
2238                         }
2239                 }
2240
2241                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
2242                 {
2243                         if (Initializer != null)
2244                                 Initializer.FlowAnalysis (fc);
2245
2246                         if (declarators != null) {
2247                                 foreach (var d in declarators) {
2248                                         if (d.Initializer != null)
2249                                                 d.Initializer.FlowAnalysis (fc);
2250                                 }
2251                         }
2252
2253                         return false;
2254                 }
2255
2256                 public override Reachability MarkReachable (Reachability rc)
2257                 {
2258                         var init = initializer as ExpressionStatement;
2259                         if (init != null)
2260                                 init.MarkReachable (rc);
2261
2262                         return base.MarkReachable (rc);
2263                 }
2264
2265                 protected override void CloneTo (CloneContext clonectx, Statement target)
2266                 {
2267                         BlockVariable t = (BlockVariable) target;
2268
2269                         if (type_expr != null)
2270                                 t.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
2271
2272                         if (initializer != null)
2273                                 t.initializer = initializer.Clone (clonectx);
2274
2275                         if (declarators != null) {
2276                                 t.declarators = null;
2277                                 foreach (var d in declarators)
2278                                         t.AddDeclarator (d.Clone (clonectx));
2279                         }
2280                 }
2281
2282                 public override object Accept (StructuralVisitor visitor)
2283                 {
2284                         return visitor.Visit (this);
2285                 }
2286         }
2287
2288         public class BlockConstant : BlockVariable
2289         {
2290                 public BlockConstant (FullNamedExpression type, LocalVariable li)
2291                         : base (type, li)
2292                 {
2293                 }
2294
2295                 public override void Emit (EmitContext ec)
2296                 {
2297                         // Nothing to emit, not even sequence point
2298                 }
2299
2300                 protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
2301                 {
2302                         initializer = initializer.Resolve (bc);
2303                         if (initializer == null)
2304                                 return null;
2305
2306                         var c = initializer as Constant;
2307                         if (c == null) {
2308                                 initializer.Error_ExpressionMustBeConstant (bc, initializer.Location, li.Name);
2309                                 return null;
2310                         }
2311
2312                         c = c.ConvertImplicitly (li.Type);
2313                         if (c == null) {
2314                                 if (TypeSpec.IsReferenceType (li.Type))
2315                                         initializer.Error_ConstantCanBeInitializedWithNullOnly (bc, li.Type, initializer.Location, li.Name);
2316                                 else
2317                                         initializer.Error_ValueCannotBeConverted (bc, li.Type, false);
2318
2319                                 return null;
2320                         }
2321
2322                         li.ConstantValue = c;
2323                         return initializer;
2324                 }
2325                 
2326                 public override object Accept (StructuralVisitor visitor)
2327                 {
2328                         return visitor.Visit (this);
2329                 }
2330         }
2331
2332         //
2333         // The information about a user-perceived local variable
2334         //
2335         public sealed class LocalVariable : INamedBlockVariable, ILocalVariable
2336         {
2337                 [Flags]
2338                 public enum Flags
2339                 {
2340                         Used = 1,
2341                         IsThis = 1 << 1,
2342                         AddressTaken = 1 << 2,
2343                         CompilerGenerated = 1 << 3,
2344                         Constant = 1 << 4,
2345                         ForeachVariable = 1 << 5,
2346                         FixedVariable = 1 << 6,
2347                         UsingVariable = 1 << 7,
2348                         IsLocked = 1 << 8,
2349
2350                         ReadonlyMask = ForeachVariable | FixedVariable | UsingVariable
2351                 }
2352
2353                 TypeSpec type;
2354                 readonly string name;
2355                 readonly Location loc;
2356                 readonly Block block;
2357                 Flags flags;
2358                 Constant const_value;
2359
2360                 public VariableInfo VariableInfo;
2361                 HoistedVariable hoisted_variant;
2362
2363                 LocalBuilder builder;
2364
2365                 public LocalVariable (Block block, string name, Location loc)
2366                 {
2367                         this.block = block;
2368                         this.name = name;
2369                         this.loc = loc;
2370                 }
2371
2372                 public LocalVariable (Block block, string name, Flags flags, Location loc)
2373                         : this (block, name, loc)
2374                 {
2375                         this.flags = flags;
2376                 }
2377
2378                 //
2379                 // Used by variable declarators
2380                 //
2381                 public LocalVariable (LocalVariable li, string name, Location loc)
2382                         : this (li.block, name, li.flags, loc)
2383                 {
2384                 }
2385
2386                 #region Properties
2387
2388                 public bool AddressTaken {
2389                         get {
2390                                 return (flags & Flags.AddressTaken) != 0;
2391                         }
2392                 }
2393
2394                 public Block Block {
2395                         get {
2396                                 return block;
2397                         }
2398                 }
2399
2400                 public Constant ConstantValue {
2401                         get {
2402                                 return const_value;
2403                         }
2404                         set {
2405                                 const_value = value;
2406                         }
2407                 }
2408
2409                 //
2410                 // Hoisted local variable variant
2411                 //
2412                 public HoistedVariable HoistedVariant {
2413                         get {
2414                                 return hoisted_variant;
2415                         }
2416                         set {
2417                                 hoisted_variant = value;
2418                         }
2419                 }
2420
2421                 public bool IsDeclared {
2422                         get {
2423                                 return type != null;
2424                         }
2425                 }
2426
2427                 public bool IsCompilerGenerated {
2428                         get {
2429                                 return (flags & Flags.CompilerGenerated) != 0;
2430                         }
2431                 }
2432
2433                 public bool IsConstant {
2434                         get {
2435                                 return (flags & Flags.Constant) != 0;
2436                         }
2437                 }
2438
2439                 public bool IsLocked {
2440                         get {
2441                                 return (flags & Flags.IsLocked) != 0;
2442                         }
2443                         set {
2444                                 flags = value ? flags | Flags.IsLocked : flags & ~Flags.IsLocked;
2445                         }
2446                 }
2447
2448                 public bool IsThis {
2449                         get {
2450                                 return (flags & Flags.IsThis) != 0;
2451                         }
2452                 }
2453
2454                 public bool IsFixed {
2455                         get {
2456                                 return (flags & Flags.FixedVariable) != 0;
2457                         }
2458                 }
2459
2460                 bool INamedBlockVariable.IsParameter {
2461                         get {
2462                                 return false;
2463                         }
2464                 }
2465
2466                 public bool IsReadonly {
2467                         get {
2468                                 return (flags & Flags.ReadonlyMask) != 0;
2469                         }
2470                 }
2471
2472                 public Location Location {
2473                         get {
2474                                 return loc;
2475                         }
2476                 }
2477
2478                 public string Name {
2479                         get {
2480                                 return name;
2481                         }
2482                 }
2483
2484                 public TypeSpec Type {
2485                     get {
2486                                 return type;
2487                         }
2488                     set {
2489                                 type = value;
2490                         }
2491                 }
2492
2493                 #endregion
2494
2495                 public void CreateBuilder (EmitContext ec)
2496                 {
2497                         if ((flags & Flags.Used) == 0) {
2498                                 if (VariableInfo == null) {
2499                                         // Missing flow analysis or wrong variable flags
2500                                         throw new InternalErrorException ("VariableInfo is null and the variable `{0}' is not used", name);
2501                                 }
2502
2503                                 if (VariableInfo.IsEverAssigned)
2504                                         ec.Report.Warning (219, 3, Location, "The variable `{0}' is assigned but its value is never used", Name);
2505                                 else
2506                                         ec.Report.Warning (168, 3, Location, "The variable `{0}' is declared but never used", Name);
2507                         }
2508
2509                         if (HoistedVariant != null)
2510                                 return;
2511
2512                         if (builder != null) {
2513                                 if ((flags & Flags.CompilerGenerated) != 0)
2514                                         return;
2515
2516                                 // To avoid Used warning duplicates
2517                                 throw new InternalErrorException ("Already created variable `{0}'", name);
2518                         }
2519
2520                         //
2521                         // All fixed variabled are pinned, a slot has to be alocated
2522                         //
2523                         builder = ec.DeclareLocal (Type, IsFixed);
2524                         if (!ec.HasSet (BuilderContext.Options.OmitDebugInfo) && (flags & Flags.CompilerGenerated) == 0)
2525                                 ec.DefineLocalVariable (name, builder);
2526                 }
2527
2528                 public static LocalVariable CreateCompilerGenerated (TypeSpec type, Block block, Location loc)
2529                 {
2530                         LocalVariable li = new LocalVariable (block, GetCompilerGeneratedName (block), Flags.CompilerGenerated | Flags.Used, loc);
2531                         li.Type = type;
2532                         return li;
2533                 }
2534
2535                 public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
2536                 {
2537                         if (IsConstant && const_value != null)
2538                                 return Constant.CreateConstantFromValue (Type, const_value.GetValue (), loc);
2539
2540                         return new LocalVariableReference (this, loc);
2541                 }
2542
2543                 public void Emit (EmitContext ec)
2544                 {
2545                         // TODO: Need something better for temporary variables
2546                         if ((flags & Flags.CompilerGenerated) != 0)
2547                                 CreateBuilder (ec);
2548
2549                         ec.Emit (OpCodes.Ldloc, builder);
2550                 }
2551
2552                 public void EmitAssign (EmitContext ec)
2553                 {
2554                         // TODO: Need something better for temporary variables
2555                         if ((flags & Flags.CompilerGenerated) != 0)
2556                                 CreateBuilder (ec);
2557
2558                         ec.Emit (OpCodes.Stloc, builder);
2559                 }
2560
2561                 public void EmitAddressOf (EmitContext ec)
2562                 {
2563                         // TODO: Need something better for temporary variables
2564                         if ((flags & Flags.CompilerGenerated) != 0)
2565                                 CreateBuilder (ec);
2566
2567                         ec.Emit (OpCodes.Ldloca, builder);
2568                 }
2569
2570                 public static string GetCompilerGeneratedName (Block block)
2571                 {
2572                         // HACK: Debugger depends on the name semantics
2573                         return "$locvar" + block.ParametersBlock.TemporaryLocalsCount++.ToString ("X");
2574                 }
2575
2576                 public string GetReadOnlyContext ()
2577                 {
2578                         switch (flags & Flags.ReadonlyMask) {
2579                         case Flags.FixedVariable:
2580                                 return "fixed variable";
2581                         case Flags.ForeachVariable:
2582                                 return "foreach iteration variable";
2583                         case Flags.UsingVariable:
2584                                 return "using variable";
2585                         }
2586
2587                         throw new InternalErrorException ("Variable is not readonly");
2588                 }
2589
2590                 public bool IsThisAssigned (FlowAnalysisContext fc, Block block)
2591                 {
2592                         if (VariableInfo == null)
2593                                 throw new Exception ();
2594
2595                         if (IsAssigned (fc))
2596                                 return true;
2597
2598                         return VariableInfo.IsFullyInitialized (fc, block.StartLocation);
2599                 }
2600
2601                 public bool IsAssigned (FlowAnalysisContext fc)
2602                 {
2603                         return fc.IsDefinitelyAssigned (VariableInfo);
2604                 }
2605
2606                 public void PrepareAssignmentAnalysis (BlockContext bc)
2607                 {
2608                         //
2609                         // No need to run assignment analysis for these guys
2610                         //
2611                         if ((flags & (Flags.Constant | Flags.ReadonlyMask | Flags.CompilerGenerated)) != 0)
2612                                 return;
2613
2614                         VariableInfo = VariableInfo.Create (bc, this);
2615                 }
2616
2617                 //
2618                 // Mark the variables as referenced in the user code
2619                 //
2620                 public void SetIsUsed ()
2621                 {
2622                         flags |= Flags.Used;
2623                 }
2624
2625                 public void SetHasAddressTaken ()
2626                 {
2627                         flags |= (Flags.AddressTaken | Flags.Used);
2628                 }
2629
2630                 public override string ToString ()
2631                 {
2632                         return string.Format ("LocalInfo ({0},{1},{2},{3})", name, type, VariableInfo, Location);
2633                 }
2634         }
2635
2636         /// <summary>
2637         ///   Block represents a C# block.
2638         /// </summary>
2639         ///
2640         /// <remarks>
2641         ///   This class is used in a number of places: either to represent
2642         ///   explicit blocks that the programmer places or implicit blocks.
2643         ///
2644         ///   Implicit blocks are used as labels or to introduce variable
2645         ///   declarations.
2646         ///
2647         ///   Top-level blocks derive from Block, and they are called ToplevelBlock
2648         ///   they contain extra information that is not necessary on normal blocks.
2649         /// </remarks>
2650         public class Block : Statement {
2651                 [Flags]
2652                 public enum Flags
2653                 {
2654                         Unchecked = 1,
2655                         ReachableEnd = 8,
2656                         Unsafe = 16,
2657                         HasCapturedVariable = 64,
2658                         HasCapturedThis = 1 << 7,
2659                         IsExpressionTree = 1 << 8,
2660                         CompilerGenerated = 1 << 9,
2661                         HasAsyncModifier = 1 << 10,
2662                         Resolved = 1 << 11,
2663                         YieldBlock = 1 << 12,
2664                         AwaitBlock = 1 << 13,
2665                         FinallyBlock = 1 << 14,
2666                         CatchBlock = 1 << 15,
2667                         Iterator = 1 << 20,
2668                         NoFlowAnalysis = 1 << 21,
2669                         InitializationEmitted = 1 << 22
2670                 }
2671
2672                 public Block Parent;
2673                 public Location StartLocation;
2674                 public Location EndLocation;
2675
2676                 public ExplicitBlock Explicit;
2677                 public ParametersBlock ParametersBlock;
2678
2679                 protected Flags flags;
2680
2681                 //
2682                 // The statements in this block
2683                 //
2684                 protected List<Statement> statements;
2685
2686                 protected List<Statement> scope_initializers;
2687
2688                 int? resolving_init_idx;
2689
2690                 Block original;
2691
2692 #if DEBUG
2693                 static int id;
2694                 public int ID = id++;
2695
2696                 static int clone_id_counter;
2697                 int clone_id;
2698 #endif
2699
2700 //              int assignable_slots;
2701
2702                 public Block (Block parent, Location start, Location end)
2703                         : this (parent, 0, start, end)
2704                 {
2705                 }
2706
2707                 public Block (Block parent, Flags flags, Location start, Location end)
2708                 {
2709                         if (parent != null) {
2710                                 // the appropriate constructors will fixup these fields
2711                                 ParametersBlock = parent.ParametersBlock;
2712                                 Explicit = parent.Explicit;
2713                         }
2714                         
2715                         this.Parent = parent;
2716                         this.flags = flags;
2717                         this.StartLocation = start;
2718                         this.EndLocation = end;
2719                         this.loc = start;
2720                         statements = new List<Statement> (4);
2721
2722                         this.original = this;
2723                 }
2724
2725                 #region Properties
2726
2727                 public Block Original {
2728                         get {
2729                                 return original;
2730                         }
2731                         protected set {
2732                                 original = value;
2733                         }
2734                 }
2735
2736                 public bool IsCompilerGenerated {
2737                         get { return (flags & Flags.CompilerGenerated) != 0; }
2738                         set { flags = value ? flags | Flags.CompilerGenerated : flags & ~Flags.CompilerGenerated; }
2739                 }
2740
2741
2742                 public bool IsCatchBlock {
2743                         get {
2744                                 return (flags & Flags.CatchBlock) != 0;
2745                         }
2746                 }
2747
2748                 public bool IsFinallyBlock {
2749                         get {
2750                                 return (flags & Flags.FinallyBlock) != 0;
2751                         }
2752                 }
2753
2754                 public bool Unchecked {
2755                         get { return (flags & Flags.Unchecked) != 0; }
2756                         set { flags = value ? flags | Flags.Unchecked : flags & ~Flags.Unchecked; }
2757                 }
2758
2759                 public bool Unsafe {
2760                         get { return (flags & Flags.Unsafe) != 0; }
2761                         set { flags |= Flags.Unsafe; }
2762                 }
2763
2764                 public List<Statement> Statements {
2765                         get { return statements; }
2766                 }
2767
2768                 #endregion
2769
2770                 public void SetEndLocation (Location loc)
2771                 {
2772                         EndLocation = loc;
2773                 }
2774
2775                 public void AddLabel (LabeledStatement target)
2776                 {
2777                         ParametersBlock.TopBlock.AddLabel (target.Name, target);
2778                 }
2779
2780                 public void AddLocalName (LocalVariable li)
2781                 {
2782                         AddLocalName (li.Name, li);
2783                 }
2784
2785                 public void AddLocalName (string name, INamedBlockVariable li)
2786                 {
2787                         ParametersBlock.TopBlock.AddLocalName (name, li, false);
2788                 }
2789
2790                 public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
2791                 {
2792                         if (reason == null) {
2793                                 Error_AlreadyDeclared (name, variable);
2794                                 return;
2795                         }
2796
2797                         ParametersBlock.TopBlock.Report.Error (136, variable.Location,
2798                                 "A local variable named `{0}' cannot be declared in this scope because it would give a different meaning " +
2799                                 "to `{0}', which is already used in a `{1}' scope to denote something else",
2800                                 name, reason);
2801                 }
2802
2803                 public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
2804                 {
2805                         var pi = variable as ParametersBlock.ParameterInfo;
2806                         if (pi != null) {
2807                                 pi.Parameter.Error_DuplicateName (ParametersBlock.TopBlock.Report);
2808                         } else {
2809                                 ParametersBlock.TopBlock.Report.Error (128, variable.Location,
2810                                         "A local variable named `{0}' is already defined in this scope", name);
2811                         }
2812                 }
2813                                         
2814                 public virtual void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
2815                 {
2816                         ParametersBlock.TopBlock.Report.Error (412, loc,
2817                                 "The type parameter name `{0}' is the same as local variable or parameter name",
2818                                 name);
2819                 }
2820
2821                 //
2822                 // It should be used by expressions which require to
2823                 // register a statement during resolve process.
2824                 //
2825                 public void AddScopeStatement (Statement s)
2826                 {
2827                         if (scope_initializers == null)
2828                                 scope_initializers = new List<Statement> ();
2829
2830                         //
2831                         // Simple recursive helper, when resolve scope initializer another
2832                         // new scope initializer can be added, this ensures it's initialized
2833                         // before existing one. For now this can happen with expression trees
2834                         // in base ctor initializer only
2835                         //
2836                         if (resolving_init_idx.HasValue) {
2837                                 scope_initializers.Insert (resolving_init_idx.Value, s);
2838                                 ++resolving_init_idx;
2839                         } else {
2840                                 scope_initializers.Add (s);
2841                         }
2842                 }
2843
2844                 public void InsertStatement (int index, Statement s)
2845                 {
2846                         statements.Insert (index, s);
2847                 }
2848                 
2849                 public void AddStatement (Statement s)
2850                 {
2851                         statements.Add (s);
2852                 }
2853
2854                 public LabeledStatement LookupLabel (string name)
2855                 {
2856                         return ParametersBlock.GetLabel (name, this);
2857                 }
2858
2859                 public override Reachability MarkReachable (Reachability rc)
2860                 {
2861                         if (rc.IsUnreachable)
2862                                 return rc;
2863
2864                         MarkReachableScope (rc);
2865
2866                         foreach (var s in statements) {
2867                                 rc = s.MarkReachable (rc);
2868                                 if (rc.IsUnreachable) {
2869                                         if ((flags & Flags.ReachableEnd) != 0)
2870                                                 return new Reachability ();
2871
2872                                         return rc;
2873                                 }
2874                         }
2875
2876                         flags |= Flags.ReachableEnd;
2877
2878                         return rc;
2879                 }
2880
2881                 public void MarkReachableScope (Reachability rc)
2882                 {
2883                         base.MarkReachable (rc);
2884
2885                         if (scope_initializers != null) {
2886                                 foreach (var si in scope_initializers)
2887                                         si.MarkReachable (rc);
2888                         }
2889                 }
2890
2891                 public override bool Resolve (BlockContext bc)
2892                 {
2893                         if ((flags & Flags.Resolved) != 0)
2894                                 return true;
2895
2896                         Block prev_block = bc.CurrentBlock;
2897                         bc.CurrentBlock = this;
2898
2899                         //
2900                         // Compiler generated scope statements
2901                         //
2902                         if (scope_initializers != null) {
2903                                 for (resolving_init_idx = 0; resolving_init_idx < scope_initializers.Count; ++resolving_init_idx) {
2904                                         scope_initializers[resolving_init_idx.Value].Resolve (bc);
2905                                 }
2906
2907                                 resolving_init_idx = null;
2908                         }
2909
2910                         bool ok = true;
2911                         int statement_count = statements.Count;
2912                         for (int ix = 0; ix < statement_count; ix++){
2913                                 Statement s = statements [ix];
2914
2915                                 if (!s.Resolve (bc)) {
2916                                         ok = false;
2917                                         statements [ix] = new EmptyStatement (s.loc);
2918                                         continue;
2919                                 }
2920                         }
2921
2922                         bc.CurrentBlock = prev_block;
2923
2924                         flags |= Flags.Resolved;
2925                         return ok;
2926                 }
2927
2928                 protected override void DoEmit (EmitContext ec)
2929                 {
2930                         for (int ix = 0; ix < statements.Count; ix++){
2931                                 statements [ix].Emit (ec);
2932                         }
2933                 }
2934
2935                 public override void Emit (EmitContext ec)
2936                 {
2937                         if (scope_initializers != null)
2938                                 EmitScopeInitializers (ec);
2939
2940                         DoEmit (ec);
2941                 }
2942
2943                 protected void EmitScopeInitializers (EmitContext ec)
2944                 {
2945                         foreach (Statement s in scope_initializers)
2946                                 s.Emit (ec);
2947                 }
2948
2949                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
2950                 {
2951                         if (scope_initializers != null) {
2952                                 foreach (var si in scope_initializers)
2953                                         si.FlowAnalysis (fc);
2954                         }
2955
2956                         return DoFlowAnalysis (fc, 0);  
2957                 }
2958
2959                 bool DoFlowAnalysis (FlowAnalysisContext fc, int startIndex)
2960                 {
2961                         bool end_unreachable = !reachable;
2962                         bool goto_flow_analysis = startIndex != 0;
2963                         for (; startIndex < statements.Count; ++startIndex) {
2964                                 var s = statements[startIndex];
2965
2966                                 end_unreachable = s.FlowAnalysis (fc);
2967                                 if (s.IsUnreachable) {
2968                                         statements [startIndex] = RewriteUnreachableStatement (s);
2969                                         continue;
2970                                 }
2971
2972                                 //
2973                                 // Statement end reachability is needed mostly due to goto support. Consider
2974                                 //
2975                                 // if (cond) {
2976                                 //    goto X;
2977                                 // } else {
2978                                 //    goto Y;
2979                                 // }
2980                                 // X:
2981                                 //
2982                                 // X label is reachable only via goto not as another statement after if. We need
2983                                 // this for flow-analysis only to carry variable info correctly.
2984                                 //
2985                                 if (end_unreachable) {
2986                                         bool after_goto_case = goto_flow_analysis && s is GotoCase;
2987
2988                                         for (++startIndex; startIndex < statements.Count; ++startIndex) {
2989                                                 s = statements[startIndex];
2990                                                 if (s is SwitchLabel) {
2991                                                         if (!after_goto_case)
2992                                                                 s.FlowAnalysis (fc);
2993
2994                                                         break;
2995                                                 }
2996
2997                                                 if (s.IsUnreachable) {
2998                                                         s.FlowAnalysis (fc);
2999                                                         statements [startIndex] = RewriteUnreachableStatement (s);
3000                                                 }
3001                                         }
3002
3003                                         //
3004                                         // Idea is to stop after goto case because goto case will always have at least same
3005                                         // variable assigned as switch case label. This saves a lot for complex goto case tests
3006                                         //
3007                                         if (after_goto_case)
3008                                                 break;
3009
3010                                         continue;
3011                                 }
3012
3013                                 var lb = s as LabeledStatement;
3014                                 if (lb != null && fc.AddReachedLabel (lb))
3015                                         break;
3016                         }
3017
3018                         //
3019                         // The condition should be true unless there is forward jumping goto
3020                         // 
3021                         // if (this is ExplicitBlock && end_unreachable != Explicit.HasReachableClosingBrace)
3022                         //      Debug.Fail ();
3023
3024                         return !Explicit.HasReachableClosingBrace;
3025                 }
3026
3027                 static Statement RewriteUnreachableStatement (Statement s)
3028                 {
3029                         // LAMESPEC: It's not clear whether declararion statement should be part of reachability
3030                         // analysis. Even csc report unreachable warning for it but it's actually used hence
3031                         // we try to emulate this behaviour
3032                         //
3033                         // Consider:
3034                         //      goto L;
3035                         //      int v;
3036                         // L:
3037                         //      v = 1;
3038
3039                         if (s is BlockVariable || s is EmptyStatement)
3040                                 return s;
3041
3042                         return new EmptyStatement (s.loc);
3043                 }
3044
3045                 public void ScanGotoJump (Statement label)
3046                 {
3047                         int i;
3048                         for (i = 0; i < statements.Count; ++i) {
3049                                 if (statements[i] == label)
3050                                         break;
3051                         }
3052
3053                         var rc = new Reachability ();
3054                         for (++i; i < statements.Count; ++i) {
3055                                 var s = statements[i];
3056                                 rc = s.MarkReachable (rc);
3057                                 if (rc.IsUnreachable)
3058                                         return;
3059                         }
3060
3061                         flags |= Flags.ReachableEnd;
3062                 }
3063
3064                 public void ScanGotoJump (Statement label, FlowAnalysisContext fc)
3065                 {
3066                         int i;
3067                         for (i = 0; i < statements.Count; ++i) {
3068                                 if (statements[i] == label)
3069                                         break;
3070                         }
3071
3072                         DoFlowAnalysis (fc, ++i);
3073                 }
3074
3075 #if DEBUG
3076                 public override string ToString ()
3077                 {
3078                         return String.Format ("{0}: ID={1} Clone={2} Location={3}", GetType (), ID, clone_id != 0, StartLocation);
3079                 }
3080 #endif
3081
3082                 protected override void CloneTo (CloneContext clonectx, Statement t)
3083                 {
3084                         Block target = (Block) t;
3085 #if DEBUG
3086                         target.clone_id = ++clone_id_counter;
3087 #endif
3088
3089                         clonectx.AddBlockMap (this, target);
3090                         if (original != this)
3091                                 clonectx.AddBlockMap (original, target);
3092
3093                         target.ParametersBlock = (ParametersBlock) (ParametersBlock == this ? target : clonectx.RemapBlockCopy (ParametersBlock));
3094                         target.Explicit = (ExplicitBlock) (Explicit == this ? target : clonectx.LookupBlock (Explicit));
3095
3096                         if (Parent != null)
3097                                 target.Parent = clonectx.RemapBlockCopy (Parent);
3098
3099                         target.statements = new List<Statement> (statements.Count);
3100                         foreach (Statement s in statements)
3101                                 target.statements.Add (s.Clone (clonectx));
3102                 }
3103
3104                 public override object Accept (StructuralVisitor visitor)
3105                 {
3106                         return visitor.Visit (this);
3107                 }
3108         }
3109
3110         public class ExplicitBlock : Block
3111         {
3112                 protected AnonymousMethodStorey am_storey;
3113
3114                 public ExplicitBlock (Block parent, Location start, Location end)
3115                         : this (parent, (Flags) 0, start, end)
3116                 {
3117                 }
3118
3119                 public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
3120                         : base (parent, flags, start, end)
3121                 {
3122                         this.Explicit = this;
3123                 }
3124
3125                 #region Properties
3126
3127                 public AnonymousMethodStorey AnonymousMethodStorey {
3128                         get {
3129                                 return am_storey;
3130                         }
3131                 }
3132
3133                 public bool HasAwait {
3134                         get {
3135                                 return (flags & Flags.AwaitBlock) != 0;
3136                         }
3137                 }
3138
3139                 public bool HasCapturedThis {
3140                         set {
3141                                 flags = value ? flags | Flags.HasCapturedThis : flags & ~Flags.HasCapturedThis;
3142                         }
3143                         get {
3144                                 return (flags & Flags.HasCapturedThis) != 0;
3145                         }
3146                 }
3147
3148                 //
3149                 // Used to indicate that the block has reference to parent
3150                 // block and cannot be made static when defining anonymous method
3151                 //
3152                 public bool HasCapturedVariable {
3153                         set {
3154                                 flags = value ? flags | Flags.HasCapturedVariable : flags & ~Flags.HasCapturedVariable;
3155                         }
3156                         get {
3157                                 return (flags & Flags.HasCapturedVariable) != 0;
3158                         }
3159                 }
3160
3161                 public bool HasReachableClosingBrace {
3162                     get {
3163                         return (flags & Flags.ReachableEnd) != 0;
3164                     }
3165                         set {
3166                                 flags = value ? flags | Flags.ReachableEnd : flags & ~Flags.ReachableEnd;
3167                         }
3168                 }
3169
3170                 public bool HasYield {
3171                         get {
3172                                 return (flags & Flags.YieldBlock) != 0;
3173                         }
3174                 }
3175
3176                 #endregion
3177
3178                 //
3179                 // Creates anonymous method storey in current block
3180                 //
3181                 public AnonymousMethodStorey CreateAnonymousMethodStorey (ResolveContext ec)
3182                 {
3183                         //
3184                         // Return same story for iterator and async blocks unless we are
3185                         // in nested anonymous method
3186                         //
3187                         if (ec.CurrentAnonymousMethod is StateMachineInitializer && ParametersBlock.Original == ec.CurrentAnonymousMethod.Block.Original)
3188                                 return ec.CurrentAnonymousMethod.Storey;
3189
3190                         if (am_storey == null) {
3191                                 MemberBase mc = ec.MemberContext as MemberBase;
3192
3193                                 //
3194                                 // Creates anonymous method storey for this block
3195                                 //
3196                                 am_storey = new AnonymousMethodStorey (this, ec.CurrentMemberDefinition.Parent.PartialContainer, mc, ec.CurrentTypeParameters, "AnonStorey", MemberKind.Class);
3197                         }
3198
3199                         return am_storey;
3200                 }
3201
3202                 public void EmitScopeInitialization (EmitContext ec)
3203                 {
3204                         if ((flags & Flags.InitializationEmitted) != 0)
3205                                 return;
3206
3207                         if (am_storey != null) {
3208                                 DefineStoreyContainer (ec, am_storey);
3209                                 am_storey.EmitStoreyInstantiation (ec, this);
3210                         }
3211
3212                         if (scope_initializers != null)
3213                                 EmitScopeInitializers (ec);
3214
3215                         flags |= Flags.InitializationEmitted;
3216                 }
3217
3218                 public override void Emit (EmitContext ec)
3219                 {
3220                         if (Parent != null)
3221                                 ec.BeginScope ();
3222
3223                         EmitScopeInitialization (ec);
3224
3225                         if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated && ec.Mark (StartLocation)) {
3226                                 ec.Emit (OpCodes.Nop);
3227                         }
3228
3229                         DoEmit (ec);
3230
3231                         if (Parent != null)
3232                                 ec.EndScope ();
3233
3234                         if (ec.EmitAccurateDebugInfo && HasReachableClosingBrace && !(this is ParametersBlock) &&
3235                                 !IsCompilerGenerated && ec.Mark (EndLocation)) {
3236                                 ec.Emit (OpCodes.Nop);
3237                         }
3238                 }
3239
3240                 protected void DefineStoreyContainer (EmitContext ec, AnonymousMethodStorey storey)
3241                 {
3242                         if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null) {
3243                                 storey.SetNestedStoryParent (ec.CurrentAnonymousMethod.Storey);
3244                                 storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
3245                         }
3246
3247                         //
3248                         // Creates anonymous method storey
3249                         //
3250                         storey.CreateContainer ();
3251                         storey.DefineContainer ();
3252
3253                         if (Original.Explicit.HasCapturedThis && Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock != null) {
3254
3255                                 //
3256                                 // Only first storey in path will hold this reference. All children blocks will
3257                                 // reference it indirectly using $ref field
3258                                 //
3259                                 for (Block b = Original.Explicit; b != null; b = b.Parent) {
3260                                         if (b.Parent != null) {
3261                                                 var s = b.Parent.Explicit.AnonymousMethodStorey;
3262                                                 if (s != null) {
3263                                                         storey.HoistedThis = s.HoistedThis;
3264                                                         break;
3265                                                 }
3266                                         }
3267
3268                                         if (b.Explicit == b.Explicit.ParametersBlock && b.Explicit.ParametersBlock.StateMachine != null) {
3269                                                 if (storey.HoistedThis == null)
3270                                                         storey.HoistedThis = b.Explicit.ParametersBlock.StateMachine.HoistedThis;
3271
3272                                                 if (storey.HoistedThis != null)
3273                                                         break;
3274                                         }
3275                                 }
3276                                 
3277                                 //
3278                                 // We are the first storey on path and 'this' has to be hoisted
3279                                 //
3280                                 if (storey.HoistedThis == null || !(storey.Parent is HoistedStoreyClass)) {
3281                                         foreach (ExplicitBlock ref_block in Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock) {
3282                                                 //
3283                                                 // ThisReferencesFromChildrenBlock holds all reference even if they
3284                                                 // are not on this path. It saves some memory otherwise it'd have to
3285                                                 // be in every explicit block. We run this check to see if the reference
3286                                                 // is valid for this storey
3287                                                 //
3288                                                 Block block_on_path = ref_block;
3289                                                 for (; block_on_path != null && block_on_path != Original; block_on_path = block_on_path.Parent);
3290
3291                                                 if (block_on_path == null)
3292                                                         continue;
3293
3294                                                 if (storey.HoistedThis == null) {
3295                                                         storey.AddCapturedThisField (ec, null);
3296                                                 }
3297
3298                                                 for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
3299                                                         ParametersBlock pb;
3300                                                         AnonymousMethodStorey b_storey = b.AnonymousMethodStorey;
3301
3302                                                         if (b_storey != null) {
3303                                                                 //
3304                                                                 // Don't add storey cross reference for `this' when the storey ends up not
3305                                                                 // beeing attached to any parent
3306                                                                 //
3307                                                                 if (b.ParametersBlock.StateMachine == null) {
3308                                                                         AnonymousMethodStorey s = null;
3309                                                                         for (Block ab = b.AnonymousMethodStorey.OriginalSourceBlock.Parent; ab != null; ab = ab.Parent) {
3310                                                                                 s = ab.Explicit.AnonymousMethodStorey;
3311                                                                                 if (s != null)
3312                                                                                         break;
3313                                                                         }
3314
3315                                                                         // Needs to be in sync with AnonymousMethodBody::DoCreateMethodHost
3316                                                                         if (s == null) {
3317                                                                                 var parent = storey == null || storey.Kind == MemberKind.Struct ? null : storey;
3318                                                                                 b.AnonymousMethodStorey.AddCapturedThisField (ec, parent);
3319                                                                                 break;
3320                                                                         }
3321
3322                                                                 }
3323
3324                                                                 //
3325                                                                 // Stop propagation inside same top block
3326                                                                 //
3327                                                                 if (b.ParametersBlock == ParametersBlock.Original) {
3328                                                                         b_storey.AddParentStoreyReference (ec, storey);
3329 //                                                                      b_storey.HoistedThis = storey.HoistedThis;
3330                                                                         break;
3331                                                                 }
3332
3333                                                                 b = pb = b.ParametersBlock;
3334                                                         } else {
3335                                                                 pb = b as ParametersBlock;
3336                                                         }
3337
3338                                                         if (pb != null && pb.StateMachine != null) {
3339                                                                 if (pb.StateMachine == storey)
3340                                                                         break;
3341
3342                                                                 //
3343                                                                 // If we are state machine with no parent. We can hook into parent without additional
3344                                                                 // reference and capture this directly
3345                                                                 //
3346                                                                 ExplicitBlock parent_storey_block = pb;
3347                                                                 while (parent_storey_block.Parent != null) {
3348                                                                         parent_storey_block = parent_storey_block.Parent.Explicit;
3349                                                                         if (parent_storey_block.AnonymousMethodStorey != null) {
3350                                                                                 break;
3351                                                                         }
3352                                                                 }
3353
3354                                                                 if (parent_storey_block.AnonymousMethodStorey == null) {
3355                                                                         pb.StateMachine.AddCapturedThisField (ec, null);
3356                                                                         b.HasCapturedThis = true;
3357                                                                         continue;
3358                                                                 }
3359
3360                                                                 pb.StateMachine.AddParentStoreyReference (ec, storey);
3361                                                         }
3362
3363                                                         //
3364                                                         // Add parent storey reference only when this is not captured directly
3365                                                         //
3366                                                         if (b_storey != null) {
3367                                                                 b_storey.AddParentStoreyReference (ec, storey);
3368                                                                 b_storey.HoistedThis = storey.HoistedThis;
3369                                                         }
3370                                                 }
3371                                         }
3372                                 }
3373                         }
3374
3375                         var ref_blocks = storey.ReferencesFromChildrenBlock;
3376                         if (ref_blocks != null) {
3377                                 foreach (ExplicitBlock ref_block in ref_blocks) {
3378                                         for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
3379                                                 if (b.AnonymousMethodStorey != null) {
3380                                                         b.AnonymousMethodStorey.AddParentStoreyReference (ec, storey);
3381
3382                                                         //
3383                                                         // Stop propagation inside same top block
3384                                                         //
3385                                                         if (b.ParametersBlock == ParametersBlock.Original)
3386                                                                 break;
3387
3388                                                         b = b.ParametersBlock;
3389                                                 }
3390
3391                                                 var pb = b as ParametersBlock;
3392                                                 if (pb != null && pb.StateMachine != null) {
3393                                                         if (pb.StateMachine == storey)
3394                                                                 break;
3395
3396                                                         pb.StateMachine.AddParentStoreyReference (ec, storey);
3397                                                 }
3398
3399                                                 b.HasCapturedVariable = true;
3400                                         }
3401                                 }
3402                         }
3403
3404                         storey.Define ();
3405                         storey.PrepareEmit ();
3406                         storey.Parent.PartialContainer.AddCompilerGeneratedClass (storey);
3407                 }
3408
3409                 public void RegisterAsyncAwait ()
3410                 {
3411                         var block = this;
3412                         while ((block.flags & Flags.AwaitBlock) == 0) {
3413                                 block.flags |= Flags.AwaitBlock;
3414
3415                                 if (block is ParametersBlock)
3416                                         return;
3417
3418                                 block = block.Parent.Explicit;
3419                         }
3420                 }
3421
3422                 public void RegisterIteratorYield ()
3423                 {
3424                         ParametersBlock.TopBlock.IsIterator = true;
3425
3426                         var block = this;
3427                         while ((block.flags & Flags.YieldBlock) == 0) {
3428                                 block.flags |= Flags.YieldBlock;
3429
3430                                 if (block.Parent == null)
3431                                         return;
3432
3433                                 block = block.Parent.Explicit;
3434                         }
3435                 }
3436
3437                 public void SetCatchBlock ()
3438                 {
3439                         flags |= Flags.CatchBlock;
3440                 }
3441
3442                 public void SetFinallyBlock ()
3443                 {
3444                         flags |= Flags.FinallyBlock;
3445                 }
3446
3447                 public void WrapIntoDestructor (TryFinally tf, ExplicitBlock tryBlock)
3448                 {
3449                         tryBlock.statements = statements;
3450                         statements = new List<Statement> (1);
3451                         statements.Add (tf);
3452                 }
3453         }
3454
3455         //
3456         // ParametersBlock was introduced to support anonymous methods
3457         // and lambda expressions
3458         // 
3459         public class ParametersBlock : ExplicitBlock
3460         {
3461                 public class ParameterInfo : INamedBlockVariable
3462                 {
3463                         readonly ParametersBlock block;
3464                         readonly int index;
3465                         public VariableInfo VariableInfo;
3466                         bool is_locked;
3467
3468                         public ParameterInfo (ParametersBlock block, int index)
3469                         {
3470                                 this.block = block;
3471                                 this.index = index;
3472                         }
3473
3474                         #region Properties
3475
3476                         public ParametersBlock Block {
3477                                 get {
3478                                         return block;
3479                                 }
3480                         }
3481
3482                         Block INamedBlockVariable.Block {
3483                                 get {
3484                                         return block;
3485                                 }
3486                         }
3487
3488                         public bool IsDeclared {
3489                                 get {
3490                                         return true;
3491                                 }
3492                         }
3493
3494                         public bool IsParameter {
3495                                 get {
3496                                         return true;
3497                                 }
3498                         }
3499
3500                         public bool IsLocked {
3501                                 get {
3502                                         return is_locked;
3503                                 }
3504                                 set {
3505                                         is_locked = value;
3506                                 }
3507                         }
3508
3509                         public Location Location {
3510                                 get {
3511                                         return Parameter.Location;
3512                                 }
3513                         }
3514
3515                         public Parameter Parameter {
3516                                 get {
3517                                         return block.Parameters [index];
3518                                 }
3519                         }
3520
3521                         public TypeSpec ParameterType {
3522                                 get {
3523                                         return Parameter.Type;
3524                                 }
3525                         }
3526
3527                         #endregion
3528
3529                         public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
3530                         {
3531                                 return new ParameterReference (this, loc);
3532                         }
3533                 }
3534
3535                 // 
3536                 // Block is converted into an expression
3537                 //
3538                 sealed class BlockScopeExpression : Expression
3539                 {
3540                         Expression child;
3541                         readonly ParametersBlock block;
3542
3543                         public BlockScopeExpression (Expression child, ParametersBlock block)
3544                         {
3545                                 this.child = child;
3546                                 this.block = block;
3547                         }
3548
3549                         public override bool ContainsEmitWithAwait ()
3550                         {
3551                                 return child.ContainsEmitWithAwait ();
3552                         }
3553
3554                         public override Expression CreateExpressionTree (ResolveContext ec)
3555                         {
3556                                 throw new NotSupportedException ();
3557                         }
3558
3559                         protected override Expression DoResolve (ResolveContext ec)
3560                         {
3561                                 if (child == null)
3562                                         return null;
3563
3564                                 child = child.Resolve (ec);
3565                                 if (child == null)
3566                                         return null;
3567
3568                                 eclass = child.eclass;
3569                                 type = child.Type;
3570                                 return this;
3571                         }
3572
3573                         public override void Emit (EmitContext ec)
3574                         {
3575                                 block.EmitScopeInitializers (ec);
3576                                 child.Emit (ec);
3577                         }
3578                 }
3579
3580                 protected ParametersCompiled parameters;
3581                 protected ParameterInfo[] parameter_info;
3582                 protected bool resolved;
3583                 protected ToplevelBlock top_block;
3584                 protected StateMachine state_machine;
3585                 protected Dictionary<string, object> labels;
3586
3587                 public ParametersBlock (Block parent, ParametersCompiled parameters, Location start, Flags flags = 0)
3588                         : base (parent, 0, start, start)
3589                 {
3590                         if (parameters == null)
3591                                 throw new ArgumentNullException ("parameters");
3592
3593                         this.parameters = parameters;
3594                         ParametersBlock = this;
3595
3596                         this.flags |= flags | (parent.ParametersBlock.flags & (Flags.YieldBlock | Flags.AwaitBlock));
3597
3598                         this.top_block = parent.ParametersBlock.top_block;
3599                         ProcessParameters ();
3600                 }
3601
3602                 protected ParametersBlock (ParametersCompiled parameters, Location start)
3603                         : base (null, 0, start, start)
3604                 {
3605                         if (parameters == null)
3606                                 throw new ArgumentNullException ("parameters");
3607
3608                         this.parameters = parameters;
3609                         ParametersBlock = this;
3610                 }
3611
3612                 //
3613                 // It's supposed to be used by method body implementation of anonymous methods
3614                 //
3615                 protected ParametersBlock (ParametersBlock source, ParametersCompiled parameters)
3616                         : base (null, 0, source.StartLocation, source.EndLocation)
3617                 {
3618                         this.parameters = parameters;
3619                         this.statements = source.statements;
3620                         this.scope_initializers = source.scope_initializers;
3621
3622                         this.resolved = true;
3623                         this.reachable = source.reachable;
3624                         this.am_storey = source.am_storey;
3625                         this.state_machine = source.state_machine;
3626                         this.flags = source.flags & Flags.ReachableEnd;
3627
3628                         ParametersBlock = this;
3629
3630                         //
3631                         // Overwrite original for comparison purposes when linking cross references
3632                         // between anonymous methods
3633                         //
3634                         Original = source.Original;
3635                 }
3636
3637                 #region Properties
3638
3639                 public bool IsAsync {
3640                         get {
3641                                 return (flags & Flags.HasAsyncModifier) != 0;
3642                         }
3643                         set {
3644                                 flags = value ? flags | Flags.HasAsyncModifier : flags & ~Flags.HasAsyncModifier;
3645                         }
3646                 }
3647
3648                 //
3649                 // Block has been converted to expression tree
3650                 //
3651                 public bool IsExpressionTree {
3652                         get {
3653                                 return (flags & Flags.IsExpressionTree) != 0;
3654                         }
3655                 }
3656
3657                 //
3658                 // The parameters for the block.
3659                 //
3660                 public ParametersCompiled Parameters {
3661                         get {
3662                                 return parameters;
3663                         }
3664                 }
3665
3666                 public StateMachine StateMachine {
3667                         get {
3668                                 return state_machine;
3669                         }
3670                 }
3671
3672                 public ToplevelBlock TopBlock {
3673                         get {
3674                                 return top_block;
3675                         }
3676                         set {
3677                                 top_block = value;
3678                         }
3679                 }
3680
3681                 public bool Resolved {
3682                         get {
3683                                 return (flags & Flags.Resolved) != 0;
3684                         }
3685                 }
3686
3687                 public int TemporaryLocalsCount { get; set; }
3688
3689                 #endregion
3690
3691                 //
3692                 // Checks whether all `out' parameters have been assigned.
3693                 //
3694                 public void CheckControlExit (FlowAnalysisContext fc)
3695                 {
3696                         CheckControlExit (fc, fc.DefiniteAssignment);
3697                 }
3698
3699                 public virtual void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
3700                 {
3701                         if (parameter_info == null)
3702                                 return;
3703
3704                         foreach (var p in parameter_info) {
3705                                 if (p.VariableInfo == null)
3706                                         continue;
3707
3708                                 if (p.VariableInfo.IsAssigned (dat))
3709                                         continue;
3710
3711                                 fc.Report.Error (177, p.Location,
3712                                         "The out parameter `{0}' must be assigned to before control leaves the current method",
3713                                         p.Parameter.Name);
3714                         }                                       
3715                 }
3716
3717                 protected override void CloneTo (CloneContext clonectx, Statement t)
3718                 {
3719                         base.CloneTo (clonectx, t);
3720
3721                         var target = (ParametersBlock) t;
3722
3723                         //
3724                         // Clone label statements as well as they contain block reference
3725                         //
3726                         var pb = this;
3727                         while (true) {
3728                                 if (pb.labels != null) {
3729                                         target.labels = new Dictionary<string, object> ();
3730
3731                                         foreach (var entry in pb.labels) {
3732                                                 var list = entry.Value as List<LabeledStatement>;
3733
3734                                                 if (list != null) {
3735                                                         var list_clone = new List<LabeledStatement> ();
3736                                                         foreach (var lentry in list) {
3737                                                                 list_clone.Add (RemapLabeledStatement (lentry, clonectx.RemapBlockCopy (lentry.Block)));
3738                                                         }
3739
3740                                                         target.labels.Add (entry.Key, list_clone);
3741                                                 } else {
3742                                                         var labeled = (LabeledStatement) entry.Value;
3743                                                         target.labels.Add (entry.Key, RemapLabeledStatement (labeled, clonectx.RemapBlockCopy (labeled.Block)));
3744                                                 }
3745                                         }
3746
3747                                         break;
3748                                 }
3749
3750                                 if (pb.Parent == null)
3751                                         break;
3752
3753                                 pb = pb.Parent.ParametersBlock;
3754                         }
3755                 }
3756
3757                 public override Expression CreateExpressionTree (ResolveContext ec)
3758                 {
3759                         if (statements.Count == 1) {
3760                                 Expression expr = statements[0].CreateExpressionTree (ec);
3761                                 if (scope_initializers != null)
3762                                         expr = new BlockScopeExpression (expr, this);
3763
3764                                 return expr;
3765                         }
3766
3767                         return base.CreateExpressionTree (ec);
3768                 }
3769
3770                 public override void Emit (EmitContext ec)
3771                 {
3772                         if (state_machine != null && state_machine.OriginalSourceBlock != this) {
3773                                 DefineStoreyContainer (ec, state_machine);
3774                                 state_machine.EmitStoreyInstantiation (ec, this);
3775                         }
3776
3777                         base.Emit (ec);
3778                 }
3779
3780                 public void EmitEmbedded (EmitContext ec)
3781                 {
3782                         if (state_machine != null && state_machine.OriginalSourceBlock != this) {
3783                                 DefineStoreyContainer (ec, state_machine);
3784                                 state_machine.EmitStoreyInstantiation (ec, this);
3785                         }
3786
3787                         base.Emit (ec);
3788                 }
3789
3790                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
3791                 {
3792                         var res = base.DoFlowAnalysis (fc);
3793
3794                         if (HasReachableClosingBrace)
3795                                 CheckControlExit (fc);
3796
3797                         return res;
3798                 }
3799
3800                 public LabeledStatement GetLabel (string name, Block block)
3801                 {
3802                         //
3803                         // Cloned parameters blocks can have their own cloned version of top-level labels
3804                         //
3805                         if (labels == null) {
3806                                 if (Parent != null)
3807                                         return Parent.ParametersBlock.GetLabel (name, block);
3808
3809                                 return null;
3810                         }
3811
3812                         object value;
3813                         if (!labels.TryGetValue (name, out value)) {
3814                                 return null;
3815                         }
3816
3817                         var label = value as LabeledStatement;
3818                         Block b = block;
3819                         if (label != null) {
3820                                 if (IsLabelVisible (label, b))
3821                                         return label;
3822
3823                         } else {
3824                                 List<LabeledStatement> list = (List<LabeledStatement>) value;
3825                                 for (int i = 0; i < list.Count; ++i) {
3826                                         label = list[i];
3827                                         if (IsLabelVisible (label, b))
3828                                                 return label;
3829                                 }
3830                         }
3831
3832                         return null;
3833                 }
3834
3835                 static bool IsLabelVisible (LabeledStatement label, Block b)
3836                 {
3837                         do {
3838                                 if (label.Block == b)
3839                                         return true;
3840                                 b = b.Parent;
3841                         } while (b != null);
3842
3843                         return false;
3844                 }
3845
3846                 public ParameterInfo GetParameterInfo (Parameter p)
3847                 {
3848                         for (int i = 0; i < parameters.Count; ++i) {
3849                                 if (parameters[i] == p)
3850                                         return parameter_info[i];
3851                         }
3852
3853                         throw new ArgumentException ("Invalid parameter");
3854                 }
3855
3856                 public ParameterReference GetParameterReference (int index, Location loc)
3857                 {
3858                         return new ParameterReference (parameter_info[index], loc);
3859                 }
3860
3861                 public Statement PerformClone ()
3862                 {
3863                         CloneContext clonectx = new CloneContext ();
3864                         return Clone (clonectx);
3865                 }
3866
3867                 protected void ProcessParameters ()
3868                 {
3869                         if (parameters.Count == 0)
3870                                 return;
3871
3872                         parameter_info = new ParameterInfo[parameters.Count];
3873                         for (int i = 0; i < parameter_info.Length; ++i) {
3874                                 var p = parameters.FixedParameters[i];
3875                                 if (p == null)
3876                                         continue;
3877
3878                                 // TODO: Should use Parameter only and more block there
3879                                 parameter_info[i] = new ParameterInfo (this, i);
3880                                 if (p.Name != null)
3881                                         AddLocalName (p.Name, parameter_info[i]);
3882                         }
3883                 }
3884
3885                 LabeledStatement RemapLabeledStatement (LabeledStatement stmt, Block dst)
3886                 {
3887                         var src = stmt.Block;
3888
3889                         //
3890                         // Cannot remap label block if the label was not yet cloned which
3891                         // can happen in case of anonymous method inside anoynymous method
3892                         // with a label. But in this case we don't care because goto cannot
3893                         // jump of out anonymous method
3894                         //
3895                         if (src.ParametersBlock != this)
3896                                 return stmt;
3897
3898                         var src_stmts = src.Statements;
3899                         for (int i = 0; i < src_stmts.Count; ++i) {
3900                                 if (src_stmts[i] == stmt)
3901                                         return (LabeledStatement) dst.Statements[i];
3902                         }
3903
3904                         throw new InternalErrorException ("Should never be reached");
3905                 }
3906
3907                 public override bool Resolve (BlockContext bc)
3908                 {
3909                         // TODO: if ((flags & Flags.Resolved) != 0)
3910
3911                         if (resolved)
3912                                 return true;
3913
3914                         resolved = true;
3915
3916                         if (bc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
3917                                 flags |= Flags.IsExpressionTree;
3918
3919                         try {
3920                                 PrepareAssignmentAnalysis (bc);
3921
3922                                 if (!base.Resolve (bc))
3923                                         return false;
3924
3925                         } catch (Exception e) {
3926                                 if (e is CompletionResult || bc.Report.IsDisabled || e is FatalException || bc.Report.Printer is NullReportPrinter || bc.Module.Compiler.Settings.BreakOnInternalError)
3927                                         throw;
3928
3929                                 if (bc.CurrentBlock != null) {
3930                                         bc.Report.Error (584, bc.CurrentBlock.StartLocation, "Internal compiler error: {0}", e.Message);
3931                                 } else {
3932                                         bc.Report.Error (587, "Internal compiler error: {0}", e.Message);
3933                                 }
3934                         }
3935
3936                         //
3937                         // If an asynchronous body of F is either an expression classified as nothing, or a 
3938                         // statement block where no return statements have expressions, the inferred return type is Task
3939                         //
3940                         if (IsAsync) {
3941                                 var am = bc.CurrentAnonymousMethod as AnonymousMethodBody;
3942                                 if (am != null && am.ReturnTypeInference != null && !am.ReturnTypeInference.HasBounds (0)) {
3943                                         am.ReturnTypeInference = null;
3944                                         am.ReturnType = bc.Module.PredefinedTypes.Task.TypeSpec;
3945                                         return true;
3946                                 }
3947                         }
3948
3949                         return true;
3950                 }
3951
3952                 void PrepareAssignmentAnalysis (BlockContext bc)
3953                 {
3954                         for (int i = 0; i < parameters.Count; ++i) {
3955                                 var par = parameters.FixedParameters[i];
3956
3957                                 if ((par.ModFlags & Parameter.Modifier.OUT) == 0)
3958                                         continue;
3959
3960                                 parameter_info [i].VariableInfo = VariableInfo.Create (bc, (Parameter) par);
3961                         }
3962                 }
3963
3964                 public ToplevelBlock ConvertToIterator (IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
3965                 {
3966                         var iterator = new Iterator (this, method, host, iterator_type, is_enumerable);
3967                         var stateMachine = new IteratorStorey (iterator);
3968
3969                         state_machine = stateMachine;
3970                         iterator.SetStateMachine (stateMachine);
3971
3972                         var tlb = new ToplevelBlock (host.Compiler, Parameters, Location.Null, Flags.CompilerGenerated);
3973                         tlb.Original = this;
3974                         tlb.state_machine = stateMachine;
3975                         tlb.AddStatement (new Return (iterator, iterator.Location));
3976                         return tlb;
3977                 }
3978
3979                 public ParametersBlock ConvertToAsyncTask (IMemberContext context, TypeDefinition host, ParametersCompiled parameters, TypeSpec returnType, TypeSpec delegateType, Location loc)
3980                 {
3981                         for (int i = 0; i < parameters.Count; i++) {
3982                                 Parameter p = parameters[i];
3983                                 Parameter.Modifier mod = p.ModFlags;
3984                                 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
3985                                         host.Compiler.Report.Error (1988, p.Location,
3986                                                 "Async methods cannot have ref or out parameters");
3987                                         return this;
3988                                 }
3989
3990                                 if (p is ArglistParameter) {
3991                                         host.Compiler.Report.Error (4006, p.Location,
3992                                                 "__arglist is not allowed in parameter list of async methods");
3993                                         return this;
3994                                 }
3995
3996                                 if (parameters.Types[i].IsPointer) {
3997                                         host.Compiler.Report.Error (4005, p.Location,
3998                                                 "Async methods cannot have unsafe parameters");
3999                                         return this;
4000                                 }
4001                         }
4002
4003                         if (!HasAwait) {
4004                                 host.Compiler.Report.Warning (1998, 1, loc,
4005                                         "Async block lacks `await' operator and will run synchronously");
4006                         }
4007
4008                         var block_type = host.Module.Compiler.BuiltinTypes.Void;
4009                         var initializer = new AsyncInitializer (this, host, block_type);
4010                         initializer.Type = block_type;
4011                         initializer.DelegateType = delegateType;
4012
4013                         var stateMachine = new AsyncTaskStorey (this, context, initializer, returnType);
4014
4015                         state_machine = stateMachine;
4016                         initializer.SetStateMachine (stateMachine);
4017
4018                         const Flags flags = Flags.CompilerGenerated;
4019
4020                         var b = this is ToplevelBlock ?
4021                                 new ToplevelBlock (host.Compiler, Parameters, Location.Null, flags) :
4022                                 new ParametersBlock (Parent, parameters, Location.Null, flags | Flags.HasAsyncModifier);
4023
4024                         b.Original = this;
4025                         b.state_machine = stateMachine;
4026                         b.AddStatement (new AsyncInitializerStatement (initializer));
4027                         return b;
4028                 }
4029         }
4030
4031         //
4032         //
4033         //
4034         public class ToplevelBlock : ParametersBlock
4035         {
4036                 LocalVariable this_variable;
4037                 CompilerContext compiler;
4038                 Dictionary<string, object> names;
4039
4040                 List<ExplicitBlock> this_references;
4041
4042                 public ToplevelBlock (CompilerContext ctx, Location loc)
4043                         : this (ctx, ParametersCompiled.EmptyReadOnlyParameters, loc)
4044                 {
4045                 }
4046
4047                 public ToplevelBlock (CompilerContext ctx, ParametersCompiled parameters, Location start, Flags flags = 0)
4048                         : base (parameters, start)
4049                 {
4050                         this.compiler = ctx;
4051                         this.flags = flags;
4052                         top_block = this;
4053
4054                         ProcessParameters ();
4055                 }
4056
4057                 //
4058                 // Recreates a top level block from parameters block. Used for
4059                 // compiler generated methods where the original block comes from
4060                 // explicit child block. This works for already resolved blocks
4061                 // only to ensure we resolve them in the correct flow order
4062                 //
4063                 public ToplevelBlock (ParametersBlock source, ParametersCompiled parameters)
4064                         : base (source, parameters)
4065                 {
4066                         this.compiler = source.TopBlock.compiler;
4067                         top_block = this;
4068                 }
4069
4070                 public bool IsIterator {
4071                         get {
4072                                 return (flags & Flags.Iterator) != 0;
4073                         }
4074                         set {
4075                                 flags = value ? flags | Flags.Iterator : flags & ~Flags.Iterator;
4076                         }
4077                 }
4078
4079                 public Report Report {
4080                         get {
4081                                 return compiler.Report;
4082                         }
4083                 }
4084
4085                 //
4086                 // Used by anonymous blocks to track references of `this' variable
4087                 //
4088                 public List<ExplicitBlock> ThisReferencesFromChildrenBlock {
4089                         get {
4090                                 return this_references;
4091                         }
4092                 }
4093
4094                 //
4095                 // Returns the "this" instance variable of this block.
4096                 // See AddThisVariable() for more information.
4097                 //
4098                 public LocalVariable ThisVariable {
4099                         get {
4100                                 return this_variable;
4101                         }
4102                 }
4103
4104                 public void AddLocalName (string name, INamedBlockVariable li, bool ignoreChildrenBlocks)
4105                 {
4106                         if (names == null)
4107                                 names = new Dictionary<string, object> ();
4108
4109                         object value;
4110                         if (!names.TryGetValue (name, out value)) {
4111                                 names.Add (name, li);
4112                                 return;
4113                         }
4114
4115                         INamedBlockVariable existing = value as INamedBlockVariable;
4116                         List<INamedBlockVariable> existing_list;
4117                         if (existing != null) {
4118                                 existing_list = new List<INamedBlockVariable> ();
4119                                 existing_list.Add (existing);
4120                                 names[name] = existing_list;
4121                         } else {
4122                                 existing_list = (List<INamedBlockVariable>) value;
4123                         }
4124
4125                         //
4126                         // A collision checking between local names
4127                         //
4128                         var variable_block = li.Block.Explicit;
4129                         for (int i = 0; i < existing_list.Count; ++i) {
4130                                 existing = existing_list[i];
4131                                 Block b = existing.Block.Explicit;
4132
4133                                 // Collision at same level
4134                                 if (variable_block == b) {
4135                                         li.Block.Error_AlreadyDeclared (name, li);
4136                                         break;
4137                                 }
4138
4139                                 // Collision with parent
4140                                 Block parent = variable_block;
4141                                 while ((parent = parent.Parent) != null) {
4142                                         if (parent == b) {
4143                                                 li.Block.Error_AlreadyDeclared (name, li, "parent or current");
4144                                                 i = existing_list.Count;
4145                                                 break;
4146                                         }
4147                                 }
4148
4149                                 if (!ignoreChildrenBlocks && variable_block.Parent != b.Parent) {
4150                                         // Collision with children
4151                                         while ((b = b.Parent) != null) {
4152                                                 if (variable_block == b) {
4153                                                         li.Block.Error_AlreadyDeclared (name, li, "child");
4154                                                         i = existing_list.Count;
4155                                                         break;
4156                                                 }
4157                                         }
4158                                 }
4159                         }
4160
4161                         existing_list.Add (li);
4162                 }
4163
4164                 public void AddLabel (string name, LabeledStatement label)
4165                 {
4166                         if (labels == null)
4167                                 labels = new Dictionary<string, object> ();
4168
4169                         object value;
4170                         if (!labels.TryGetValue (name, out value)) {
4171                                 labels.Add (name, label);
4172                                 return;
4173                         }
4174
4175                         LabeledStatement existing = value as LabeledStatement;
4176                         List<LabeledStatement> existing_list;
4177                         if (existing != null) {
4178                                 existing_list = new List<LabeledStatement> ();
4179                                 existing_list.Add (existing);
4180                                 labels[name] = existing_list;
4181                         } else {
4182                                 existing_list = (List<LabeledStatement>) value;
4183                         }
4184
4185                         //
4186                         // A collision checking between labels
4187                         //
4188                         for (int i = 0; i < existing_list.Count; ++i) {
4189                                 existing = existing_list[i];
4190                                 Block b = existing.Block;
4191
4192                                 // Collision at same level
4193                                 if (label.Block == b) {
4194                                         Report.SymbolRelatedToPreviousError (existing.loc, name);
4195                                         Report.Error (140, label.loc, "The label `{0}' is a duplicate", name);
4196                                         break;
4197                                 }
4198
4199                                 // Collision with parent
4200                                 b = label.Block;
4201                                 while ((b = b.Parent) != null) {
4202                                         if (existing.Block == b) {
4203                                                 Report.Error (158, label.loc,
4204                                                         "The label `{0}' shadows another label by the same name in a contained scope", name);
4205                                                 i = existing_list.Count;
4206                                                 break;
4207                                         }
4208                                 }
4209
4210                                 // Collision with with children
4211                                 b = existing.Block;
4212                                 while ((b = b.Parent) != null) {
4213                                         if (label.Block == b) {
4214                                                 Report.Error (158, label.loc,
4215                                                         "The label `{0}' shadows another label by the same name in a contained scope", name);
4216                                                 i = existing_list.Count;
4217                                                 break;
4218                                         }
4219                                 }
4220                         }
4221
4222                         existing_list.Add (label);
4223                 }
4224
4225                 public void AddThisReferenceFromChildrenBlock (ExplicitBlock block)
4226                 {
4227                         if (this_references == null)
4228                                 this_references = new List<ExplicitBlock> ();
4229
4230                         if (!this_references.Contains (block))
4231                                 this_references.Add (block);
4232                 }
4233
4234                 public void RemoveThisReferenceFromChildrenBlock (ExplicitBlock block)
4235                 {
4236                         this_references.Remove (block);
4237                 }
4238
4239                 //
4240                 // Creates an arguments set from all parameters, useful for method proxy calls
4241                 //
4242                 public Arguments GetAllParametersArguments ()
4243                 {
4244                         int count = parameters.Count;
4245                         Arguments args = new Arguments (count);
4246                         for (int i = 0; i < count; ++i) {
4247                                 var pi = parameter_info[i];
4248                                 var arg_expr = GetParameterReference (i, pi.Location);
4249
4250                                 Argument.AType atype_modifier;
4251                                 switch (pi.Parameter.ParameterModifier & Parameter.Modifier.RefOutMask) {
4252                                 case Parameter.Modifier.REF:
4253                                         atype_modifier = Argument.AType.Ref;
4254                                         break;
4255                                 case Parameter.Modifier.OUT:
4256                                         atype_modifier = Argument.AType.Out;
4257                                         break;
4258                                 default:
4259                                         atype_modifier = 0;
4260                                         break;
4261                                 }
4262
4263                                 args.Add (new Argument (arg_expr, atype_modifier));
4264                         }
4265
4266                         return args;
4267                 }
4268
4269                 //
4270                 // Lookup inside a block, the returned value can represent 3 states
4271                 //
4272                 // true+variable: A local name was found and it's valid
4273                 // false+variable: A local name was found in a child block only
4274                 // false+null: No local name was found
4275                 //
4276                 public bool GetLocalName (string name, Block block, ref INamedBlockVariable variable)
4277                 {
4278                         if (names == null)
4279                                 return false;
4280
4281                         object value;
4282                         if (!names.TryGetValue (name, out value))
4283                                 return false;
4284
4285                         variable = value as INamedBlockVariable;
4286                         Block b = block;
4287                         if (variable != null) {
4288                                 do {
4289                                         if (variable.Block == b.Original)
4290                                                 return true;
4291
4292                                         b = b.Parent;
4293                                 } while (b != null);
4294
4295                                 b = variable.Block;
4296                                 do {
4297                                         if (block == b)
4298                                                 return false;
4299
4300                                         b = b.Parent;
4301                                 } while (b != null);
4302                         } else {
4303                                 List<INamedBlockVariable> list = (List<INamedBlockVariable>) value;
4304                                 for (int i = 0; i < list.Count; ++i) {
4305                                         variable = list[i];
4306                                         do {
4307                                                 if (variable.Block == b.Original)
4308                                                         return true;
4309
4310                                                 b = b.Parent;
4311                                         } while (b != null);
4312
4313                                         b = variable.Block;
4314                                         do {
4315                                                 if (block == b)
4316                                                         return false;
4317
4318                                                 b = b.Parent;
4319                                         } while (b != null);
4320
4321                                         b = block;
4322                                 }
4323                         }
4324
4325                         variable = null;
4326                         return false;
4327                 }
4328
4329                 public void IncludeBlock (ParametersBlock pb, ToplevelBlock block)
4330                 {
4331                         if (block.names != null) {
4332                                 foreach (var n in block.names) {
4333                                         var variable = n.Value as INamedBlockVariable;
4334                                         if (variable != null) {
4335                                                 if (variable.Block.ParametersBlock == pb)
4336                                                         AddLocalName (n.Key, variable, false);
4337                                                 continue;
4338                                         }
4339
4340                                         foreach (var v in (List<INamedBlockVariable>) n.Value)
4341                                                 if (v.Block.ParametersBlock == pb)
4342                                                         AddLocalName (n.Key, v, false);
4343                                 }
4344                         }
4345                 }
4346
4347                 // <summary>
4348                 //   This is used by non-static `struct' constructors which do not have an
4349                 //   initializer - in this case, the constructor must initialize all of the
4350                 //   struct's fields.  To do this, we add a "this" variable and use the flow
4351                 //   analysis code to ensure that it's been fully initialized before control
4352                 //   leaves the constructor.
4353                 // </summary>
4354                 public void AddThisVariable (BlockContext bc)
4355                 {
4356                         if (this_variable != null)
4357                                 throw new InternalErrorException (StartLocation.ToString ());
4358
4359                         this_variable = new LocalVariable (this, "this", LocalVariable.Flags.IsThis | LocalVariable.Flags.Used, StartLocation);
4360                         this_variable.Type = bc.CurrentType;
4361                         this_variable.PrepareAssignmentAnalysis (bc);
4362                 }
4363
4364                 public override void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
4365                 {
4366                         //
4367                         // If we're a non-static struct constructor which doesn't have an
4368                         // initializer, then we must initialize all of the struct's fields.
4369                         //
4370                         if (this_variable != null)
4371                                 this_variable.IsThisAssigned (fc, this);
4372
4373                         base.CheckControlExit (fc, dat);
4374                 }
4375
4376                 public override void Emit (EmitContext ec)
4377                 {
4378                         if (Report.Errors > 0)
4379                                 return;
4380
4381                         try {
4382                         if (IsCompilerGenerated) {
4383                                 using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
4384                                         base.Emit (ec);
4385                                 }
4386                         } else {
4387                                 base.Emit (ec);
4388                         }
4389
4390                         //
4391                         // If `HasReturnLabel' is set, then we already emitted a
4392                         // jump to the end of the method, so we must emit a `ret'
4393                         // there.
4394                         //
4395                         // Unfortunately, System.Reflection.Emit automatically emits
4396                         // a leave to the end of a finally block.  This is a problem
4397                         // if no code is following the try/finally block since we may
4398                         // jump to a point after the end of the method.
4399                         // As a workaround, we're always creating a return label in
4400                         // this case.
4401                         //
4402                         if (ec.HasReturnLabel || HasReachableClosingBrace) {
4403                                 if (ec.HasReturnLabel)
4404                                         ec.MarkLabel (ec.ReturnLabel);
4405
4406                                 if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated)
4407                                         ec.Mark (EndLocation);
4408
4409                                 if (ec.ReturnType.Kind != MemberKind.Void)
4410                                         ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4411
4412                                 ec.Emit (OpCodes.Ret);
4413                         }
4414
4415                         } catch (Exception e) {
4416                                 throw new InternalErrorException (e, StartLocation);
4417                         }
4418                 }
4419
4420                 public bool Resolve (BlockContext bc, IMethodData md)
4421                 {
4422                         if (resolved)
4423                                 return true;
4424
4425                         var errors = bc.Report.Errors;
4426
4427                         base.Resolve (bc);
4428
4429                         if (bc.Report.Errors > errors)
4430                                 return false;
4431
4432                         MarkReachable (new Reachability ());
4433
4434                         if (HasReachableClosingBrace && bc.ReturnType.Kind != MemberKind.Void) {
4435                                 // TODO: var md = bc.CurrentMemberDefinition;
4436                                 bc.Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
4437                         }
4438
4439                         if ((flags & Flags.NoFlowAnalysis) != 0)
4440                                 return true;
4441
4442                         var fc = new FlowAnalysisContext (bc.Module.Compiler, this, bc.AssignmentInfoOffset);
4443                         try {
4444                                 FlowAnalysis (fc);
4445                         } catch (Exception e) {
4446                                 throw new InternalErrorException (e, StartLocation);
4447                         }
4448
4449                         return true;
4450                 }
4451         }
4452         
4453         public class SwitchLabel : Statement
4454         {
4455                 Constant converted;
4456                 Expression label;
4457
4458                 Label? il_label;
4459
4460                 //
4461                 // if expr == null, then it is the default case.
4462                 //
4463                 public SwitchLabel (Expression expr, Location l)
4464                 {
4465                         label = expr;
4466                         loc = l;
4467                 }
4468
4469                 public bool IsDefault {
4470                         get {
4471                                 return label == null;
4472                         }
4473                 }
4474
4475                 public Expression Label {
4476                         get {
4477                                 return label;
4478                         }
4479                 }
4480
4481                 public Location Location {
4482                         get {
4483                                 return loc;
4484                         }
4485                 }
4486
4487                 public Constant Converted {
4488                         get {
4489                                 return converted;
4490                         }
4491                         set {
4492                                 converted = value; 
4493                         }
4494                 }
4495
4496                 public bool PatternMatching { get; set; }
4497
4498                 public bool SectionStart { get; set; }
4499
4500                 public Label GetILLabel (EmitContext ec)
4501                 {
4502                         if (il_label == null){
4503                                 il_label = ec.DefineLabel ();
4504                         }
4505
4506                         return il_label.Value;
4507                 }
4508
4509                 protected override void DoEmit (EmitContext ec)
4510                 {
4511                         ec.MarkLabel (GetILLabel (ec));
4512                 }
4513
4514                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4515                 {
4516                         if (!SectionStart)
4517                                 return false;
4518
4519                         fc.BranchDefiniteAssignment (fc.SwitchInitialDefinitiveAssignment);
4520                         return false;
4521                 }
4522
4523                 public override bool Resolve (BlockContext bc)
4524                 {
4525                         if (ResolveAndReduce (bc))
4526                                 bc.Switch.RegisterLabel (bc, this);
4527
4528                         return true;
4529                 }
4530
4531                 //
4532                 // Resolves the expression, reduces it to a literal if possible
4533                 // and then converts it to the requested type.
4534                 //
4535                 bool ResolveAndReduce (BlockContext bc)
4536                 {
4537                         if (IsDefault)
4538                                 return true;
4539
4540                         var switch_statement = bc.Switch;
4541
4542                         if (PatternMatching) {
4543                                 label = new Is (switch_statement.ExpressionValue, label, loc).Resolve (bc);
4544                                 return label != null;
4545                         }
4546
4547                         var c = label.ResolveLabelConstant (bc);
4548                         if (c == null)
4549                                 return false;
4550
4551                         if (switch_statement.IsNullable && c is NullLiteral) {
4552                                 converted = c;
4553                                 return true;
4554                         }
4555
4556                         if (switch_statement.IsPatternMatching) {
4557                                 label = new Is (switch_statement.ExpressionValue, label, loc).Resolve (bc);
4558                                 return true;
4559                         }
4560
4561                         converted = c.ImplicitConversionRequired (bc, switch_statement.SwitchType);
4562                         return converted != null;
4563                 }
4564
4565                 public void Error_AlreadyOccurs (ResolveContext ec, SwitchLabel collision_with)
4566                 {
4567                         ec.Report.SymbolRelatedToPreviousError (collision_with.loc, null);
4568                         ec.Report.Error (152, loc, "The label `{0}' already occurs in this switch statement", GetSignatureForError ());
4569                 }
4570
4571                 protected override void CloneTo (CloneContext clonectx, Statement target)
4572                 {
4573                         var t = (SwitchLabel) target;
4574                         if (label != null)
4575                                 t.label = label.Clone (clonectx);
4576                 }
4577
4578                 public override object Accept (StructuralVisitor visitor)
4579                 {
4580                         return visitor.Visit (this);
4581                 }
4582
4583                 public string GetSignatureForError ()
4584                 {
4585                         string label;
4586                         if (converted == null)
4587                                 label = "default";
4588                         else
4589                                 label = converted.GetValueAsLiteral ();
4590
4591                         return string.Format ("case {0}:", label);
4592                 }
4593         }
4594
4595         public class Switch : LoopStatement
4596         {
4597                 // structure used to hold blocks of keys while calculating table switch
4598                 sealed class LabelsRange : IComparable<LabelsRange>
4599                 {
4600                         public readonly long min;
4601                         public long max;
4602                         public readonly List<long> label_values;
4603
4604                         public LabelsRange (long value)
4605                         {
4606                                 min = max = value;
4607                                 label_values = new List<long> ();
4608                                 label_values.Add (value);
4609                         }
4610
4611                         public LabelsRange (long min, long max, ICollection<long> values)
4612                         {
4613                                 this.min = min;
4614                                 this.max = max;
4615                                 this.label_values = new List<long> (values);
4616                         }
4617
4618                         public long Range {
4619                                 get {
4620                                         return max - min + 1;
4621                                 }
4622                         }
4623
4624                         public bool AddValue (long value)
4625                         {
4626                                 var gap = value - min + 1;
4627                                 // Ensure the range has > 50% occupancy
4628                                 if (gap > 2 * (label_values.Count + 1) || gap <= 0)
4629                                         return false;
4630
4631                                 max = value;
4632                                 label_values.Add (value);
4633                                 return true;
4634                         }
4635
4636                         public int CompareTo (LabelsRange other)
4637                         {
4638                                 int nLength = label_values.Count;
4639                                 int nLengthOther = other.label_values.Count;
4640                                 if (nLengthOther == nLength)
4641                                         return (int) (other.min - min);
4642
4643                                 return nLength - nLengthOther;
4644                         }
4645                 }
4646
4647                 sealed class DispatchStatement : Statement
4648                 {
4649                         readonly Switch body;
4650
4651                         public DispatchStatement (Switch body)
4652                         {
4653                                 this.body = body;
4654                         }
4655
4656                         protected override void CloneTo (CloneContext clonectx, Statement target)
4657                         {
4658                                 throw new NotImplementedException ();
4659                         }
4660
4661                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4662                         {
4663                                 return false;
4664                         }
4665
4666                         protected override void DoEmit (EmitContext ec)
4667                         {
4668                                 body.EmitDispatch (ec);
4669                         }
4670                 }
4671
4672                 class MissingBreak : Statement
4673                 {
4674                         readonly SwitchLabel label;
4675
4676                         public MissingBreak (SwitchLabel sl)
4677                         {
4678                                 this.label = sl;
4679                                 this.loc = sl.loc;
4680                         }
4681
4682                         public bool FallOut { get; set; }
4683
4684                         protected override void DoEmit (EmitContext ec)
4685                         {
4686                         }
4687
4688                         protected override void CloneTo (CloneContext clonectx, Statement target)
4689                         {
4690                         }
4691
4692                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
4693                         {
4694                                 if (FallOut) {
4695                                         fc.Report.Error (8070, loc, "Control cannot fall out of switch statement through final case label `{0}'",
4696                                                 label.GetSignatureForError ());
4697                                 } else {
4698                                         fc.Report.Error (163, loc, "Control cannot fall through from one case label `{0}' to another",
4699                                                 label.GetSignatureForError ());
4700                                 }
4701                                 return true;
4702                         }
4703                 }
4704
4705                 public Expression Expr;
4706
4707                 //
4708                 // Mapping of all labels to their SwitchLabels
4709                 //
4710                 Dictionary<long, SwitchLabel> labels;
4711                 Dictionary<string, SwitchLabel> string_labels;
4712                 List<SwitchLabel> case_labels;
4713
4714                 List<Tuple<GotoCase, Constant>> goto_cases;
4715                 List<DefiniteAssignmentBitSet> end_reachable_das;
4716
4717                 /// <summary>
4718                 ///   The governing switch type
4719                 /// </summary>
4720                 public TypeSpec SwitchType;
4721
4722                 Expression new_expr;
4723
4724                 SwitchLabel case_null;
4725                 SwitchLabel case_default;
4726
4727                 Label defaultLabel, nullLabel;
4728                 VariableReference value;
4729                 ExpressionStatement string_dictionary;
4730                 FieldExpr switch_cache_field;
4731                 ExplicitBlock block;
4732                 bool end_reachable;
4733
4734                 //
4735                 // Nullable Types support
4736                 //
4737                 Nullable.Unwrap unwrap;
4738
4739                 public Switch (Expression e, ExplicitBlock block, Location l)
4740                         : base (block)
4741                 {
4742                         Expr = e;
4743                         this.block = block;
4744                         loc = l;
4745                 }
4746
4747                 public SwitchLabel ActiveLabel { get; set; }
4748
4749                 public ExplicitBlock Block {
4750                         get {
4751                                 return block;
4752                         }
4753                 }
4754
4755                 public SwitchLabel DefaultLabel {
4756                         get {
4757                                 return case_default;
4758                         }
4759                 }
4760
4761                 public bool IsNullable {
4762                         get {
4763                                 return unwrap != null;
4764                         }
4765                 }
4766
4767                 public bool IsPatternMatching {
4768                         get {
4769                                 return new_expr == null && SwitchType != null;
4770                         }
4771                 }
4772
4773                 public List<SwitchLabel> RegisteredLabels {
4774                         get {
4775                                 return case_labels;
4776                         }
4777                 }
4778
4779                 public VariableReference ExpressionValue {
4780                         get {
4781                                 return value;
4782                         }
4783                 }
4784
4785                 //
4786                 // Determines the governing type for a switch.  The returned
4787                 // expression might be the expression from the switch, or an
4788                 // expression that includes any potential conversions to
4789                 //
4790                 static Expression SwitchGoverningType (ResolveContext rc, Expression expr, bool unwrapExpr)
4791                 {
4792                         switch (expr.Type.BuiltinType) {
4793                         case BuiltinTypeSpec.Type.Byte:
4794                         case BuiltinTypeSpec.Type.SByte:
4795                         case BuiltinTypeSpec.Type.UShort:
4796                         case BuiltinTypeSpec.Type.Short:
4797                         case BuiltinTypeSpec.Type.UInt:
4798                         case BuiltinTypeSpec.Type.Int:
4799                         case BuiltinTypeSpec.Type.ULong:
4800                         case BuiltinTypeSpec.Type.Long:
4801                         case BuiltinTypeSpec.Type.Char:
4802                         case BuiltinTypeSpec.Type.String:
4803                         case BuiltinTypeSpec.Type.Bool:
4804                                 return expr;
4805                         }
4806
4807                         if (expr.Type.IsEnum)
4808                                 return expr;
4809
4810                         //
4811                         // Try to find a *user* defined implicit conversion.
4812                         //
4813                         // If there is no implicit conversion, or if there are multiple
4814                         // conversions, we have to report an error
4815                         //
4816                         Expression converted = null;
4817                         foreach (TypeSpec tt in rc.Module.PredefinedTypes.SwitchUserTypes) {
4818
4819                                 if (!unwrapExpr && tt.IsNullableType && expr.Type.IsNullableType)
4820                                         break;
4821
4822                                 var restr = Convert.UserConversionRestriction.ImplicitOnly |
4823                                         Convert.UserConversionRestriction.ProbingOnly;
4824
4825                                 if (unwrapExpr)
4826                                         restr |= Convert.UserConversionRestriction.NullableSourceOnly;
4827
4828                                 var e = Convert.UserDefinedConversion (rc, expr, tt, restr, Location.Null);
4829                                 if (e == null)
4830                                         continue;
4831
4832                                 //
4833                                 // Ignore over-worked ImplicitUserConversions that do
4834                                 // an implicit conversion in addition to the user conversion.
4835                                 // 
4836                                 var uc = e as UserCast;
4837                                 if (uc == null)
4838                                         continue;
4839
4840                                 if (converted != null){
4841 //                                      rc.Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
4842                                         return null;
4843                                 }
4844
4845                                 converted = e;
4846                         }
4847                         return converted;
4848                 }
4849
4850                 public static TypeSpec[] CreateSwitchUserTypes (ModuleContainer module, TypeSpec nullable)
4851                 {
4852                         var types = module.Compiler.BuiltinTypes;
4853
4854                         // LAMESPEC: For some reason it does not contain bool which looks like csc bug
4855                         TypeSpec[] stypes = new[] {
4856                                 types.SByte,
4857                                 types.Byte,
4858                                 types.Short,
4859                                 types.UShort,
4860                                 types.Int,
4861                                 types.UInt,
4862                                 types.Long,
4863                                 types.ULong,
4864                                 types.Char,
4865                                 types.String
4866                         };
4867
4868                         if (nullable != null) {
4869
4870                                 Array.Resize (ref stypes, stypes.Length + 9);
4871
4872                                 for (int i = 0; i < 9; ++i) {
4873                                         stypes [10 + i] = nullable.MakeGenericType (module, new [] { stypes [i] });
4874                                 }
4875                         }
4876
4877                         return stypes;
4878                 }
4879
4880                 public void RegisterLabel (BlockContext rc, SwitchLabel sl)
4881                 {
4882                         case_labels.Add (sl);
4883
4884                         if (sl.IsDefault) {
4885                                 if (case_default != null) {
4886                                         sl.Error_AlreadyOccurs (rc, case_default);
4887                                 } else {
4888                                         case_default = sl;
4889                                 }
4890
4891                                 return;
4892                         }
4893
4894                         if (sl.Converted == null)
4895                                 return;
4896
4897                         try {
4898                                 if (string_labels != null) {
4899                                         string string_value = sl.Converted.GetValue () as string;
4900                                         if (string_value == null)
4901                                                 case_null = sl;
4902                                         else
4903                                                 string_labels.Add (string_value, sl);
4904                                 } else {
4905                                         if (sl.Converted.IsNull) {
4906                                                 case_null = sl;
4907                                         } else {
4908                                                 labels.Add (sl.Converted.GetValueAsLong (), sl);
4909                                         }
4910                                 }
4911                         } catch (ArgumentException) {
4912                                 if (string_labels != null)
4913                                         sl.Error_AlreadyOccurs (rc, string_labels[(string) sl.Converted.GetValue ()]);
4914                                 else
4915                                         sl.Error_AlreadyOccurs (rc, labels[sl.Converted.GetValueAsLong ()]);
4916                         }
4917                 }
4918                 
4919                 //
4920                 // This method emits code for a lookup-based switch statement (non-string)
4921                 // Basically it groups the cases into blocks that are at least half full,
4922                 // and then spits out individual lookup opcodes for each block.
4923                 // It emits the longest blocks first, and short blocks are just
4924                 // handled with direct compares.
4925                 //
4926                 void EmitTableSwitch (EmitContext ec, Expression val)
4927                 {
4928                         if (labels != null && labels.Count > 0) {
4929                                 List<LabelsRange> ranges;
4930                                 if (string_labels != null) {
4931                                         // We have done all hard work for string already
4932                                         // setup single range only
4933                                         ranges = new List<LabelsRange> (1);
4934                                         ranges.Add (new LabelsRange (0, labels.Count - 1, labels.Keys));
4935                                 } else {
4936                                         var element_keys = new long[labels.Count];
4937                                         labels.Keys.CopyTo (element_keys, 0);
4938                                         Array.Sort (element_keys);
4939
4940                                         //
4941                                         // Build possible ranges of switch labes to reduce number
4942                                         // of comparisons
4943                                         //
4944                                         ranges = new List<LabelsRange> (element_keys.Length);
4945                                         var range = new LabelsRange (element_keys[0]);
4946                                         ranges.Add (range);
4947                                         for (int i = 1; i < element_keys.Length; ++i) {
4948                                                 var l = element_keys[i];
4949                                                 if (range.AddValue (l))
4950                                                         continue;
4951
4952                                                 range = new LabelsRange (l);
4953                                                 ranges.Add (range);
4954                                         }
4955
4956                                         // sort the blocks so we can tackle the largest ones first
4957                                         ranges.Sort ();
4958                                 }
4959
4960                                 Label lbl_default = defaultLabel;
4961                                 TypeSpec compare_type = SwitchType.IsEnum ? EnumSpec.GetUnderlyingType (SwitchType) : SwitchType;
4962
4963                                 for (int range_index = ranges.Count - 1; range_index >= 0; --range_index) {
4964                                         LabelsRange kb = ranges[range_index];
4965                                         lbl_default = (range_index == 0) ? defaultLabel : ec.DefineLabel ();
4966
4967                                         // Optimize small ranges using simple equality check
4968                                         if (kb.Range <= 2) {
4969                                                 foreach (var key in kb.label_values) {
4970                                                         SwitchLabel sl = labels[key];
4971                                                         if (sl == case_default || sl == case_null)
4972                                                                 continue;
4973
4974                                                         if (sl.Converted.IsZeroInteger) {
4975                                                                 val.EmitBranchable (ec, sl.GetILLabel (ec), false);
4976                                                         } else {
4977                                                                 val.Emit (ec);
4978                                                                 sl.Converted.Emit (ec);
4979                                                                 ec.Emit (OpCodes.Beq, sl.GetILLabel (ec));
4980                                                         }
4981                                                 }
4982                                         } else {
4983                                                 // TODO: if all the keys in the block are the same and there are
4984                                                 //       no gaps/defaults then just use a range-check.
4985                                                 if (compare_type.BuiltinType == BuiltinTypeSpec.Type.Long || compare_type.BuiltinType == BuiltinTypeSpec.Type.ULong) {
4986                                                         // TODO: optimize constant/I4 cases
4987
4988                                                         // check block range (could be > 2^31)
4989                                                         val.Emit (ec);
4990                                                         ec.EmitLong (kb.min);
4991                                                         ec.Emit (OpCodes.Blt, lbl_default);
4992
4993                                                         val.Emit (ec);
4994                                                         ec.EmitLong (kb.max);
4995                                                         ec.Emit (OpCodes.Bgt, lbl_default);
4996
4997                                                         // normalize range
4998                                                         val.Emit (ec);
4999                                                         if (kb.min != 0) {
5000                                                                 ec.EmitLong (kb.min);
5001                                                                 ec.Emit (OpCodes.Sub);
5002                                                         }
5003
5004                                                         ec.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
5005                                                 } else {
5006                                                         // normalize range
5007                                                         val.Emit (ec);
5008                                                         int first = (int) kb.min;
5009                                                         if (first > 0) {
5010                                                                 ec.EmitInt (first);
5011                                                                 ec.Emit (OpCodes.Sub);
5012                                                         } else if (first < 0) {
5013                                                                 ec.EmitInt (-first);
5014                                                                 ec.Emit (OpCodes.Add);
5015                                                         }
5016                                                 }
5017
5018                                                 // first, build the list of labels for the switch
5019                                                 int iKey = 0;
5020                                                 long cJumps = kb.Range;
5021                                                 Label[] switch_labels = new Label[cJumps];
5022                                                 for (int iJump = 0; iJump < cJumps; iJump++) {
5023                                                         var key = kb.label_values[iKey];
5024                                                         if (key == kb.min + iJump) {
5025                                                                 switch_labels[iJump] = labels[key].GetILLabel (ec);
5026                                                                 iKey++;
5027                                                         } else {
5028                                                                 switch_labels[iJump] = lbl_default;
5029                                                         }
5030                                                 }
5031
5032                                                 // emit the switch opcode
5033                                                 ec.Emit (OpCodes.Switch, switch_labels);
5034                                         }
5035
5036                                         // mark the default for this block
5037                                         if (range_index != 0)
5038                                                 ec.MarkLabel (lbl_default);
5039                                 }
5040
5041                                 // the last default just goes to the end
5042                                 if (ranges.Count > 0)
5043                                         ec.Emit (OpCodes.Br, lbl_default);
5044                         }
5045                 }
5046                 
5047                 public SwitchLabel FindLabel (Constant value)
5048                 {
5049                         SwitchLabel sl = null;
5050
5051                         if (string_labels != null) {
5052                                 string s = value.GetValue () as string;
5053                                 if (s == null) {
5054                                         if (case_null != null)
5055                                                 sl = case_null;
5056                                         else if (case_default != null)
5057                                                 sl = case_default;
5058                                 } else {
5059                                         string_labels.TryGetValue (s, out sl);
5060                                 }
5061                         } else {
5062                                 if (value is NullLiteral) {
5063                                         sl = case_null;
5064                                 } else {
5065                                         labels.TryGetValue (value.GetValueAsLong (), out sl);
5066                                 }
5067                         }
5068
5069                         if (sl == null || sl.SectionStart)
5070                                 return sl;
5071
5072                         //
5073                         // Always return section start, it simplifies handling of switch labels
5074                         //
5075                         for (int idx = case_labels.IndexOf (sl); ; --idx) {
5076                                 var cs = case_labels [idx];
5077                                 if (cs.SectionStart)
5078                                         return cs;
5079                         }
5080                 }
5081
5082                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
5083                 {
5084                         Expr.FlowAnalysis (fc);
5085
5086                         var prev_switch = fc.SwitchInitialDefinitiveAssignment;
5087                         var InitialDefinitiveAssignment = fc.DefiniteAssignment;
5088                         fc.SwitchInitialDefinitiveAssignment = InitialDefinitiveAssignment;
5089
5090                         block.FlowAnalysis (fc);
5091
5092                         fc.SwitchInitialDefinitiveAssignment = prev_switch;
5093
5094                         if (end_reachable_das != null) {
5095                                 var sections_das = DefiniteAssignmentBitSet.And (end_reachable_das);
5096                                 InitialDefinitiveAssignment |= sections_das;
5097                                 end_reachable_das = null;
5098                         }
5099
5100                         fc.DefiniteAssignment = InitialDefinitiveAssignment;
5101
5102                         return case_default != null && !end_reachable;
5103                 }
5104
5105                 public override bool Resolve (BlockContext ec)
5106                 {
5107                         Expr = Expr.Resolve (ec);
5108                         if (Expr == null)
5109                                 return false;
5110
5111                         //
5112                         // LAMESPEC: User conversion from non-nullable governing type has a priority
5113                         //
5114                         new_expr = SwitchGoverningType (ec, Expr, false);
5115
5116                         if (new_expr == null) {
5117                                 if (Expr.Type.IsNullableType) {
5118                                         unwrap = Nullable.Unwrap.Create (Expr, false);
5119                                         if (unwrap == null)
5120                                                 return false;
5121
5122                                         //
5123                                         // Unwrap + user conversion using non-nullable type is not allowed but user operator
5124                                         // involving nullable Expr and nullable governing type is
5125                                         //
5126                                         new_expr = SwitchGoverningType (ec, unwrap, true);
5127                                 }
5128                         }
5129
5130                         Expression switch_expr;
5131                         if (new_expr == null) {
5132                                 if (ec.Module.Compiler.Settings.Version != LanguageVersion.Experimental) {
5133                                         if (Expr.Type != InternalType.ErrorType) {
5134                                                 ec.Report.Error (151, loc,
5135                                                         "A switch expression of type `{0}' cannot be converted to an integral type, bool, char, string, enum or nullable type",
5136                                                         Expr.Type.GetSignatureForError ());
5137                                         }
5138
5139                                         return false;
5140                                 }
5141
5142                                 switch_expr = Expr;
5143                                 SwitchType = Expr.Type;
5144                         } else {
5145                                 switch_expr = new_expr;
5146                                 SwitchType = new_expr.Type;
5147                                 if (SwitchType.IsNullableType) {
5148                                         new_expr = unwrap = Nullable.Unwrap.Create (new_expr, true);
5149                                         SwitchType = Nullable.NullableInfo.GetUnderlyingType (SwitchType);
5150                                 }
5151
5152                                 if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.Bool && ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
5153                                         ec.Report.FeatureIsNotAvailable (ec.Module.Compiler, loc, "switch expression of boolean type");
5154                                         return false;
5155                                 }
5156
5157                                 if (block.Statements.Count == 0)
5158                                         return true;
5159
5160                                 if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
5161                                         string_labels = new Dictionary<string, SwitchLabel> ();
5162                                 } else {
5163                                         labels = new Dictionary<long, SwitchLabel> ();
5164                                 }
5165                         }
5166
5167                         var constant = switch_expr as Constant;
5168
5169                         //
5170                         // Don't need extra variable for constant switch or switch with
5171                         // only default case
5172                         //
5173                         if (constant == null) {
5174                                 //
5175                                 // Store switch expression for comparison purposes
5176                                 //
5177                                 value = switch_expr as VariableReference;
5178                                 if (value == null && !HasOnlyDefaultSection ()) {
5179                                         var current_block = ec.CurrentBlock;
5180                                         ec.CurrentBlock = Block;
5181                                         // Create temporary variable inside switch scope
5182                                         value = TemporaryVariableReference.Create (SwitchType, ec.CurrentBlock, loc);
5183                                         value.Resolve (ec);
5184                                         ec.CurrentBlock = current_block;
5185                                 }
5186                         }
5187
5188                         case_labels = new List<SwitchLabel> ();
5189
5190                         Switch old_switch = ec.Switch;
5191                         ec.Switch = this;
5192                         var parent_los = ec.EnclosingLoopOrSwitch;
5193                         ec.EnclosingLoopOrSwitch = this;
5194
5195                         var ok = Statement.Resolve (ec);
5196
5197                         ec.EnclosingLoopOrSwitch = parent_los;
5198                         ec.Switch = old_switch;
5199
5200                         //
5201                         // Check if all goto cases are valid. Needs to be done after switch
5202                         // is resolved because goto can jump forward in the scope.
5203                         //
5204                         if (goto_cases != null) {
5205                                 foreach (var gc in goto_cases) {
5206                                         if (gc.Item1 == null) {
5207                                                 if (DefaultLabel == null) {
5208                                                         Goto.Error_UnknownLabel (ec, "default", loc);
5209                                                 }
5210
5211                                                 continue;
5212                                         }
5213
5214                                         var sl = FindLabel (gc.Item2);
5215                                         if (sl == null) {
5216                                                 Goto.Error_UnknownLabel (ec, "case " + gc.Item2.GetValueAsLiteral (), loc);
5217                                         } else {
5218                                                 gc.Item1.Label = sl;
5219                                         }
5220                                 }
5221                         }
5222
5223                         if (!ok)
5224                                 return false;
5225
5226                         if (constant == null && SwitchType.BuiltinType == BuiltinTypeSpec.Type.String && string_labels.Count > 6) {
5227                                 ResolveStringSwitchMap (ec);
5228                         }
5229
5230                         //
5231                         // Anonymous storey initialization has to happen before
5232                         // any generated switch dispatch
5233                         //
5234                         block.InsertStatement (0, new DispatchStatement (this));
5235
5236                         return true;
5237                 }
5238
5239                 bool HasOnlyDefaultSection ()
5240                 {
5241                         for (int i = 0; i < block.Statements.Count; ++i) {
5242                                 var s = block.Statements[i] as SwitchLabel;
5243
5244                                 if (s == null || s.IsDefault)
5245                                         continue;
5246
5247                                 return false;
5248                         }
5249
5250                         return true;
5251                 }
5252
5253                 public override Reachability MarkReachable (Reachability rc)
5254                 {
5255                         if (rc.IsUnreachable)
5256                                 return rc;
5257
5258                         base.MarkReachable (rc);
5259
5260                         block.MarkReachableScope (rc);
5261
5262                         if (block.Statements.Count == 0)
5263                                 return rc;
5264
5265                         SwitchLabel constant_label = null;
5266                         var constant = new_expr as Constant;
5267
5268                         if (constant != null) {
5269                                 constant_label = FindLabel (constant) ?? case_default;
5270                                 if (constant_label == null) {
5271                                         block.Statements.RemoveAt (0);
5272                                         return rc;
5273                                 }
5274                         }
5275
5276                         var section_rc = new Reachability ();
5277                         SwitchLabel prev_label = null;
5278
5279                         for (int i = 0; i < block.Statements.Count; ++i) {
5280                                 var s = block.Statements[i];
5281                                 var sl = s as SwitchLabel;
5282
5283                                 if (sl != null && sl.SectionStart) {
5284                                         //
5285                                         // Section is marked already via goto case
5286                                         //
5287                                         if (!sl.IsUnreachable) {
5288                                                 section_rc = new Reachability ();
5289                                                 continue;
5290                                         }
5291
5292                                         if (constant_label != null && constant_label != sl)
5293                                                 section_rc = Reachability.CreateUnreachable ();
5294                                         else if (section_rc.IsUnreachable) {
5295                                                 section_rc = new Reachability ();
5296                                         } else {
5297                                                 if (prev_label != null) {
5298                                                         sl.SectionStart = false;
5299                                                         s = new MissingBreak (prev_label);
5300                                                         s.MarkReachable (rc);
5301                                                         block.Statements.Insert (i - 1, s);
5302                                                         ++i;
5303                                                 }
5304                                         }
5305
5306                                         prev_label = sl;
5307                                 }
5308
5309                                 section_rc = s.MarkReachable (section_rc);
5310                         }
5311
5312                         if (!section_rc.IsUnreachable && prev_label != null) {
5313                                 prev_label.SectionStart = false;
5314                                 var s = new MissingBreak (prev_label) {
5315                                         FallOut = true
5316                                 };
5317
5318                                 s.MarkReachable (rc);
5319                                 block.Statements.Add (s);
5320                         }
5321
5322                         //
5323                         // Reachability can affect parent only when all possible paths are handled but
5324                         // we still need to run reachability check on switch body to check for fall-through
5325                         //
5326                         if (case_default == null && constant_label == null)
5327                                 return rc;
5328
5329                         //
5330                         // We have at least one local exit from the switch
5331                         //
5332                         if (end_reachable)
5333                                 return rc;
5334
5335                         return Reachability.CreateUnreachable ();
5336                 }
5337
5338                 public void RegisterGotoCase (GotoCase gotoCase, Constant value)
5339                 {
5340                         if (goto_cases == null)
5341                                 goto_cases = new List<Tuple<GotoCase, Constant>> ();
5342
5343                         goto_cases.Add (Tuple.Create (gotoCase, value));
5344                 }
5345
5346                 //
5347                 // Converts string switch into string hashtable
5348                 //
5349                 void ResolveStringSwitchMap (ResolveContext ec)
5350                 {
5351                         FullNamedExpression string_dictionary_type;
5352                         if (ec.Module.PredefinedTypes.Dictionary.Define ()) {
5353                                 string_dictionary_type = new TypeExpression (
5354                                         ec.Module.PredefinedTypes.Dictionary.TypeSpec.MakeGenericType (ec,
5355                                                 new [] { ec.BuiltinTypes.String, ec.BuiltinTypes.Int }),
5356                                         loc);
5357                         } else if (ec.Module.PredefinedTypes.Hashtable.Define ()) {
5358                                 string_dictionary_type = new TypeExpression (ec.Module.PredefinedTypes.Hashtable.TypeSpec, loc);
5359                         } else {
5360                                 ec.Module.PredefinedTypes.Dictionary.Resolve ();
5361                                 return;
5362                         }
5363
5364                         var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
5365                         Field field = new Field (ctype, string_dictionary_type,
5366                                 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
5367                                 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "switch$map", ec.Module.CounterSwitchTypes++), loc), null);
5368                         if (!field.Define ())
5369                                 return;
5370                         ctype.AddField (field);
5371
5372                         var init = new List<Expression> ();
5373                         int counter = -1;
5374                         labels = new Dictionary<long, SwitchLabel> (string_labels.Count);
5375                         string value = null;
5376
5377                         foreach (SwitchLabel sl in case_labels) {
5378
5379                                 if (sl.SectionStart)
5380                                         labels.Add (++counter, sl);
5381
5382                                 if (sl == case_default || sl == case_null)
5383                                         continue;
5384
5385                                 value = (string) sl.Converted.GetValue ();
5386                                 var init_args = new List<Expression> (2);
5387                                 init_args.Add (new StringLiteral (ec.BuiltinTypes, value, sl.Location));
5388
5389                                 sl.Converted = new IntConstant (ec.BuiltinTypes, counter, loc);
5390                                 init_args.Add (sl.Converted);
5391
5392                                 init.Add (new CollectionElementInitializer (init_args, loc));
5393                         }
5394         
5395                         Arguments args = new Arguments (1);
5396                         args.Add (new Argument (new IntConstant (ec.BuiltinTypes, init.Count, loc)));
5397                         Expression initializer = new NewInitialize (string_dictionary_type, args,
5398                                 new CollectionOrObjectInitializers (init, loc), loc);
5399
5400                         switch_cache_field = new FieldExpr (field, loc);
5401                         string_dictionary = new SimpleAssign (switch_cache_field, initializer.Resolve (ec));
5402                 }
5403
5404                 void DoEmitStringSwitch (EmitContext ec)
5405                 {
5406                         Label l_initialized = ec.DefineLabel ();
5407
5408                         //
5409                         // Skip initialization when value is null
5410                         //
5411                         value.EmitBranchable (ec, nullLabel, false);
5412
5413                         //
5414                         // Check if string dictionary is initialized and initialize
5415                         //
5416                         switch_cache_field.EmitBranchable (ec, l_initialized, true);
5417                         using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
5418                                 string_dictionary.EmitStatement (ec);
5419                         }
5420                         ec.MarkLabel (l_initialized);
5421
5422                         LocalTemporary string_switch_variable = new LocalTemporary (ec.BuiltinTypes.Int);
5423
5424                         ResolveContext rc = new ResolveContext (ec.MemberContext);
5425
5426                         if (switch_cache_field.Type.IsGeneric) {
5427                                 Arguments get_value_args = new Arguments (2);
5428                                 get_value_args.Add (new Argument (value));
5429                                 get_value_args.Add (new Argument (string_switch_variable, Argument.AType.Out));
5430                                 Expression get_item = new Invocation (new MemberAccess (switch_cache_field, "TryGetValue", loc), get_value_args).Resolve (rc);
5431                                 if (get_item == null)
5432                                         return;
5433
5434                                 //
5435                                 // A value was not found, go to default case
5436                                 //
5437                                 get_item.EmitBranchable (ec, defaultLabel, false);
5438                         } else {
5439                                 Arguments get_value_args = new Arguments (1);
5440                                 get_value_args.Add (new Argument (value));
5441
5442                                 Expression get_item = new ElementAccess (switch_cache_field, get_value_args, loc).Resolve (rc);
5443                                 if (get_item == null)
5444                                         return;
5445
5446                                 LocalTemporary get_item_object = new LocalTemporary (ec.BuiltinTypes.Object);
5447                                 get_item_object.EmitAssign (ec, get_item, true, false);
5448                                 ec.Emit (OpCodes.Brfalse, defaultLabel);
5449
5450                                 ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
5451                                         new Cast (new TypeExpression (ec.BuiltinTypes.Int, loc), get_item_object, loc)).Resolve (rc);
5452
5453                                 get_item_int.EmitStatement (ec);
5454                                 get_item_object.Release (ec);
5455                         }
5456
5457                         EmitTableSwitch (ec, string_switch_variable);
5458                         string_switch_variable.Release (ec);
5459                 }
5460
5461                 //
5462                 // Emits switch using simple if/else comparison for small label count (4 + optional default)
5463                 //
5464                 void EmitShortSwitch (EmitContext ec)
5465                 {
5466                         MethodSpec equal_method = null;
5467                         if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
5468                                 equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (loc);
5469                         }
5470
5471                         if (equal_method != null) {
5472                                 value.EmitBranchable (ec, nullLabel, false);
5473                         }
5474
5475                         for (int i = 0; i < case_labels.Count; ++i) {
5476                                 var label = case_labels [i];
5477                                 if (label == case_default || label == case_null)
5478                                         continue;
5479
5480                                 var constant = label.Converted;
5481
5482                                 if (constant == null) {
5483                                         label.Label.EmitBranchable (ec, label.GetILLabel (ec), true);
5484                                         continue;
5485                                 }
5486
5487                                 if (equal_method != null) {
5488                                         value.Emit (ec);
5489                                         constant.Emit (ec);
5490
5491                                         var call = new CallEmitter ();
5492                                         call.EmitPredefined (ec, equal_method, new Arguments (0));
5493                                         ec.Emit (OpCodes.Brtrue, label.GetILLabel (ec));
5494                                         continue;
5495                                 }
5496
5497                                 if (constant.IsZeroInteger && constant.Type.BuiltinType != BuiltinTypeSpec.Type.Long && constant.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
5498                                         value.EmitBranchable (ec, label.GetILLabel (ec), false);
5499                                         continue;
5500                                 }
5501
5502                                 value.Emit (ec);
5503                                 constant.Emit (ec);
5504                                 ec.Emit (OpCodes.Beq, label.GetILLabel (ec));
5505                         }
5506
5507                         ec.Emit (OpCodes.Br, defaultLabel);
5508                 }
5509
5510                 void EmitDispatch (EmitContext ec)
5511                 {
5512                         if (IsPatternMatching) {
5513                                 EmitShortSwitch (ec);
5514                                 return;
5515                         }
5516
5517                         if (value == null) {
5518                                 //
5519                                 // Constant switch, we've already done the work if there is only 1 label
5520                                 // referenced
5521                                 //
5522                                 int reachable = 0;
5523                                 foreach (var sl in case_labels) {
5524                                         if (sl.IsUnreachable)
5525                                                 continue;
5526
5527                                         if (reachable++ > 0) {
5528                                                 var constant = (Constant) new_expr;
5529                                                 var constant_label = FindLabel (constant) ?? case_default;
5530
5531                                                 ec.Emit (OpCodes.Br, constant_label.GetILLabel (ec));
5532                                                 break;
5533                                         }
5534                                 }
5535
5536                                 return;
5537                         }
5538
5539                         if (string_dictionary != null) {
5540                                 DoEmitStringSwitch (ec);
5541                         } else if (case_labels.Count < 4 || string_labels != null) {
5542                                 EmitShortSwitch (ec);
5543                         } else {
5544                                 EmitTableSwitch (ec, value);
5545                         }
5546                 }
5547
5548                 protected override void DoEmit (EmitContext ec)
5549                 {
5550                         //
5551                         // Setup the codegen context
5552                         //
5553                         Label old_end = ec.LoopEnd;
5554                         Switch old_switch = ec.Switch;
5555
5556                         ec.LoopEnd = ec.DefineLabel ();
5557                         ec.Switch = this;
5558
5559                         defaultLabel = case_default == null ? ec.LoopEnd : case_default.GetILLabel (ec);
5560                         nullLabel = case_null == null ? defaultLabel : case_null.GetILLabel (ec);
5561
5562                         if (value != null) {
5563                                 ec.Mark (loc);
5564
5565                                 var switch_expr = new_expr ?? Expr;
5566                                 if (IsNullable) {
5567                                         unwrap.EmitCheck (ec);
5568                                         ec.Emit (OpCodes.Brfalse, nullLabel);
5569                                         value.EmitAssign (ec, switch_expr, false, false);
5570                                 } else if (switch_expr != value) {
5571                                         value.EmitAssign (ec, switch_expr, false, false);
5572                                 }
5573
5574
5575                                 //
5576                                 // Next statement is compiler generated we don't need extra
5577                                 // nop when we can use the statement for sequence point
5578                                 //
5579                                 ec.Mark (block.StartLocation);
5580                                 block.IsCompilerGenerated = true;
5581                         } else {
5582                                 new_expr.EmitSideEffect (ec);
5583                         }
5584
5585                         block.Emit (ec);
5586
5587                         // Restore context state. 
5588                         ec.MarkLabel (ec.LoopEnd);
5589
5590                         //
5591                         // Restore the previous context
5592                         //
5593                         ec.LoopEnd = old_end;
5594                         ec.Switch = old_switch;
5595                 }
5596
5597                 protected override void CloneTo (CloneContext clonectx, Statement t)
5598                 {
5599                         Switch target = (Switch) t;
5600
5601                         target.Expr = Expr.Clone (clonectx);
5602                         target.Statement = target.block = (ExplicitBlock) block.Clone (clonectx);
5603                 }
5604                 
5605                 public override object Accept (StructuralVisitor visitor)
5606                 {
5607                         return visitor.Visit (this);
5608                 }
5609
5610                 public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
5611                 {
5612                         if (case_default == null && !(new_expr is Constant))
5613                                 return;
5614
5615                         if (end_reachable_das == null)
5616                                 end_reachable_das = new List<DefiniteAssignmentBitSet> ();
5617
5618                         end_reachable_das.Add (fc.DefiniteAssignment);
5619                 }
5620
5621                 public override void SetEndReachable ()
5622                 {
5623                         end_reachable = true;
5624                 }
5625         }
5626
5627         // A place where execution can restart in a state machine
5628         public abstract class ResumableStatement : Statement
5629         {
5630                 bool prepared;
5631                 protected Label resume_point;
5632
5633                 public Label PrepareForEmit (EmitContext ec)
5634                 {
5635                         if (!prepared) {
5636                                 prepared = true;
5637                                 resume_point = ec.DefineLabel ();
5638                         }
5639                         return resume_point;
5640                 }
5641
5642                 public virtual Label PrepareForDispose (EmitContext ec, Label end)
5643                 {
5644                         return end;
5645                 }
5646
5647                 public virtual void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
5648                 {
5649                 }
5650         }
5651
5652         public abstract class TryFinallyBlock : ExceptionStatement
5653         {
5654                 protected Statement stmt;
5655                 Label dispose_try_block;
5656                 bool prepared_for_dispose, emitted_dispose;
5657                 Method finally_host;
5658
5659                 protected TryFinallyBlock (Statement stmt, Location loc)
5660                         : base (loc)
5661                 {
5662                         this.stmt = stmt;
5663                 }
5664
5665                 #region Properties
5666
5667                 public Statement Statement {
5668                         get {
5669                                 return stmt;
5670                         }
5671                 }
5672
5673                 #endregion
5674
5675                 protected abstract void EmitTryBody (EmitContext ec);
5676                 public abstract void EmitFinallyBody (EmitContext ec);
5677
5678                 public override Label PrepareForDispose (EmitContext ec, Label end)
5679                 {
5680                         if (!prepared_for_dispose) {
5681                                 prepared_for_dispose = true;
5682                                 dispose_try_block = ec.DefineLabel ();
5683                         }
5684                         return dispose_try_block;
5685                 }
5686
5687                 protected sealed override void DoEmit (EmitContext ec)
5688                 {
5689                         EmitTryBodyPrepare (ec);
5690                         EmitTryBody (ec);
5691
5692                         bool beginFinally = EmitBeginFinallyBlock (ec);
5693
5694                         Label start_finally = ec.DefineLabel ();
5695                         if (resume_points != null && beginFinally) {
5696                                 var state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
5697
5698                                 ec.Emit (OpCodes.Ldloc, state_machine.SkipFinally);
5699                                 ec.Emit (OpCodes.Brfalse_S, start_finally);
5700                                 ec.Emit (OpCodes.Endfinally);
5701                         }
5702
5703                         ec.MarkLabel (start_finally);
5704
5705                         if (finally_host != null) {
5706                                 finally_host.Define ();
5707                                 finally_host.PrepareEmit ();
5708                                 finally_host.Emit ();
5709
5710                                 // Now it's safe to add, to close it properly and emit sequence points
5711                                 finally_host.Parent.AddMember (finally_host);
5712
5713                                 var ce = new CallEmitter ();
5714                                 ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
5715                                 ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
5716                         } else {
5717                                 EmitFinallyBody (ec);
5718                         }
5719
5720                         if (beginFinally)
5721                                 ec.EndExceptionBlock ();
5722                 }
5723
5724                 public override void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
5725                 {
5726                         if (emitted_dispose)
5727                                 return;
5728
5729                         emitted_dispose = true;
5730
5731                         Label end_of_try = ec.DefineLabel ();
5732
5733                         // Ensure that the only way we can get into this code is through a dispatcher
5734                         if (have_dispatcher)
5735                                 ec.Emit (OpCodes.Br, end);
5736
5737                         ec.BeginExceptionBlock ();
5738
5739                         ec.MarkLabel (dispose_try_block);
5740
5741                         Label[] labels = null;
5742                         for (int i = 0; i < resume_points.Count; ++i) {
5743                                 ResumableStatement s = resume_points[i];
5744                                 Label ret = s.PrepareForDispose (ec, end_of_try);
5745                                 if (ret.Equals (end_of_try) && labels == null)
5746                                         continue;
5747                                 if (labels == null) {
5748                                         labels = new Label[resume_points.Count];
5749                                         for (int j = 0; j < i; ++j)
5750                                                 labels[j] = end_of_try;
5751                                 }
5752                                 labels[i] = ret;
5753                         }
5754
5755                         if (labels != null) {
5756                                 int j;
5757                                 for (j = 1; j < labels.Length; ++j)
5758                                         if (!labels[0].Equals (labels[j]))
5759                                                 break;
5760                                 bool emit_dispatcher = j < labels.Length;
5761
5762                                 if (emit_dispatcher) {
5763                                         ec.Emit (OpCodes.Ldloc, pc);
5764                                         ec.EmitInt (first_resume_pc);
5765                                         ec.Emit (OpCodes.Sub);
5766                                         ec.Emit (OpCodes.Switch, labels);
5767                                 }
5768
5769                                 foreach (ResumableStatement s in resume_points)
5770                                         s.EmitForDispose (ec, pc, end_of_try, emit_dispatcher);
5771                         }
5772
5773                         ec.MarkLabel (end_of_try);
5774
5775                         ec.BeginFinallyBlock ();
5776
5777                         if (finally_host != null) {
5778                                 var ce = new CallEmitter ();
5779                                 ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
5780                                 ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
5781                         } else {
5782                                 EmitFinallyBody (ec);
5783                         }
5784
5785                         ec.EndExceptionBlock ();
5786                 }
5787
5788                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
5789                 {
5790                         var res = stmt.FlowAnalysis (fc);
5791                         parent = null;
5792                         return res;
5793                 }
5794
5795                 protected virtual bool EmitBeginFinallyBlock (EmitContext ec)
5796                 {
5797                         ec.BeginFinallyBlock ();
5798                         return true;
5799                 }
5800
5801                 public override Reachability MarkReachable (Reachability rc)
5802                 {
5803                         base.MarkReachable (rc);
5804                         return Statement.MarkReachable (rc);
5805                 }
5806
5807                 public override bool Resolve (BlockContext bc)
5808                 {
5809                         bool ok;
5810
5811                         parent = bc.CurrentTryBlock;
5812                         bc.CurrentTryBlock = this;
5813
5814                         using (bc.Set (ResolveContext.Options.TryScope)) {
5815                                 ok = stmt.Resolve (bc);
5816                         }
5817
5818                         bc.CurrentTryBlock = parent;
5819
5820                         //
5821                         // Finally block inside iterator is called from MoveNext and
5822                         // Dispose methods that means we need to lift the block into
5823                         // newly created host method to emit the body only once. The
5824                         // original block then simply calls the newly generated method.
5825                         //
5826                         if (bc.CurrentIterator != null && !bc.IsInProbingMode) {
5827                                 var b = stmt as Block;
5828                                 if (b != null && b.Explicit.HasYield) {
5829                                         finally_host = bc.CurrentIterator.CreateFinallyHost (this);
5830                                 }
5831                         }
5832
5833                         return base.Resolve (bc) && ok;
5834                 }
5835         }
5836
5837         //
5838         // Base class for blocks using exception handling
5839         //
5840         public abstract class ExceptionStatement : ResumableStatement
5841         {
5842                 protected List<ResumableStatement> resume_points;
5843                 protected int first_resume_pc;
5844                 protected ExceptionStatement parent;
5845
5846                 protected ExceptionStatement (Location loc)
5847                 {
5848                         this.loc = loc;
5849                 }
5850
5851                 protected virtual void EmitTryBodyPrepare (EmitContext ec)
5852                 {
5853                         StateMachineInitializer state_machine = null;
5854                         if (resume_points != null) {
5855                                 state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
5856
5857                                 ec.EmitInt ((int) IteratorStorey.State.Running);
5858                                 ec.Emit (OpCodes.Stloc, state_machine.CurrentPC);
5859                         }
5860
5861                         ec.BeginExceptionBlock ();
5862
5863                         if (resume_points != null) {
5864                                 ec.MarkLabel (resume_point);
5865
5866                                 // For normal control flow, we want to fall-through the Switch
5867                                 // So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
5868                                 ec.Emit (OpCodes.Ldloc, state_machine.CurrentPC);
5869                                 ec.EmitInt (first_resume_pc);
5870                                 ec.Emit (OpCodes.Sub);
5871
5872                                 Label[] labels = new Label[resume_points.Count];
5873                                 for (int i = 0; i < resume_points.Count; ++i)
5874                                         labels[i] = resume_points[i].PrepareForEmit (ec);
5875                                 ec.Emit (OpCodes.Switch, labels);
5876                         }
5877                 }
5878
5879                 public virtual int AddResumePoint (ResumableStatement stmt, int pc, StateMachineInitializer stateMachine)
5880                 {
5881                         if (parent != null) {
5882                                 // TODO: MOVE to virtual TryCatch
5883                                 var tc = this as TryCatch;
5884                                 var s = tc != null && tc.IsTryCatchFinally ? stmt : this;
5885
5886                                 pc = parent.AddResumePoint (s, pc, stateMachine);
5887                         } else {
5888                                 pc = stateMachine.AddResumePoint (this);
5889                         }
5890
5891                         if (resume_points == null) {
5892                                 resume_points = new List<ResumableStatement> ();
5893                                 first_resume_pc = pc;
5894                         }
5895
5896                         if (pc != first_resume_pc + resume_points.Count)
5897                                 throw new InternalErrorException ("missed an intervening AddResumePoint?");
5898
5899                         resume_points.Add (stmt);
5900                         return pc;
5901                 }
5902         }
5903
5904         public class Lock : TryFinallyBlock
5905         {
5906                 Expression expr;
5907                 TemporaryVariableReference expr_copy;
5908                 TemporaryVariableReference lock_taken;
5909                         
5910                 public Lock (Expression expr, Statement stmt, Location loc)
5911                         : base (stmt, loc)
5912                 {
5913                         this.expr = expr;
5914                 }
5915
5916                 public Expression Expr {
5917                         get {
5918                                 return this.expr;
5919                         }
5920                 }
5921
5922                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
5923                 {
5924                         expr.FlowAnalysis (fc);
5925                         return base.DoFlowAnalysis (fc);
5926                 }
5927
5928                 public override bool Resolve (BlockContext ec)
5929                 {
5930                         expr = expr.Resolve (ec);
5931                         if (expr == null)
5932                                 return false;
5933
5934                         if (!TypeSpec.IsReferenceType (expr.Type) && expr.Type != InternalType.ErrorType) {
5935                                 ec.Report.Error (185, loc,
5936                                         "`{0}' is not a reference type as required by the lock statement",
5937                                         expr.Type.GetSignatureForError ());
5938                         }
5939
5940                         if (expr.Type.IsGenericParameter) {
5941                                 expr = Convert.ImplicitTypeParameterConversion (expr, (TypeParameterSpec)expr.Type, ec.BuiltinTypes.Object);
5942                         }
5943
5944                         VariableReference lv = expr as VariableReference;
5945                         bool locked;
5946                         if (lv != null) {
5947                                 locked = lv.IsLockedByStatement;
5948                                 lv.IsLockedByStatement = true;
5949                         } else {
5950                                 lv = null;
5951                                 locked = false;
5952                         }
5953
5954                         //
5955                         // Have to keep original lock value around to unlock same location
5956                         // in the case of original value has changed or is null
5957                         //
5958                         expr_copy = TemporaryVariableReference.Create (ec.BuiltinTypes.Object, ec.CurrentBlock, loc);
5959                         expr_copy.Resolve (ec);
5960
5961                         //
5962                         // Ensure Monitor methods are available
5963                         //
5964                         if (ResolvePredefinedMethods (ec) > 1) {
5965                                 lock_taken = TemporaryVariableReference.Create (ec.BuiltinTypes.Bool, ec.CurrentBlock, loc);
5966                                 lock_taken.Resolve (ec);
5967                         }
5968
5969                         using (ec.Set (ResolveContext.Options.LockScope)) {
5970                                 base.Resolve (ec);
5971                         }
5972
5973                         if (lv != null) {
5974                                 lv.IsLockedByStatement = locked;
5975                         }
5976
5977                         return true;
5978                 }
5979                 
5980                 protected override void EmitTryBodyPrepare (EmitContext ec)
5981                 {
5982                         expr_copy.EmitAssign (ec, expr);
5983
5984                         if (lock_taken != null) {
5985                                 //
5986                                 // Initialize ref variable
5987                                 //
5988                                 lock_taken.EmitAssign (ec, new BoolLiteral (ec.BuiltinTypes, false, loc));
5989                         } else {
5990                                 //
5991                                 // Monitor.Enter (expr_copy)
5992                                 //
5993                                 expr_copy.Emit (ec);
5994                                 ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter.Get ());
5995                         }
5996
5997                         base.EmitTryBodyPrepare (ec);
5998                 }
5999
6000                 protected override void EmitTryBody (EmitContext ec)
6001                 {
6002                         //
6003                         // Monitor.Enter (expr_copy, ref lock_taken)
6004                         //
6005                         if (lock_taken != null) {
6006                                 expr_copy.Emit (ec);
6007                                 lock_taken.LocalInfo.CreateBuilder (ec);
6008                                 lock_taken.AddressOf (ec, AddressOp.Load);
6009                                 ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter_v4.Get ());
6010                         }
6011
6012                         Statement.Emit (ec);
6013                 }
6014
6015                 public override void EmitFinallyBody (EmitContext ec)
6016                 {
6017                         //
6018                         // if (lock_taken) Monitor.Exit (expr_copy)
6019                         //
6020                         Label skip = ec.DefineLabel ();
6021
6022                         if (lock_taken != null) {
6023                                 lock_taken.Emit (ec);
6024                                 ec.Emit (OpCodes.Brfalse_S, skip);
6025                         }
6026
6027                         expr_copy.Emit (ec);
6028                         var m = ec.Module.PredefinedMembers.MonitorExit.Resolve (loc);
6029                         if (m != null)
6030                                 ec.Emit (OpCodes.Call, m);
6031
6032                         ec.MarkLabel (skip);
6033                 }
6034
6035                 int ResolvePredefinedMethods (ResolveContext rc)
6036                 {
6037                         // Try 4.0 Monitor.Enter (object, ref bool) overload first
6038                         var m = rc.Module.PredefinedMembers.MonitorEnter_v4.Get ();
6039                         if (m != null)
6040                                 return 4;
6041
6042                         m = rc.Module.PredefinedMembers.MonitorEnter.Get ();
6043                         if (m != null)
6044                                 return 1;
6045
6046                         rc.Module.PredefinedMembers.MonitorEnter_v4.Resolve (loc);
6047                         return 0;
6048                 }
6049
6050                 protected override void CloneTo (CloneContext clonectx, Statement t)
6051                 {
6052                         Lock target = (Lock) t;
6053
6054                         target.expr = expr.Clone (clonectx);
6055                         target.stmt = Statement.Clone (clonectx);
6056                 }
6057                 
6058                 public override object Accept (StructuralVisitor visitor)
6059                 {
6060                         return visitor.Visit (this);
6061                 }
6062
6063         }
6064
6065         public class Unchecked : Statement {
6066                 public Block Block;
6067                 
6068                 public Unchecked (Block b, Location loc)
6069                 {
6070                         Block = b;
6071                         b.Unchecked = true;
6072                         this.loc = loc;
6073                 }
6074
6075                 public override bool Resolve (BlockContext ec)
6076                 {
6077                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
6078                                 return Block.Resolve (ec);
6079                 }
6080                 
6081                 protected override void DoEmit (EmitContext ec)
6082                 {
6083                         using (ec.With (EmitContext.Options.CheckedScope, false))
6084                                 Block.Emit (ec);
6085                 }
6086
6087                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6088                 {
6089                         return Block.FlowAnalysis (fc);
6090                 }
6091
6092                 public override Reachability MarkReachable (Reachability rc)
6093                 {
6094                         base.MarkReachable (rc);
6095                         return Block.MarkReachable (rc);
6096                 }
6097
6098                 protected override void CloneTo (CloneContext clonectx, Statement t)
6099                 {
6100                         Unchecked target = (Unchecked) t;
6101
6102                         target.Block = clonectx.LookupBlock (Block);
6103                 }
6104                 
6105                 public override object Accept (StructuralVisitor visitor)
6106                 {
6107                         return visitor.Visit (this);
6108                 }
6109         }
6110
6111         public class Checked : Statement {
6112                 public Block Block;
6113                 
6114                 public Checked (Block b, Location loc)
6115                 {
6116                         Block = b;
6117                         b.Unchecked = false;
6118                         this.loc = loc;
6119                 }
6120
6121                 public override bool Resolve (BlockContext ec)
6122                 {
6123                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
6124                                 return Block.Resolve (ec);
6125                 }
6126
6127                 protected override void DoEmit (EmitContext ec)
6128                 {
6129                         using (ec.With (EmitContext.Options.CheckedScope, true))
6130                                 Block.Emit (ec);
6131                 }
6132
6133                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6134                 {
6135                         return Block.FlowAnalysis (fc);
6136                 }
6137
6138                 public override Reachability MarkReachable (Reachability rc)
6139                 {
6140                         base.MarkReachable (rc);
6141                         return Block.MarkReachable (rc);
6142                 }
6143
6144                 protected override void CloneTo (CloneContext clonectx, Statement t)
6145                 {
6146                         Checked target = (Checked) t;
6147
6148                         target.Block = clonectx.LookupBlock (Block);
6149                 }
6150                 
6151                 public override object Accept (StructuralVisitor visitor)
6152                 {
6153                         return visitor.Visit (this);
6154                 }
6155         }
6156
6157         public class Unsafe : Statement {
6158                 public Block Block;
6159
6160                 public Unsafe (Block b, Location loc)
6161                 {
6162                         Block = b;
6163                         Block.Unsafe = true;
6164                         this.loc = loc;
6165                 }
6166
6167                 public override bool Resolve (BlockContext ec)
6168                 {
6169                         if (ec.CurrentIterator != null)
6170                                 ec.Report.Error (1629, loc, "Unsafe code may not appear in iterators");
6171
6172                         using (ec.Set (ResolveContext.Options.UnsafeScope))
6173                                 return Block.Resolve (ec);
6174                 }
6175                 
6176                 protected override void DoEmit (EmitContext ec)
6177                 {
6178                         Block.Emit (ec);
6179                 }
6180
6181                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6182                 {
6183                         return Block.FlowAnalysis (fc);
6184                 }
6185
6186                 public override Reachability MarkReachable (Reachability rc)
6187                 {
6188                         base.MarkReachable (rc);
6189                         return Block.MarkReachable (rc);
6190                 }
6191
6192                 protected override void CloneTo (CloneContext clonectx, Statement t)
6193                 {
6194                         Unsafe target = (Unsafe) t;
6195
6196                         target.Block = clonectx.LookupBlock (Block);
6197                 }
6198                 
6199                 public override object Accept (StructuralVisitor visitor)
6200                 {
6201                         return visitor.Visit (this);
6202                 }
6203         }
6204
6205         // 
6206         // Fixed statement
6207         //
6208         public class Fixed : Statement
6209         {
6210                 abstract class Emitter : ShimExpression
6211                 {
6212                         protected LocalVariable vi;
6213
6214                         protected Emitter (Expression expr, LocalVariable li)
6215                                 : base (expr)
6216                         {
6217                                 vi = li;
6218                         }
6219
6220                         public abstract void EmitExit (EmitContext ec);
6221
6222                         public override void FlowAnalysis (FlowAnalysisContext fc)
6223                         {
6224                                 expr.FlowAnalysis (fc);
6225                         }
6226                 }
6227
6228                 class ExpressionEmitter : Emitter {
6229                         public ExpressionEmitter (Expression converted, LocalVariable li) :
6230                                 base (converted, li)
6231                         {
6232                         }
6233
6234                         protected override Expression DoResolve (ResolveContext rc)
6235                         {
6236                                 throw new NotImplementedException ();
6237                         }
6238
6239                         public override void Emit (EmitContext ec) {
6240                                 //
6241                                 // Store pointer in pinned location
6242                                 //
6243                                 expr.Emit (ec);
6244                                 vi.EmitAssign (ec);
6245                         }
6246
6247                         public override void EmitExit (EmitContext ec)
6248                         {
6249                                 ec.EmitInt (0);
6250                                 ec.Emit (OpCodes.Conv_U);
6251                                 vi.EmitAssign (ec);
6252                         }
6253                 }
6254
6255                 class StringEmitter : Emitter
6256                 {
6257                         LocalVariable pinned_string;
6258
6259                         public StringEmitter (Expression expr, LocalVariable li)
6260                                 : base (expr, li)
6261                         {
6262                         }
6263
6264                         protected override Expression DoResolve (ResolveContext rc)
6265                         {
6266                                 pinned_string = new LocalVariable (vi.Block, "$pinned",
6267                                         LocalVariable.Flags.FixedVariable | LocalVariable.Flags.CompilerGenerated | LocalVariable.Flags.Used,
6268                                         vi.Location);
6269                                 pinned_string.Type = rc.BuiltinTypes.String;
6270
6271                                 eclass = ExprClass.Variable;
6272                                 type = rc.BuiltinTypes.Int;
6273                                 return this;
6274                         }
6275
6276                         public override void Emit (EmitContext ec)
6277                         {
6278                                 pinned_string.CreateBuilder (ec);
6279
6280                                 expr.Emit (ec);
6281                                 pinned_string.EmitAssign (ec);
6282
6283                                 // TODO: Should use Binary::Add
6284                                 pinned_string.Emit (ec);
6285                                 ec.Emit (OpCodes.Conv_I);
6286
6287                                 var m = ec.Module.PredefinedMembers.RuntimeHelpersOffsetToStringData.Resolve (loc);
6288                                 if (m == null)
6289                                         return;
6290
6291                                 PropertyExpr pe = new PropertyExpr (m, pinned_string.Location);
6292                                 //pe.InstanceExpression = pinned_string;
6293                                 pe.Resolve (new ResolveContext (ec.MemberContext)).Emit (ec);
6294
6295                                 ec.Emit (OpCodes.Add);
6296                                 vi.EmitAssign (ec);
6297                         }
6298
6299                         public override void EmitExit (EmitContext ec)
6300                         {
6301                                 ec.EmitNull ();
6302                                 pinned_string.EmitAssign (ec);
6303                         }
6304                 }
6305
6306                 public class VariableDeclaration : BlockVariable
6307                 {
6308                         public VariableDeclaration (FullNamedExpression type, LocalVariable li)
6309                                 : base (type, li)
6310                         {
6311                         }
6312
6313                         protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
6314                         {
6315                                 if (!Variable.Type.IsPointer && li == Variable) {
6316                                         bc.Report.Error (209, TypeExpression.Location,
6317                                                 "The type of locals declared in a fixed statement must be a pointer type");
6318                                         return null;
6319                                 }
6320
6321                                 var res = initializer.Resolve (bc);
6322                                 if (res == null)
6323                                         return null;
6324
6325                                 //
6326                                 // Case 1: Array
6327                                 //
6328                                 if (res.Type.IsArray) {
6329                                         TypeSpec array_type = TypeManager.GetElementType (res.Type);
6330
6331                                         //
6332                                         // Provided that array_type is unmanaged,
6333                                         //
6334                                         if (!TypeManager.VerifyUnmanaged (bc.Module, array_type, loc))
6335                                                 return null;
6336
6337                                         //
6338                                         // and T* is implicitly convertible to the
6339                                         // pointer type given in the fixed statement.
6340                                         //
6341                                         ArrayPtr array_ptr = new ArrayPtr (res, array_type, loc);
6342
6343                                         Expression converted = Convert.ImplicitConversionRequired (bc, array_ptr.Resolve (bc), li.Type, loc);
6344                                         if (converted == null)
6345                                                 return null;
6346
6347                                         //
6348                                         // fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
6349                                         //
6350                                         converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
6351                                                 new Binary (Binary.Operator.Equality, res, new NullLiteral (loc)),
6352                                                 new Binary (Binary.Operator.Equality, new MemberAccess (res, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc)))),
6353                                                         new NullLiteral (loc),
6354                                                         converted, loc);
6355
6356                                         converted = converted.Resolve (bc);
6357
6358                                         return new ExpressionEmitter (converted, li);
6359                                 }
6360
6361                                 //
6362                                 // Case 2: string
6363                                 //
6364                                 if (res.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
6365                                         return new StringEmitter (res, li).Resolve (bc);
6366                                 }
6367
6368                                 // Case 3: fixed buffer
6369                                 if (res is FixedBufferPtr) {
6370                                         return new ExpressionEmitter (res, li);
6371                                 }
6372
6373                                 bool already_fixed = true;
6374
6375                                 //
6376                                 // Case 4: & object.
6377                                 //
6378                                 Unary u = res as Unary;
6379                                 if (u != null) {
6380                                         if (u.Oper == Unary.Operator.AddressOf) {
6381                                                 IVariableReference vr = u.Expr as IVariableReference;
6382                                                 if (vr == null || !vr.IsFixed) {
6383                                                         already_fixed = false;
6384                                                 }
6385                                         }
6386                                 } else if (initializer is Cast) {
6387                                         bc.Report.Error (254, initializer.Location, "The right hand side of a fixed statement assignment may not be a cast expression");
6388                                         return null;
6389                                 }
6390
6391                                 if (already_fixed) {
6392                                         bc.Report.Error (213, loc, "You cannot use the fixed statement to take the address of an already fixed expression");
6393                                 }
6394
6395                                 res = Convert.ImplicitConversionRequired (bc, res, li.Type, loc);
6396                                 return new ExpressionEmitter (res, li);
6397                         }
6398                 }
6399
6400
6401                 VariableDeclaration decl;
6402                 Statement statement;
6403                 bool has_ret;
6404
6405                 public Fixed (VariableDeclaration decl, Statement stmt, Location l)
6406                 {
6407                         this.decl = decl;
6408                         statement = stmt;
6409                         loc = l;
6410                 }
6411
6412                 #region Properties
6413
6414                 public Statement Statement {
6415                         get {
6416                                 return statement;
6417                         }
6418                 }
6419
6420                 public BlockVariable Variables {
6421                         get {
6422                                 return decl;
6423                         }
6424                 }
6425
6426                 #endregion
6427
6428                 public override bool Resolve (BlockContext bc)
6429                 {
6430                         using (bc.Set (ResolveContext.Options.FixedInitializerScope)) {
6431                                 if (!decl.Resolve (bc))
6432                                         return false;
6433                         }
6434
6435                         return statement.Resolve (bc);
6436                 }
6437
6438                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6439                 {
6440                         decl.FlowAnalysis (fc);
6441                         return statement.FlowAnalysis (fc);
6442                 }
6443                 
6444                 protected override void DoEmit (EmitContext ec)
6445                 {
6446                         decl.Variable.CreateBuilder (ec);
6447                         decl.Initializer.Emit (ec);
6448                         if (decl.Declarators != null) {
6449                                 foreach (var d in decl.Declarators) {
6450                                         d.Variable.CreateBuilder (ec);
6451                                         d.Initializer.Emit (ec);
6452                                 }
6453                         }
6454
6455                         statement.Emit (ec);
6456
6457                         if (has_ret)
6458                                 return;
6459
6460                         //
6461                         // Clear the pinned variable
6462                         //
6463                         ((Emitter) decl.Initializer).EmitExit (ec);
6464                         if (decl.Declarators != null) {
6465                                 foreach (var d in decl.Declarators) {
6466                                         ((Emitter)d.Initializer).EmitExit (ec);
6467                                 }
6468                         }
6469                 }
6470
6471                 public override Reachability MarkReachable (Reachability rc)
6472                 {
6473                         base.MarkReachable (rc);
6474
6475                         decl.MarkReachable (rc);
6476
6477                         rc = statement.MarkReachable (rc);
6478
6479                         // TODO: What if there is local exit?
6480                         has_ret = rc.IsUnreachable;
6481                         return rc;
6482                 }
6483
6484                 protected override void CloneTo (CloneContext clonectx, Statement t)
6485                 {
6486                         Fixed target = (Fixed) t;
6487
6488                         target.decl = (VariableDeclaration) decl.Clone (clonectx);
6489                         target.statement = statement.Clone (clonectx);
6490                 }
6491                 
6492                 public override object Accept (StructuralVisitor visitor)
6493                 {
6494                         return visitor.Visit (this);
6495                 }
6496         }
6497
6498         public class Catch : Statement
6499         {
6500                 class CatchVariableStore : Statement
6501                 {
6502                         readonly Catch ctch;
6503
6504                         public CatchVariableStore (Catch ctch)
6505                         {
6506                                 this.ctch = ctch;
6507                         }
6508
6509                         protected override void CloneTo (CloneContext clonectx, Statement target)
6510                         {
6511                         }
6512
6513                         protected override void DoEmit (EmitContext ec)
6514                         {
6515                                 // Emits catch variable debug information inside correct block
6516                                 ctch.EmitCatchVariableStore (ec);
6517                         }
6518
6519                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6520                         {
6521                                 return true;
6522                         }
6523                 }
6524
6525                 class FilterStatement : Statement
6526                 {
6527                         readonly Catch ctch;
6528
6529                         public FilterStatement (Catch ctch)
6530                         {
6531                                 this.ctch = ctch;
6532                         }
6533
6534                         protected override void CloneTo (CloneContext clonectx, Statement target)
6535                         {
6536                         }
6537
6538                         protected override void DoEmit (EmitContext ec)
6539                         {
6540                                 if (ctch.li != null) {
6541                                         if (ctch.hoisted_temp != null)
6542                                                 ctch.hoisted_temp.Emit (ec);
6543                                         else
6544                                                 ctch.li.Emit (ec);
6545
6546                                         if (!ctch.IsGeneral && ctch.type.Kind == MemberKind.TypeParameter)
6547                                                 ec.Emit (OpCodes.Box, ctch.type);
6548                                 }
6549
6550                                 var expr_start = ec.DefineLabel ();
6551                                 var end = ec.DefineLabel ();
6552
6553                                 ec.Emit (OpCodes.Brtrue_S, expr_start);
6554                                 ec.EmitInt (0);
6555                                 ec.Emit (OpCodes.Br, end);
6556                                 ec.MarkLabel (expr_start);
6557
6558                                 ctch.Filter.Emit (ec);
6559
6560                                 ec.MarkLabel (end);
6561                                 ec.Emit (OpCodes.Endfilter);
6562                                 ec.BeginFilterHandler ();
6563                                 ec.Emit (OpCodes.Pop);
6564                         }
6565
6566                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6567                         {
6568                                 ctch.Filter.FlowAnalysis (fc);
6569                                 return true;
6570                         }
6571
6572                         public override bool Resolve (BlockContext bc)
6573                         {
6574                                 ctch.Filter = ctch.Filter.Resolve (bc);
6575
6576                                 if (ctch.Filter != null) {
6577                                         if (ctch.Filter.ContainsEmitWithAwait ()) {
6578                                                 bc.Report.Error (7094, ctch.Filter.Location, "The `await' operator cannot be used in the filter expression of a catch clause");
6579                                         }
6580
6581                                         var c = ctch.Filter as Constant;
6582                                         if (c != null && !c.IsDefaultValue) {
6583                                                 bc.Report.Warning (7095, 1, ctch.Filter.Location, "Exception filter expression is a constant");
6584                                         }
6585                                 }
6586
6587                                 return true;
6588                         }
6589                 }
6590
6591                 ExplicitBlock block;
6592                 LocalVariable li;
6593                 FullNamedExpression type_expr;
6594                 CompilerAssign assign;
6595                 TypeSpec type;
6596                 LocalTemporary hoisted_temp;
6597
6598                 public Catch (ExplicitBlock block, Location loc)
6599                 {
6600                         this.block = block;
6601                         this.loc = loc;
6602                 }
6603
6604                 #region Properties
6605
6606                 public ExplicitBlock Block {
6607                         get {
6608                                 return block;
6609                         }
6610                 }
6611
6612                 public TypeSpec CatchType {
6613                         get {
6614                                 return type;
6615                         }
6616                 }
6617
6618                 public Expression Filter {
6619                         get; set;
6620                 }
6621
6622                 public bool IsGeneral {
6623                         get {
6624                                 return type_expr == null;
6625                         }
6626                 }
6627
6628                 public FullNamedExpression TypeExpression {
6629                         get {
6630                                 return type_expr;
6631                         }
6632                         set {
6633                                 type_expr = value;
6634                         }
6635                 }
6636
6637                 public LocalVariable Variable {
6638                         get {
6639                                 return li;
6640                         }
6641                         set {
6642                                 li = value;
6643                         }
6644                 }
6645
6646                 #endregion
6647
6648                 protected override void DoEmit (EmitContext ec)
6649                 {
6650                         if (Filter != null) {
6651                                 ec.BeginExceptionFilterBlock ();
6652                                 ec.Emit (OpCodes.Isinst, IsGeneral ? ec.BuiltinTypes.Object : CatchType);
6653
6654                                 if (Block.HasAwait) {
6655                                         Block.EmitScopeInitialization (ec);
6656                                 } else {
6657                                         Block.Emit (ec);
6658                                 }
6659
6660                                 return;
6661                         }
6662
6663                         if (IsGeneral)
6664                                 ec.BeginCatchBlock (ec.BuiltinTypes.Object);
6665                         else
6666                                 ec.BeginCatchBlock (CatchType);
6667
6668                         if (li == null)
6669                                 ec.Emit (OpCodes.Pop);
6670
6671                         if (Block.HasAwait) {
6672                                 if (li != null)
6673                                         EmitCatchVariableStore (ec);
6674                         } else {
6675                                 Block.Emit (ec);
6676                         }
6677                 }
6678
6679                 void EmitCatchVariableStore (EmitContext ec)
6680                 {
6681                         li.CreateBuilder (ec);
6682
6683                         //
6684                         // For hoisted catch variable we have to use a temporary local variable
6685                         // for captured variable initialization during storey setup because variable
6686                         // needs to be on the stack after storey instance for stfld operation
6687                         //
6688                         if (li.HoistedVariant != null) {
6689                                 hoisted_temp = new LocalTemporary (li.Type);
6690                                 hoisted_temp.Store (ec);
6691
6692                                 // switch to assignment from temporary variable and not from top of the stack
6693                                 assign.UpdateSource (hoisted_temp);
6694                         }
6695                 }
6696
6697                 public override bool Resolve (BlockContext bc)
6698                 {
6699                         using (bc.Set (ResolveContext.Options.CatchScope)) {
6700                                 if (type_expr == null) {
6701                                         if (CreateExceptionVariable (bc.Module.Compiler.BuiltinTypes.Object)) {
6702                                                 if (!block.HasAwait || Filter != null)
6703                                                         block.AddScopeStatement (new CatchVariableStore (this));
6704
6705                                                 Expression source = new EmptyExpression (li.Type);
6706                                                 assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
6707                                                 Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
6708                                         }
6709                                 } else {
6710                                         type = type_expr.ResolveAsType (bc);
6711                                         if (type == null)
6712                                                 return false;
6713
6714                                         if (li == null)
6715                                                 CreateExceptionVariable (type);
6716
6717                                         if (type.BuiltinType != BuiltinTypeSpec.Type.Exception && !TypeSpec.IsBaseClass (type, bc.BuiltinTypes.Exception, false)) {
6718                                                 bc.Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
6719                                         } else if (li != null) {
6720                                                 li.Type = type;
6721                                                 li.PrepareAssignmentAnalysis (bc);
6722
6723                                                 // source variable is at the top of the stack
6724                                                 Expression source = new EmptyExpression (li.Type);
6725                                                 if (li.Type.IsGenericParameter)
6726                                                         source = new UnboxCast (source, li.Type);
6727
6728                                                 if (!block.HasAwait || Filter != null)
6729                                                         block.AddScopeStatement (new CatchVariableStore (this));
6730
6731                                                 //
6732                                                 // Uses Location.Null to hide from symbol file
6733                                                 //
6734                                                 assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
6735                                                 Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
6736                                         }
6737                                 }
6738
6739                                 if (Filter != null) {
6740                                         Block.AddScopeStatement (new FilterStatement (this));
6741                                 }
6742
6743                                 Block.SetCatchBlock ();
6744                                 return Block.Resolve (bc);
6745                         }
6746                 }
6747
6748                 bool CreateExceptionVariable (TypeSpec type)
6749                 {
6750                         if (!Block.HasAwait)
6751                                 return false;
6752
6753                         // TODO: Scan the block for rethrow expression
6754                         //if (!Block.HasRethrow)
6755                         //      return;
6756
6757                         li = LocalVariable.CreateCompilerGenerated (type, block, Location.Null);
6758                         return true;
6759                 }
6760
6761                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
6762                 {
6763                         if (li != null && !li.IsCompilerGenerated) {
6764                                 fc.SetVariableAssigned (li.VariableInfo, true);
6765                         }
6766
6767                         return block.FlowAnalysis (fc);
6768                 }
6769
6770                 public override Reachability MarkReachable (Reachability rc)
6771                 {
6772                         base.MarkReachable (rc);
6773
6774                         var c = Filter as Constant;
6775                         if (c != null && c.IsDefaultValue)
6776                                 return Reachability.CreateUnreachable ();
6777
6778                         return block.MarkReachable (rc);
6779                 }
6780
6781                 protected override void CloneTo (CloneContext clonectx, Statement t)
6782                 {
6783                         Catch target = (Catch) t;
6784
6785                         if (type_expr != null)
6786                                 target.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
6787
6788                         if (Filter != null)
6789                                 target.Filter = Filter.Clone (clonectx);
6790
6791                         target.block = (ExplicitBlock) clonectx.LookupBlock (block);
6792                 }
6793         }
6794
6795         public class TryFinally : TryFinallyBlock
6796         {
6797                 ExplicitBlock fini;
6798                 List<DefiniteAssignmentBitSet> try_exit_dat;
6799                 List<Label> redirected_jumps;
6800                 Label? start_fin_label;
6801
6802                 public TryFinally (Statement stmt, ExplicitBlock fini, Location loc)
6803                          : base (stmt, loc)
6804                 {
6805                         this.fini = fini;
6806                 }
6807
6808                 public ExplicitBlock FinallyBlock {
6809                         get {
6810                                 return fini;
6811                         }
6812                 }
6813
6814                 public void RegisterForControlExitCheck (DefiniteAssignmentBitSet vector)
6815                 {
6816                         if (try_exit_dat == null)
6817                                 try_exit_dat = new List<DefiniteAssignmentBitSet> ();
6818
6819                         try_exit_dat.Add (vector);
6820                 }
6821
6822                 public override bool Resolve (BlockContext bc)
6823                 {
6824                         bool ok = base.Resolve (bc);
6825
6826                         fini.SetFinallyBlock ();
6827                         using (bc.Set (ResolveContext.Options.FinallyScope)) {
6828                                 ok &= fini.Resolve (bc);
6829                         }
6830
6831                         return ok;
6832                 }
6833
6834                 protected override void EmitTryBody (EmitContext ec)
6835                 {
6836                         if (fini.HasAwait) {
6837                                 if (ec.TryFinallyUnwind == null)
6838                                         ec.TryFinallyUnwind = new List<TryFinally> ();
6839
6840                                 ec.TryFinallyUnwind.Add (this);
6841                                 stmt.Emit (ec);
6842                                 ec.TryFinallyUnwind.Remove (this);
6843
6844                                 if (start_fin_label != null)
6845                                         ec.MarkLabel (start_fin_label.Value);
6846
6847                                 return;
6848                         }
6849
6850                         stmt.Emit (ec);
6851                 }
6852
6853                 protected override bool EmitBeginFinallyBlock (EmitContext ec)
6854                 {
6855                         if (fini.HasAwait)
6856                                 return false;
6857
6858                         return base.EmitBeginFinallyBlock (ec);
6859                 }
6860
6861                 public override void EmitFinallyBody (EmitContext ec)
6862                 {
6863                         if (!fini.HasAwait) {
6864                                 fini.Emit (ec);
6865                                 return;
6866                         }
6867
6868                         //
6869                         // Emits catch block like
6870                         //
6871                         // catch (object temp) {
6872                         //      this.exception_field = temp;
6873                         // }
6874                         //
6875                         var type = ec.BuiltinTypes.Object;
6876                         ec.BeginCatchBlock (type);
6877
6878                         var temp = ec.GetTemporaryLocal (type);
6879                         ec.Emit (OpCodes.Stloc, temp);
6880
6881                         var exception_field = ec.GetTemporaryField (type);
6882                         ec.EmitThis ();
6883                         ec.Emit (OpCodes.Ldloc, temp);
6884                         exception_field.EmitAssignFromStack (ec);
6885
6886                         ec.EndExceptionBlock ();
6887
6888                         ec.FreeTemporaryLocal (temp, type);
6889
6890                         fini.Emit (ec);
6891
6892                         //
6893                         // Emits exception rethrow
6894                         //
6895                         // if (this.exception_field != null)
6896                         //      throw this.exception_field;
6897                         //
6898                         exception_field.Emit (ec);
6899                         var skip_throw = ec.DefineLabel ();
6900                         ec.Emit (OpCodes.Brfalse_S, skip_throw);
6901                         exception_field.Emit (ec);
6902                         ec.Emit (OpCodes.Throw);
6903                         ec.MarkLabel (skip_throw);
6904
6905                         exception_field.IsAvailableForReuse = true;
6906
6907                         EmitUnwindFinallyTable (ec);
6908                 }
6909
6910                 bool IsParentBlock (Block block)
6911                 {
6912                         for (Block b = fini; b != null; b = b.Parent) {
6913                                 if (b == block)
6914                                         return true;
6915                         }
6916
6917                         return false;
6918                 }
6919
6920                 public static Label EmitRedirectedJump (EmitContext ec, AsyncInitializer initializer, Label label, Block labelBlock)
6921                 {
6922                         int idx;
6923                         if (labelBlock != null) {
6924                                 for (idx = ec.TryFinallyUnwind.Count; idx != 0; --idx) {
6925                                         var fin = ec.TryFinallyUnwind [idx - 1];
6926                                         if (!fin.IsParentBlock (labelBlock))
6927                                                 break;
6928                                 }
6929                         } else {
6930                                 idx = 0;
6931                         }
6932
6933                         bool set_return_state = true;
6934
6935                         for (; idx < ec.TryFinallyUnwind.Count; ++idx) {
6936                                 var fin = ec.TryFinallyUnwind [idx];
6937                                 if (labelBlock != null && !fin.IsParentBlock (labelBlock))
6938                                         break;
6939
6940                                 fin.EmitRedirectedExit (ec, label, initializer, set_return_state);
6941                                 set_return_state = false;
6942
6943                                 if (fin.start_fin_label == null) {
6944                                         fin.start_fin_label = ec.DefineLabel ();
6945                                 }
6946
6947                                 label = fin.start_fin_label.Value;
6948                         }
6949
6950                         return label;
6951                 }
6952
6953                 public static Label EmitRedirectedReturn (EmitContext ec, AsyncInitializer initializer)
6954                 {
6955                         return EmitRedirectedJump (ec, initializer, initializer.BodyEnd, null);
6956                 }
6957
6958                 void EmitRedirectedExit (EmitContext ec, Label label, AsyncInitializer initializer, bool setReturnState)
6959                 {
6960                         if (redirected_jumps == null) {
6961                                 redirected_jumps = new List<Label> ();
6962
6963                                 // Add fallthrough label
6964                                 redirected_jumps.Add (ec.DefineLabel ());
6965
6966                                 if (setReturnState)
6967                                         initializer.HoistedReturnState = ec.GetTemporaryField (ec.Module.Compiler.BuiltinTypes.Int, true);
6968                         }
6969
6970                         int index = redirected_jumps.IndexOf (label);
6971                         if (index < 0) {
6972                                 redirected_jumps.Add (label);
6973                                 index = redirected_jumps.Count - 1;
6974                         }
6975
6976                         //
6977                         // Indicates we have captured exit jump
6978                         //
6979                         if (setReturnState) {
6980                                 var value = new IntConstant (initializer.HoistedReturnState.Type, index, Location.Null);
6981                                 initializer.HoistedReturnState.EmitAssign (ec, value, false, false);
6982                         }
6983                 }
6984
6985                 //
6986                 // Emits state table of jumps outside of try block and reload of return
6987                 // value when try block returns value
6988                 //
6989                 void EmitUnwindFinallyTable (EmitContext ec)
6990                 {
6991                         if (redirected_jumps == null)
6992                                 return;
6993
6994                         var initializer = (AsyncInitializer)ec.CurrentAnonymousMethod;
6995                         initializer.HoistedReturnState.EmitLoad (ec);
6996                         ec.Emit (OpCodes.Switch, redirected_jumps.ToArray ());
6997
6998                         // Mark fallthrough label
6999                         ec.MarkLabel (redirected_jumps [0]);
7000                 }
7001
7002                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7003                 {
7004                         var da = fc.BranchDefiniteAssignment ();
7005
7006                         var tf = fc.TryFinally;
7007                         fc.TryFinally = this;
7008
7009                         var res_stmt = Statement.FlowAnalysis (fc);
7010
7011                         fc.TryFinally = tf;
7012
7013                         var try_da = fc.DefiniteAssignment;
7014                         fc.DefiniteAssignment = da;
7015
7016                         var res_fin = fini.FlowAnalysis (fc);
7017
7018                         if (try_exit_dat != null) {
7019                                 //
7020                                 // try block has global exit but we need to run definite assignment check
7021                                 // for parameter block out parameter after finally block because it's always
7022                                 // executed before exit
7023                                 //
7024                                 foreach (var try_da_part in try_exit_dat)
7025                                         fc.ParametersBlock.CheckControlExit (fc, fc.DefiniteAssignment | try_da_part);
7026
7027                                 try_exit_dat = null;
7028                         }
7029
7030                         fc.DefiniteAssignment |= try_da;
7031                         return res_stmt | res_fin;
7032                 }
7033
7034                 public override Reachability MarkReachable (Reachability rc)
7035                 {
7036                         //
7037                         // Mark finally block first for any exit statement in try block
7038                         // to know whether the code which follows finally is reachable
7039                         //
7040                         return fini.MarkReachable (rc) | base.MarkReachable (rc);
7041                 }
7042
7043                 protected override void CloneTo (CloneContext clonectx, Statement t)
7044                 {
7045                         TryFinally target = (TryFinally) t;
7046
7047                         target.stmt = stmt.Clone (clonectx);
7048                         if (fini != null)
7049                                 target.fini = (ExplicitBlock) clonectx.LookupBlock (fini);
7050                 }
7051                 
7052                 public override object Accept (StructuralVisitor visitor)
7053                 {
7054                         return visitor.Visit (this);
7055                 }
7056         }
7057
7058         public class TryCatch : ExceptionStatement
7059         {
7060                 public Block Block;
7061                 List<Catch> clauses;
7062                 readonly bool inside_try_finally;
7063                 List<Catch> catch_sm;
7064
7065                 public TryCatch (Block block, List<Catch> catch_clauses, Location l, bool inside_try_finally)
7066                         : base (l)
7067                 {
7068                         this.Block = block;
7069                         this.clauses = catch_clauses;
7070                         this.inside_try_finally = inside_try_finally;
7071                 }
7072
7073                 public List<Catch> Clauses {
7074                         get {
7075                                 return clauses;
7076                         }
7077                 }
7078
7079                 public bool IsTryCatchFinally {
7080                         get {
7081                                 return inside_try_finally;
7082                         }
7083                 }
7084
7085                 public override bool Resolve (BlockContext bc)
7086                 {
7087                         bool ok;
7088
7089                         using (bc.Set (ResolveContext.Options.TryScope)) {
7090                                 parent = bc.CurrentTryBlock;
7091
7092                                 if (IsTryCatchFinally) {
7093                                         ok = Block.Resolve (bc);
7094                                 } else {
7095                                         using (bc.Set (ResolveContext.Options.TryWithCatchScope)) {
7096                                                 bc.CurrentTryBlock = this;
7097                                                 ok = Block.Resolve (bc);
7098                                                 bc.CurrentTryBlock = parent;
7099                                         }
7100                                 }
7101                         }
7102
7103                         for (int i = 0; i < clauses.Count; ++i) {
7104                                 var c = clauses[i];
7105
7106                                 ok &= c.Resolve (bc);
7107
7108                                 if (c.Block.HasAwait) {
7109                                         if (catch_sm == null)
7110                                                 catch_sm = new List<Catch> ();
7111
7112                                         catch_sm.Add (c);
7113                                 }
7114
7115                                 if (c.Filter != null)
7116                                         continue;
7117
7118                                 TypeSpec resolved_type = c.CatchType;
7119                                 if (resolved_type == null)
7120                                         continue;
7121
7122                                 for (int ii = 0; ii < clauses.Count; ++ii) {
7123                                         if (ii == i)
7124                                                 continue;
7125
7126                                         if (clauses[ii].Filter != null)
7127                                                 continue;
7128
7129                                         if (clauses[ii].IsGeneral) {
7130                                                 if (resolved_type.BuiltinType != BuiltinTypeSpec.Type.Exception)
7131                                                         continue;
7132
7133                                                 if (!bc.Module.DeclaringAssembly.WrapNonExceptionThrows)
7134                                                         continue;
7135
7136                                                 if (!bc.Module.PredefinedAttributes.RuntimeCompatibility.IsDefined)
7137                                                         continue;
7138
7139                                                 bc.Report.Warning (1058, 1, c.loc,
7140                                                         "A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
7141
7142                                                 continue;
7143                                         }
7144
7145                                         if (ii >= i)
7146                                                 continue;
7147
7148                                         var ct = clauses[ii].CatchType;
7149                                         if (ct == null)
7150                                                 continue;
7151
7152                                         if (resolved_type == ct || TypeSpec.IsBaseClass (resolved_type, ct, true)) {
7153                                                 bc.Report.Error (160, c.loc,
7154                                                         "A previous catch clause already catches all exceptions of this or a super type `{0}'",
7155                                                         ct.GetSignatureForError ());
7156                                                 ok = false;
7157                                         }
7158                                 }
7159                         }
7160
7161                         return base.Resolve (bc) && ok;
7162                 }
7163
7164                 protected sealed override void DoEmit (EmitContext ec)
7165                 {
7166                         if (!inside_try_finally)
7167                                 EmitTryBodyPrepare (ec);
7168
7169                         Block.Emit (ec);
7170
7171                         LocalBuilder state_variable = null;
7172                         foreach (Catch c in clauses) {
7173                                 c.Emit (ec);
7174
7175                                 if (catch_sm != null) {
7176                                         if (state_variable == null) {
7177                                                 //
7178                                                 // Cannot reuse temp variable because non-catch path assumes the value is 0
7179                                                 // which may not be true for reused local variable
7180                                                 //
7181                                                 state_variable = ec.DeclareLocal (ec.Module.Compiler.BuiltinTypes.Int, false);
7182                                         }
7183
7184                                         var index = catch_sm.IndexOf (c);
7185                                         if (index < 0)
7186                                                 continue;
7187
7188                                         ec.EmitInt (index + 1);
7189                                         ec.Emit (OpCodes.Stloc, state_variable);
7190                                 }
7191                         }
7192
7193                         if (!inside_try_finally)
7194                                 ec.EndExceptionBlock ();
7195
7196                         if (state_variable != null) {
7197                                 ec.Emit (OpCodes.Ldloc, state_variable);
7198
7199                                 var labels = new Label [catch_sm.Count + 1];
7200                                 for (int i = 0; i < labels.Length; ++i) {
7201                                         labels [i] = ec.DefineLabel ();
7202                                 }
7203
7204                                 var end = ec.DefineLabel ();
7205                                 ec.Emit (OpCodes.Switch, labels);
7206
7207                                 // 0 value is default label
7208                                 ec.MarkLabel (labels [0]);
7209                                 ec.Emit (OpCodes.Br, end);
7210
7211                                 var atv = ec.AsyncThrowVariable;
7212                                 Catch c = null;
7213                                 for (int i = 0; i < catch_sm.Count; ++i) {
7214                                         if (c != null && c.Block.HasReachableClosingBrace)
7215                                                 ec.Emit (OpCodes.Br, end);
7216
7217                                         ec.MarkLabel (labels [i + 1]);
7218                                         c = catch_sm [i];
7219                                         ec.AsyncThrowVariable = c.Variable;
7220                                         c.Block.Emit (ec);
7221                                 }
7222                                 ec.AsyncThrowVariable = atv;
7223
7224                                 ec.MarkLabel (end);
7225                         }
7226                 }
7227
7228                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7229                 {
7230                         var start_fc = fc.BranchDefiniteAssignment ();
7231                         var res = Block.FlowAnalysis (fc);
7232
7233                         DefiniteAssignmentBitSet try_fc = res ? null : fc.DefiniteAssignment;
7234
7235                         foreach (var c in clauses) {
7236                                 fc.BranchDefiniteAssignment (start_fc);
7237                                 if (!c.FlowAnalysis (fc)) {
7238                                         if (try_fc == null)
7239                                                 try_fc = fc.DefiniteAssignment;
7240                                         else
7241                                                 try_fc &= fc.DefiniteAssignment;
7242
7243                                         res = false;
7244                                 }
7245                         }
7246
7247                         fc.DefiniteAssignment = try_fc ?? start_fc;
7248                         parent = null;
7249                         return res;
7250                 }
7251
7252                 public override Reachability MarkReachable (Reachability rc)
7253                 {
7254                         if (rc.IsUnreachable)
7255                                 return rc;
7256
7257                         base.MarkReachable (rc);
7258
7259                         var tc_rc = Block.MarkReachable (rc);
7260
7261                         foreach (var c in clauses)
7262                                 tc_rc &= c.MarkReachable (rc);
7263
7264                         return tc_rc;
7265                 }
7266
7267                 protected override void CloneTo (CloneContext clonectx, Statement t)
7268                 {
7269                         TryCatch target = (TryCatch) t;
7270
7271                         target.Block = clonectx.LookupBlock (Block);
7272                         if (clauses != null){
7273                                 target.clauses = new List<Catch> ();
7274                                 foreach (Catch c in clauses)
7275                                         target.clauses.Add ((Catch) c.Clone (clonectx));
7276                         }
7277                 }
7278
7279                 public override object Accept (StructuralVisitor visitor)
7280                 {
7281                         return visitor.Visit (this);
7282                 }
7283         }
7284
7285         public class Using : TryFinallyBlock
7286         {
7287                 public class VariableDeclaration : BlockVariable
7288                 {
7289                         Statement dispose_call;
7290
7291                         public VariableDeclaration (FullNamedExpression type, LocalVariable li)
7292                                 : base (type, li)
7293                         {
7294                         }
7295
7296                         public VariableDeclaration (LocalVariable li, Location loc)
7297                                 : base (li)
7298                         {
7299                                 reachable = true;
7300                                 this.loc = loc;
7301                         }
7302
7303                         public VariableDeclaration (Expression expr)
7304                                 : base (null)
7305                         {
7306                                 loc = expr.Location;
7307                                 Initializer = expr;
7308                         }
7309
7310                         #region Properties
7311
7312                         public bool IsNested { get; private set; }
7313
7314                         #endregion
7315
7316                         public void EmitDispose (EmitContext ec)
7317                         {
7318                                 dispose_call.Emit (ec);
7319                         }
7320
7321                         public override bool Resolve (BlockContext bc)
7322                         {
7323                                 if (IsNested)
7324                                         return true;
7325
7326                                 return base.Resolve (bc, false);
7327                         }
7328
7329                         public Expression ResolveExpression (BlockContext bc)
7330                         {
7331                                 var e = Initializer.Resolve (bc);
7332                                 if (e == null)
7333                                         return null;
7334
7335                                 li = LocalVariable.CreateCompilerGenerated (e.Type, bc.CurrentBlock, loc);
7336                                 Initializer = ResolveInitializer (bc, Variable, e);
7337                                 return e;
7338                         }
7339
7340                         protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
7341                         {
7342                                 if (li.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
7343                                         initializer = initializer.Resolve (bc);
7344                                         if (initializer == null)
7345                                                 return null;
7346
7347                                         // Once there is dynamic used defer conversion to runtime even if we know it will never succeed
7348                                         Arguments args = new Arguments (1);
7349                                         args.Add (new Argument (initializer));
7350                                         initializer = new DynamicConversion (bc.BuiltinTypes.IDisposable, 0, args, initializer.Location).Resolve (bc);
7351                                         if (initializer == null)
7352                                                 return null;
7353
7354                                         var var = LocalVariable.CreateCompilerGenerated (initializer.Type, bc.CurrentBlock, loc);
7355                                         dispose_call = CreateDisposeCall (bc, var);
7356                                         dispose_call.Resolve (bc);
7357
7358                                         return base.ResolveInitializer (bc, li, new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc));
7359                                 }
7360
7361                                 if (li == Variable) {
7362                                         CheckIDiposableConversion (bc, li, initializer);
7363                                         dispose_call = CreateDisposeCall (bc, li);
7364                                         dispose_call.Resolve (bc);
7365                                 }
7366
7367                                 return base.ResolveInitializer (bc, li, initializer);
7368                         }
7369
7370                         protected virtual void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
7371                         {
7372                                 var type = li.Type;
7373
7374                                 if (type.BuiltinType != BuiltinTypeSpec.Type.IDisposable && !CanConvertToIDisposable (bc, type)) {
7375                                         if (type.IsNullableType) {
7376                                                 // it's handled in CreateDisposeCall
7377                                                 return;
7378                                         }
7379
7380                                         if (type != InternalType.ErrorType) {
7381                                                 bc.Report.SymbolRelatedToPreviousError (type);
7382                                                 var loc = type_expr == null ? initializer.Location : type_expr.Location;
7383                                                 bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
7384                                                         type.GetSignatureForError ());
7385                                         }
7386
7387                                         return;
7388                                 }
7389                         }
7390
7391                         static bool CanConvertToIDisposable (BlockContext bc, TypeSpec type)
7392                         {
7393                                 var target = bc.BuiltinTypes.IDisposable;
7394                                 var tp = type as TypeParameterSpec;
7395                                 if (tp != null)
7396                                         return Convert.ImplicitTypeParameterConversion (null, tp, target) != null;
7397
7398                                 return type.ImplementsInterface (target, false);
7399                         }
7400
7401                         protected virtual Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
7402                         {
7403                                 var lvr = lv.CreateReferenceExpression (bc, lv.Location);
7404                                 var type = lv.Type;
7405                                 var loc = lv.Location;
7406
7407                                 var idt = bc.BuiltinTypes.IDisposable;
7408                                 var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
7409
7410                                 var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
7411                                 dispose_mg.InstanceExpression = type.IsNullableType ?
7412                                         new Cast (new TypeExpression (idt, loc), lvr, loc).Resolve (bc) :
7413                                         lvr;
7414
7415                                 //
7416                                 // Hide it from symbol file via null location
7417                                 //
7418                                 Statement dispose = new StatementExpression (new Invocation (dispose_mg, null), Location.Null);
7419
7420                                 // Add conditional call when disposing possible null variable
7421                                 if (!TypeSpec.IsValueType (type) || type.IsNullableType)
7422                                         dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc)), dispose, dispose.loc);
7423
7424                                 return dispose;
7425                         }
7426
7427                         public void ResolveDeclaratorInitializer (BlockContext bc)
7428                         {
7429                                 Initializer = base.ResolveInitializer (bc, Variable, Initializer);
7430                         }
7431
7432                         public Statement RewriteUsingDeclarators (BlockContext bc, Statement stmt)
7433                         {
7434                                 for (int i = declarators.Count - 1; i >= 0; --i) {
7435                                         var d = declarators [i];
7436                                         var vd = new VariableDeclaration (d.Variable, d.Variable.Location);
7437                                         vd.Initializer = d.Initializer;
7438                                         vd.IsNested = true;
7439                                         vd.dispose_call = CreateDisposeCall (bc, d.Variable);
7440                                         vd.dispose_call.Resolve (bc);
7441
7442                                         stmt = new Using (vd, stmt, d.Variable.Location);
7443                                 }
7444
7445                                 declarators = null;
7446                                 return stmt;
7447                         }       
7448
7449                         public override object Accept (StructuralVisitor visitor)
7450                         {
7451                                 return visitor.Visit (this);
7452                         }       
7453                 }
7454
7455                 VariableDeclaration decl;
7456
7457                 public Using (VariableDeclaration decl, Statement stmt, Location loc)
7458                         : base (stmt, loc)
7459                 {
7460                         this.decl = decl;
7461                 }
7462
7463                 public Using (Expression expr, Statement stmt, Location loc)
7464                         : base (stmt, loc)
7465                 {
7466                         this.decl = new VariableDeclaration (expr);
7467                 }
7468
7469                 #region Properties
7470
7471                 public Expression Expr {
7472                         get {
7473                                 return decl.Variable == null ? decl.Initializer : null;
7474                         }
7475                 }
7476
7477                 public BlockVariable Variables {
7478                         get {
7479                                 return decl;
7480                         }
7481                 }
7482
7483                 #endregion
7484
7485                 public override void Emit (EmitContext ec)
7486                 {
7487                         //
7488                         // Don't emit sequence point it will be set on variable declaration
7489                         //
7490                         DoEmit (ec);
7491                 }
7492
7493                 protected override void EmitTryBodyPrepare (EmitContext ec)
7494                 {
7495                         decl.Emit (ec);
7496                         base.EmitTryBodyPrepare (ec);
7497                 }
7498
7499                 protected override void EmitTryBody (EmitContext ec)
7500                 {
7501                         stmt.Emit (ec);
7502                 }
7503
7504                 public override void EmitFinallyBody (EmitContext ec)
7505                 {
7506                         decl.EmitDispose (ec);
7507                 }
7508
7509                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7510                 {
7511                         decl.FlowAnalysis (fc);
7512                         return stmt.FlowAnalysis (fc);
7513                 }
7514
7515                 public override Reachability MarkReachable (Reachability rc)
7516                 {
7517                         decl.MarkReachable (rc);
7518                         return base.MarkReachable (rc);
7519                 }
7520
7521                 public override bool Resolve (BlockContext ec)
7522                 {
7523                         VariableReference vr;
7524                         bool vr_locked = false;
7525
7526                         using (ec.Set (ResolveContext.Options.UsingInitializerScope)) {
7527                                 if (decl.Variable == null) {
7528                                         vr = decl.ResolveExpression (ec) as VariableReference;
7529                                         if (vr != null) {
7530                                                 vr_locked = vr.IsLockedByStatement;
7531                                                 vr.IsLockedByStatement = true;
7532                                         }
7533                                 } else {
7534                                         if (decl.IsNested) {
7535                                                 decl.ResolveDeclaratorInitializer (ec);
7536                                         } else {
7537                                                 if (!decl.Resolve (ec))
7538                                                         return false;
7539
7540                                                 if (decl.Declarators != null) {
7541                                                         stmt = decl.RewriteUsingDeclarators (ec, stmt);
7542                                                 }
7543                                         }
7544
7545                                         vr = null;
7546                                 }
7547                         }
7548
7549                         var ok = base.Resolve (ec);
7550
7551                         if (vr != null)
7552                                 vr.IsLockedByStatement = vr_locked;
7553
7554                         return ok;
7555                 }
7556
7557                 protected override void CloneTo (CloneContext clonectx, Statement t)
7558                 {
7559                         Using target = (Using) t;
7560
7561                         target.decl = (VariableDeclaration) decl.Clone (clonectx);
7562                         target.stmt = stmt.Clone (clonectx);
7563                 }
7564
7565                 public override object Accept (StructuralVisitor visitor)
7566                 {
7567                         return visitor.Visit (this);
7568                 }
7569         }
7570
7571         /// <summary>
7572         ///   Implementation of the foreach C# statement
7573         /// </summary>
7574         public class Foreach : LoopStatement
7575         {
7576                 abstract class IteratorStatement : Statement
7577                 {
7578                         protected readonly Foreach for_each;
7579
7580                         protected IteratorStatement (Foreach @foreach)
7581                         {
7582                                 this.for_each = @foreach;
7583                                 this.loc = @foreach.expr.Location;
7584                         }
7585
7586                         protected override void CloneTo (CloneContext clonectx, Statement target)
7587                         {
7588                                 throw new NotImplementedException ();
7589                         }
7590
7591                         public override void Emit (EmitContext ec)
7592                         {
7593                                 if (ec.EmitAccurateDebugInfo) {
7594                                         ec.Emit (OpCodes.Nop);
7595                                 }
7596
7597                                 base.Emit (ec);
7598                         }
7599
7600                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
7601                         {
7602                                 throw new NotImplementedException ();
7603                         }
7604                 }
7605
7606                 sealed class ArrayForeach : IteratorStatement
7607                 {
7608                         TemporaryVariableReference[] lengths;
7609                         Expression [] length_exprs;
7610                         StatementExpression[] counter;
7611                         TemporaryVariableReference[] variables;
7612
7613                         TemporaryVariableReference copy;
7614
7615                         public ArrayForeach (Foreach @foreach, int rank)
7616                                 : base (@foreach)
7617                         {
7618                                 counter = new StatementExpression[rank];
7619                                 variables = new TemporaryVariableReference[rank];
7620                                 length_exprs = new Expression [rank];
7621
7622                                 //
7623                                 // Only use temporary length variables when dealing with
7624                                 // multi-dimensional arrays
7625                                 //
7626                                 if (rank > 1)
7627                                         lengths = new TemporaryVariableReference [rank];
7628                         }
7629
7630                         public override bool Resolve (BlockContext ec)
7631                         {
7632                                 Block variables_block = for_each.variable.Block;
7633                                 copy = TemporaryVariableReference.Create (for_each.expr.Type, variables_block, loc);
7634                                 copy.Resolve (ec);
7635
7636                                 int rank = length_exprs.Length;
7637                                 Arguments list = new Arguments (rank);
7638                                 for (int i = 0; i < rank; i++) {
7639                                         var v = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
7640                                         variables[i] = v;
7641                                         counter[i] = new StatementExpression (new UnaryMutator (UnaryMutator.Mode.PostIncrement, v, Location.Null));
7642                                         counter[i].Resolve (ec);
7643
7644                                         if (rank == 1) {
7645                                                 length_exprs [i] = new MemberAccess (copy, "Length").Resolve (ec);
7646                                         } else {
7647                                                 lengths[i] = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
7648                                                 lengths[i].Resolve (ec);
7649
7650                                                 Arguments args = new Arguments (1);
7651                                                 args.Add (new Argument (new IntConstant (ec.BuiltinTypes, i, loc)));
7652                                                 length_exprs [i] = new Invocation (new MemberAccess (copy, "GetLength"), args).Resolve (ec);
7653                                         }
7654
7655                                         list.Add (new Argument (v));
7656                                 }
7657
7658                                 var access = new ElementAccess (copy, list, loc).Resolve (ec);
7659                                 if (access == null)
7660                                         return false;
7661
7662                                 TypeSpec var_type;
7663                                 if (for_each.type is VarExpr) {
7664                                         // Infer implicitly typed local variable from foreach array type
7665                                         var_type = access.Type;
7666                                 } else {
7667                                         var_type = for_each.type.ResolveAsType (ec);
7668
7669                                         if (var_type == null)
7670                                                 return false;
7671
7672                                         access = Convert.ExplicitConversion (ec, access, var_type, loc);
7673                                         if (access == null)
7674                                                 return false;
7675                                 }
7676
7677                                 for_each.variable.Type = var_type;
7678
7679                                 var variable_ref = new LocalVariableReference (for_each.variable, loc).Resolve (ec);
7680                                 if (variable_ref == null)
7681                                         return false;
7682
7683                                 for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.type.Location));
7684
7685                                 return for_each.body.Resolve (ec);
7686                         }
7687
7688                         protected override void DoEmit (EmitContext ec)
7689                         {
7690                                 copy.EmitAssign (ec, for_each.expr);
7691
7692                                 int rank = length_exprs.Length;
7693                                 Label[] test = new Label [rank];
7694                                 Label[] loop = new Label [rank];
7695
7696                                 for (int i = 0; i < rank; i++) {
7697                                         test [i] = ec.DefineLabel ();
7698                                         loop [i] = ec.DefineLabel ();
7699
7700                                         if (lengths != null)
7701                                                 lengths [i].EmitAssign (ec, length_exprs [i]);
7702                                 }
7703
7704                                 IntConstant zero = new IntConstant (ec.BuiltinTypes, 0, loc);
7705                                 for (int i = 0; i < rank; i++) {
7706                                         variables [i].EmitAssign (ec, zero);
7707
7708                                         ec.Emit (OpCodes.Br, test [i]);
7709                                         ec.MarkLabel (loop [i]);
7710                                 }
7711
7712                                 for_each.body.Emit (ec);
7713
7714                                 ec.MarkLabel (ec.LoopBegin);
7715                                 ec.Mark (for_each.expr.Location);
7716
7717                                 for (int i = rank - 1; i >= 0; i--){
7718                                         counter [i].Emit (ec);
7719
7720                                         ec.MarkLabel (test [i]);
7721                                         variables [i].Emit (ec);
7722
7723                                         if (lengths != null)
7724                                                 lengths [i].Emit (ec);
7725                                         else
7726                                                 length_exprs [i].Emit (ec);
7727
7728                                         ec.Emit (OpCodes.Blt, loop [i]);
7729                                 }
7730
7731                                 ec.MarkLabel (ec.LoopEnd);
7732                         }
7733                 }
7734
7735                 sealed class CollectionForeach : IteratorStatement, OverloadResolver.IErrorHandler
7736                 {
7737                         class RuntimeDispose : Using.VariableDeclaration
7738                         {
7739                                 public RuntimeDispose (LocalVariable lv, Location loc)
7740                                         : base (lv, loc)
7741                                 {
7742                                         reachable = true;
7743                                 }
7744
7745                                 protected override void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
7746                                 {
7747                                         // Defered to runtime check
7748                                 }
7749
7750                                 protected override Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
7751                                 {
7752                                         var idt = bc.BuiltinTypes.IDisposable;
7753
7754                                         //
7755                                         // Fabricates code like
7756                                         //
7757                                         // if ((temp = vr as IDisposable) != null) temp.Dispose ();
7758                                         //
7759
7760                                         var dispose_variable = LocalVariable.CreateCompilerGenerated (idt, bc.CurrentBlock, loc);
7761
7762                                         var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign (
7763                                                 dispose_variable.CreateReferenceExpression (bc, loc),
7764                                                 new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc),
7765                                                 loc), new NullLiteral (loc));
7766
7767                                         var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
7768
7769                                         var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
7770                                         dispose_mg.InstanceExpression = dispose_variable.CreateReferenceExpression (bc, loc);
7771
7772                                         Statement dispose = new StatementExpression (new Invocation (dispose_mg, null));
7773                                         return new If (idisaposable_test, dispose, loc);
7774                                 }
7775                         }
7776
7777                         LocalVariable variable;
7778                         Expression expr;
7779                         Statement statement;
7780                         ExpressionStatement init;
7781                         TemporaryVariableReference enumerator_variable;
7782                         bool ambiguous_getenumerator_name;
7783
7784                         public CollectionForeach (Foreach @foreach, LocalVariable var, Expression expr)
7785                                 : base (@foreach)
7786                         {
7787                                 this.variable = var;
7788                                 this.expr = expr;
7789                         }
7790
7791                         void Error_WrongEnumerator (ResolveContext rc, MethodSpec enumerator)
7792                         {
7793                                 rc.Report.SymbolRelatedToPreviousError (enumerator);
7794                                 rc.Report.Error (202, loc,
7795                                         "foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
7796                                                 enumerator.ReturnType.GetSignatureForError (), enumerator.GetSignatureForError ());
7797                         }
7798
7799                         MethodGroupExpr ResolveGetEnumerator (ResolveContext rc)
7800                         {
7801                                 //
7802                                 // Option 1: Try to match by name GetEnumerator first
7803                                 //
7804                                 var mexpr = Expression.MemberLookup (rc, false, expr.Type,
7805                                         "GetEnumerator", 0, Expression.MemberLookupRestrictions.ExactArity, loc);               // TODO: What if CS0229 ?
7806
7807                                 var mg = mexpr as MethodGroupExpr;
7808                                 if (mg != null) {
7809                                         mg.InstanceExpression = expr;
7810                                         Arguments args = new Arguments (0);
7811                                         mg = mg.OverloadResolve (rc, ref args, this, OverloadResolver.Restrictions.ProbingOnly | OverloadResolver.Restrictions.GetEnumeratorLookup);
7812
7813                                         // For ambiguous GetEnumerator name warning CS0278 was reported, but Option 2 could still apply
7814                                         if (ambiguous_getenumerator_name)
7815                                                 mg = null;
7816
7817                                         if (mg != null && !mg.BestCandidate.IsStatic && mg.BestCandidate.IsPublic) {
7818                                                 return mg;
7819                                         }
7820                                 }
7821
7822                                 //
7823                                 // Option 2: Try to match using IEnumerable interfaces with preference of generic version
7824                                 //
7825                                 var t = expr.Type;
7826                                 PredefinedMember<MethodSpec> iface_candidate = null;
7827                                 var ptypes = rc.Module.PredefinedTypes;
7828                                 var gen_ienumerable = ptypes.IEnumerableGeneric;
7829                                 if (!gen_ienumerable.Define ())
7830                                         gen_ienumerable = null;
7831
7832                                 var ifaces = t.Interfaces;
7833                                 if (ifaces != null) {
7834                                         foreach (var iface in ifaces) {
7835                                                 if (gen_ienumerable != null && iface.MemberDefinition == gen_ienumerable.TypeSpec.MemberDefinition) {
7836                                                         if (iface_candidate != null && iface_candidate != rc.Module.PredefinedMembers.IEnumerableGetEnumerator) {
7837                                                                 rc.Report.SymbolRelatedToPreviousError (expr.Type);
7838                                                                 rc.Report.Error (1640, loc,
7839                                                                         "foreach statement cannot operate on variables of type `{0}' because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
7840                                                                         expr.Type.GetSignatureForError (), gen_ienumerable.TypeSpec.GetSignatureForError ());
7841
7842                                                                 return null;
7843                                                         }
7844
7845                                                         // TODO: Cache this somehow
7846                                                         iface_candidate = new PredefinedMember<MethodSpec> (rc.Module, iface,
7847                                                                 MemberFilter.Method ("GetEnumerator", 0, ParametersCompiled.EmptyReadOnlyParameters, null));
7848
7849                                                         continue;
7850                                                 }
7851
7852                                                 if (iface.BuiltinType == BuiltinTypeSpec.Type.IEnumerable && iface_candidate == null) {
7853                                                         iface_candidate = rc.Module.PredefinedMembers.IEnumerableGetEnumerator;
7854                                                 }
7855                                         }
7856                                 }
7857
7858                                 if (iface_candidate == null) {
7859                                         if (expr.Type != InternalType.ErrorType) {
7860                                                 rc.Report.Error (1579, loc,
7861                                                         "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
7862                                                         expr.Type.GetSignatureForError (), "GetEnumerator");
7863                                         }
7864
7865                                         return null;
7866                                 }
7867
7868                                 var method = iface_candidate.Resolve (loc);
7869                                 if (method == null)
7870                                         return null;
7871
7872                                 mg = MethodGroupExpr.CreatePredefined (method, expr.Type, loc);
7873                                 mg.InstanceExpression = expr;
7874                                 return mg;
7875                         }
7876
7877                         MethodGroupExpr ResolveMoveNext (ResolveContext rc, MethodSpec enumerator)
7878                         {
7879                                 var ms = MemberCache.FindMember (enumerator.ReturnType,
7880                                         MemberFilter.Method ("MoveNext", 0, ParametersCompiled.EmptyReadOnlyParameters, rc.BuiltinTypes.Bool),
7881                                         BindingRestriction.InstanceOnly) as MethodSpec;
7882
7883                                 if (ms == null || !ms.IsPublic) {
7884                                         Error_WrongEnumerator (rc, enumerator);
7885                                         return null;
7886                                 }
7887
7888                                 return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, expr.Location);
7889                         }
7890
7891                         PropertySpec ResolveCurrent (ResolveContext rc, MethodSpec enumerator)
7892                         {
7893                                 var ps = MemberCache.FindMember (enumerator.ReturnType,
7894                                         MemberFilter.Property ("Current", null),
7895                                         BindingRestriction.InstanceOnly) as PropertySpec;
7896
7897                                 if (ps == null || !ps.IsPublic) {
7898                                         Error_WrongEnumerator (rc, enumerator);
7899                                         return null;
7900                                 }
7901
7902                                 return ps;
7903                         }
7904
7905                         public override bool Resolve (BlockContext ec)
7906                         {
7907                                 bool is_dynamic = expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
7908
7909                                 if (is_dynamic) {
7910                                         expr = Convert.ImplicitConversionRequired (ec, expr, ec.BuiltinTypes.IEnumerable, loc);
7911                                 } else if (expr.Type.IsNullableType) {
7912                                         expr = new Nullable.UnwrapCall (expr).Resolve (ec);
7913                                 }
7914
7915                                 var get_enumerator_mg = ResolveGetEnumerator (ec);
7916                                 if (get_enumerator_mg == null) {
7917                                         return false;
7918                                 }
7919
7920                                 var get_enumerator = get_enumerator_mg.BestCandidate;
7921                                 enumerator_variable = TemporaryVariableReference.Create (get_enumerator.ReturnType, variable.Block, loc);
7922                                 enumerator_variable.Resolve (ec);
7923
7924                                 // Prepare bool MoveNext ()
7925                                 var move_next_mg = ResolveMoveNext (ec, get_enumerator);
7926                                 if (move_next_mg == null) {
7927                                         return false;
7928                                 }
7929
7930                                 move_next_mg.InstanceExpression = enumerator_variable;
7931
7932                                 // Prepare ~T~ Current { get; }
7933                                 var current_prop = ResolveCurrent (ec, get_enumerator);
7934                                 if (current_prop == null) {
7935                                         return false;
7936                                 }
7937
7938                                 var current_pe = new PropertyExpr (current_prop, loc) { InstanceExpression = enumerator_variable }.Resolve (ec);
7939                                 if (current_pe == null)
7940                                         return false;
7941
7942                                 VarExpr ve = for_each.type as VarExpr;
7943
7944                                 if (ve != null) {
7945                                         if (is_dynamic) {
7946                                                 // Source type is dynamic, set element type to dynamic too
7947                                                 variable.Type = ec.BuiltinTypes.Dynamic;
7948                                         } else {
7949                                                 // Infer implicitly typed local variable from foreach enumerable type
7950                                                 variable.Type = current_pe.Type;
7951                                         }
7952                                 } else {
7953                                         if (is_dynamic) {
7954                                                 // Explicit cast of dynamic collection elements has to be done at runtime
7955                                                 current_pe = EmptyCast.Create (current_pe, ec.BuiltinTypes.Dynamic);
7956                                         }
7957
7958                                         variable.Type = for_each.type.ResolveAsType (ec);
7959
7960                                         if (variable.Type == null)
7961                                                 return false;
7962
7963                                         current_pe = Convert.ExplicitConversion (ec, current_pe, variable.Type, loc);
7964                                         if (current_pe == null)
7965                                                 return false;
7966                                 }
7967
7968                                 var variable_ref = new LocalVariableReference (variable, loc).Resolve (ec);
7969                                 if (variable_ref == null)
7970                                         return false;
7971
7972                                 for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), for_each.type.Location));
7973
7974                                 var init = new Invocation.Predefined (get_enumerator_mg, null);
7975
7976                                 statement = new While (new BooleanExpression (new Invocation (move_next_mg, null)),
7977                                          for_each.body, Location.Null);
7978
7979                                 var enum_type = enumerator_variable.Type;
7980
7981                                 //
7982                                 // Add Dispose method call when enumerator can be IDisposable
7983                                 //
7984                                 if (!enum_type.ImplementsInterface (ec.BuiltinTypes.IDisposable, false)) {
7985                                         if (!enum_type.IsSealed && !TypeSpec.IsValueType (enum_type)) {
7986                                                 //
7987                                                 // Runtime Dispose check
7988                                                 //
7989                                                 var vd = new RuntimeDispose (enumerator_variable.LocalInfo, Location.Null);
7990                                                 vd.Initializer = init;
7991                                                 statement = new Using (vd, statement, Location.Null);
7992                                         } else {
7993                                                 //
7994                                                 // No Dispose call needed
7995                                                 //
7996                                                 this.init = new SimpleAssign (enumerator_variable, init, Location.Null);
7997                                                 this.init.Resolve (ec);
7998                                         }
7999                                 } else {
8000                                         //
8001                                         // Static Dispose check
8002                                         //
8003                                         var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, Location.Null);
8004                                         vd.Initializer = init;
8005                                         statement = new Using (vd, statement, Location.Null);
8006                                 }
8007
8008                                 return statement.Resolve (ec);
8009                         }
8010
8011                         protected override void DoEmit (EmitContext ec)
8012                         {
8013                                 enumerator_variable.LocalInfo.CreateBuilder (ec);
8014
8015                                 if (init != null)
8016                                         init.EmitStatement (ec);
8017
8018                                 statement.Emit (ec);
8019                         }
8020
8021                         #region IErrorHandler Members
8022
8023                         bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
8024                         {
8025                                 ec.Report.SymbolRelatedToPreviousError (best);
8026                                 ec.Report.Warning (278, 2, expr.Location,
8027                                         "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
8028                                         expr.Type.GetSignatureForError (), "enumerable",
8029                                         best.GetSignatureForError (), ambiguous.GetSignatureForError ());
8030
8031                                 ambiguous_getenumerator_name = true;
8032                                 return true;
8033                         }
8034
8035                         bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
8036                         {
8037                                 return false;
8038                         }
8039
8040                         bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
8041                         {
8042                                 return false;
8043                         }
8044
8045                         bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
8046                         {
8047                                 return false;
8048                         }
8049
8050                         #endregion
8051                 }
8052
8053                 Expression type;
8054                 LocalVariable variable;
8055                 Expression expr;
8056                 Block body;
8057
8058                 public Foreach (Expression type, LocalVariable var, Expression expr, Statement stmt, Block body, Location l)
8059                         : base (stmt)
8060                 {
8061                         this.type = type;
8062                         this.variable = var;
8063                         this.expr = expr;
8064                         this.body = body;
8065                         loc = l;
8066                 }
8067
8068                 public Expression Expr {
8069                         get { return expr; }
8070                 }
8071
8072                 public Expression TypeExpression {
8073                         get { return type; }
8074                 }
8075
8076                 public LocalVariable Variable {
8077                         get { return variable; }
8078                 }
8079
8080                 public override Reachability MarkReachable (Reachability rc)
8081                 {
8082                         base.MarkReachable (rc);
8083
8084                         body.MarkReachable (rc);
8085
8086                         return rc;
8087                 }
8088
8089                 public override bool Resolve (BlockContext ec)
8090                 {
8091                         expr = expr.Resolve (ec);
8092                         if (expr == null)
8093                                 return false;
8094
8095                         if (expr.IsNull) {
8096                                 ec.Report.Error (186, loc, "Use of null is not valid in this context");
8097                                 return false;
8098                         }
8099
8100                         body.AddStatement (Statement);
8101
8102                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
8103                                 Statement = new ArrayForeach (this, 1);
8104                         } else if (expr.Type is ArrayContainer) {
8105                                 Statement = new ArrayForeach (this, ((ArrayContainer) expr.Type).Rank);
8106                         } else {
8107                                 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
8108                                         ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
8109                                                 expr.ExprClassName);
8110                                         return false;
8111                                 }
8112
8113                                 Statement = new CollectionForeach (this, variable, expr);
8114                         }
8115
8116                         return base.Resolve (ec);
8117                 }
8118
8119                 protected override void DoEmit (EmitContext ec)
8120                 {
8121                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
8122                         ec.LoopBegin = ec.DefineLabel ();
8123                         ec.LoopEnd = ec.DefineLabel ();
8124
8125                         if (!(Statement is Block))
8126                                 ec.BeginCompilerScope ();
8127
8128                         variable.CreateBuilder (ec);
8129
8130                         Statement.Emit (ec);
8131
8132                         if (!(Statement is Block))
8133                                 ec.EndScope ();
8134
8135                         ec.LoopBegin = old_begin;
8136                         ec.LoopEnd = old_end;
8137                 }
8138
8139                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
8140                 {
8141                         expr.FlowAnalysis (fc);
8142
8143                         var da = fc.BranchDefiniteAssignment ();
8144                         body.FlowAnalysis (fc);
8145                         fc.DefiniteAssignment = da;
8146                         return false;
8147                 }
8148
8149                 protected override void CloneTo (CloneContext clonectx, Statement t)
8150                 {
8151                         Foreach target = (Foreach) t;
8152
8153                         target.type = type.Clone (clonectx);
8154                         target.expr = expr.Clone (clonectx);
8155                         target.body = (Block) body.Clone (clonectx);
8156                         target.Statement = Statement.Clone (clonectx);
8157                 }
8158                 
8159                 public override object Accept (StructuralVisitor visitor)
8160                 {
8161                         return visitor.Visit (this);
8162                 }
8163         }
8164 }