2002-08-15 Tim Coleman <tim@timcoleman.com>
[mono.git] / mcs / mbas / statement.cs
1 //
2 // statement.cs: Statement representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@gnome.org)
7 //
8 // (C) 2001, 2002 Ximian, Inc.
9 //
10
11 using System;
12 using System.Text;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp {
18
19         using System.Collections;
20         
21         public abstract class Statement {
22                 public Location loc;
23                 
24                 ///
25                 /// Resolves the statement, true means that all sub-statements
26                 /// did resolve ok.
27                 //
28                 public virtual bool Resolve (EmitContext ec)
29                 {
30                         return true;
31                 }
32                 
33                 /// <summary>
34                 ///   Return value indicates whether all code paths emitted return.
35                 /// </summary>
36                 public abstract bool Emit (EmitContext ec);
37                 
38                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
39                 {
40                         e = e.Resolve (ec);
41                         if (e == null)
42                                 return null;
43                         
44                         if (e.Type != TypeManager.bool_type){
45                                 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
46                                                                 new Location (-1));
47                         }
48
49                         if (e == null){
50                                 Report.Error (
51                                         31, loc, "Can not convert the expression to a boolean");
52                         }
53
54                         if (CodeGen.SymbolWriter != null)
55                                 ec.Mark (loc);
56
57                         return e;
58                 }
59                 
60                 /// <remarks>
61                 ///    Encapsulates the emission of a boolean test and jumping to a
62                 ///    destination.
63                 ///
64                 ///    This will emit the bool expression in `bool_expr' and if
65                 ///    `target_is_for_true' is true, then the code will generate a 
66                 ///    brtrue to the target.   Otherwise a brfalse. 
67                 /// </remarks>
68                 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
69                                                        Label target, bool target_is_for_true)
70                 {
71                         ILGenerator ig = ec.ig;
72                         
73                         bool invert = false;
74                         if (bool_expr is Unary){
75                                 Unary u = (Unary) bool_expr;
76                                 
77                                 if (u.Oper == Unary.Operator.LogicalNot){
78                                         invert = true;
79
80                                         u.EmitLogicalNot (ec);
81                                 }
82                         } else if (bool_expr is Binary){
83                                 Binary b = (Binary) bool_expr;
84
85                                 if (b.EmitBranchable (ec, target, target_is_for_true))
86                                         return;
87                         }
88
89                         if (!invert)
90                                 bool_expr.Emit (ec);
91
92                         if (target_is_for_true){
93                                 if (invert)
94                                         ig.Emit (OpCodes.Brfalse, target);
95                                 else
96                                         ig.Emit (OpCodes.Brtrue, target);
97                         } else {
98                                 if (invert)
99                                         ig.Emit (OpCodes.Brtrue, target);
100                                 else
101                                         ig.Emit (OpCodes.Brfalse, target);
102                         }
103                 }
104
105                 public static void Warning_DeadCodeFound (Location loc)
106                 {
107                         Report.Warning (162, loc, "Unreachable code detected");
108                 }
109         }
110
111         public class EmptyStatement : Statement {
112                 public override bool Resolve (EmitContext ec)
113                 {
114                         return true;
115                 }
116                 
117                 public override bool Emit (EmitContext ec)
118                 {
119                         return false;
120                 }
121         }
122         
123         public class If : Statement {
124                 Expression expr;
125                 public Statement TrueStatement;
126                 public Statement FalseStatement;
127                 
128                 public If (Expression expr, Statement trueStatement, Location l)
129                 {
130                         this.expr = expr;
131                         TrueStatement = trueStatement;
132                         loc = l;
133                 }
134
135                 public If (Expression expr,
136                            Statement trueStatement,
137                            Statement falseStatement,
138                            Location l)
139                 {
140                         this.expr = expr;
141                         TrueStatement = trueStatement;
142                         FalseStatement = falseStatement;
143                         loc = l;
144                 }
145
146                 public override bool Resolve (EmitContext ec)
147                 {
148                         Report.Debug (1, "START IF BLOCK");
149
150                         expr = ResolveBoolean (ec, expr, loc);
151                         if (expr == null){
152                                 return false;
153                         }
154                         
155                         ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
156                         
157                         if (!TrueStatement.Resolve (ec)) {
158                                 ec.KillFlowBranching ();
159                                 return false;
160                         }
161
162                         ec.CurrentBranching.CreateSibling ();
163
164                         if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
165                                 ec.KillFlowBranching ();
166                                 return false;
167                         }
168                                         
169                         ec.EndFlowBranching ();
170
171                         Report.Debug (1, "END IF BLOCK");
172
173                         return true;
174                 }
175                 
176                 public override bool Emit (EmitContext ec)
177                 {
178                         ILGenerator ig = ec.ig;
179                         Label false_target = ig.DefineLabel ();
180                         Label end;
181                         bool is_true_ret, is_false_ret;
182
183                         //
184                         // Dead code elimination
185                         //
186                         if (expr is BoolConstant){
187                                 bool take = ((BoolConstant) expr).Value;
188
189                                 if (take){
190                                         if (FalseStatement != null){
191                                                 Warning_DeadCodeFound (FalseStatement.loc);
192                                         }
193                                         return TrueStatement.Emit (ec);
194                                 } else {
195                                         Warning_DeadCodeFound (TrueStatement.loc);
196                                         if (FalseStatement != null)
197                                                 return FalseStatement.Emit (ec);
198                                 }
199                         }
200                         
201                         EmitBoolExpression (ec, expr, false_target, false);
202
203                         is_true_ret = TrueStatement.Emit (ec);
204                         is_false_ret = is_true_ret;
205
206                         if (FalseStatement != null){
207                                 bool branch_emitted = false;
208                                 
209                                 end = ig.DefineLabel ();
210                                 if (!is_true_ret){
211                                         ig.Emit (OpCodes.Br, end);
212                                         branch_emitted = true;
213                                 }
214
215                                 ig.MarkLabel (false_target);
216                                 is_false_ret = FalseStatement.Emit (ec);
217
218                                 if (branch_emitted)
219                                         ig.MarkLabel (end);
220                         } else {
221                                 ig.MarkLabel (false_target);
222                                 is_false_ret = false;
223                         }
224
225                         return is_true_ret && is_false_ret;
226                 }
227         }
228
229         public class Do : Statement {
230                 public Expression expr;
231                 public readonly Statement  EmbeddedStatement;
232                 
233                 public Do (Statement statement, Expression boolExpr, Location l)
234                 {
235                         expr = boolExpr;
236                         EmbeddedStatement = statement;
237                         loc = l;
238                 }
239
240                 public override bool Resolve (EmitContext ec)
241                 {
242                         if (!EmbeddedStatement.Resolve (ec))
243                                 return false;
244
245                         expr = ResolveBoolean (ec, expr, loc);
246                         if (expr == null)
247                                 return false;
248                         
249                         return true;
250                 }
251                 
252                 public override bool Emit (EmitContext ec)
253                 {
254                         ILGenerator ig = ec.ig;
255                         Label loop = ig.DefineLabel ();
256                         Label old_begin = ec.LoopBegin;
257                         Label old_end = ec.LoopEnd;
258                         bool  old_inloop = ec.InLoop;
259                         bool old_breaks = ec.Breaks;
260                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
261                         
262                         ec.LoopBegin = ig.DefineLabel ();
263                         ec.LoopEnd = ig.DefineLabel ();
264                         ec.InLoop = true;
265                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
266                                 
267                         ig.MarkLabel (loop);
268                         ec.Breaks = false;
269                         EmbeddedStatement.Emit (ec);
270                         bool breaks = ec.Breaks;
271                         ig.MarkLabel (ec.LoopBegin);
272
273                         //
274                         // Dead code elimination
275                         //
276                         if (expr is BoolConstant){
277                                 bool res = ((BoolConstant) expr).Value;
278
279                                 if (res)
280                                         ec.ig.Emit (OpCodes.Br, loop); 
281                         } else
282                                 EmitBoolExpression (ec, expr, loop, true);
283                         
284                         ig.MarkLabel (ec.LoopEnd);
285
286                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
287                         ec.LoopBegin = old_begin;
288                         ec.LoopEnd = old_end;
289                         ec.InLoop = old_inloop;
290                         ec.Breaks = old_breaks;
291
292                         //
293                         // Inform whether we are infinite or not
294                         //
295                         if (expr is BoolConstant){
296                                 BoolConstant bc = (BoolConstant) expr;
297
298                                 if (bc.Value == true)
299                                         return breaks == false;
300                         }
301                         
302                         return false;
303                 }
304         }
305
306         public class While : Statement {
307                 public Expression expr;
308                 public readonly Statement Statement;
309                 
310                 public While (Expression boolExpr, Statement statement, Location l)
311                 {
312                         this.expr = boolExpr;
313                         Statement = statement;
314                         loc = l;
315                 }
316
317                 public override bool Resolve (EmitContext ec)
318                 {
319                         expr = ResolveBoolean (ec, expr, loc);
320                         if (expr == null)
321                                 return false;
322                         
323                         return Statement.Resolve (ec);
324                 }
325                 
326                 public override bool Emit (EmitContext ec)
327                 {
328                         ILGenerator ig = ec.ig;
329                         Label old_begin = ec.LoopBegin;
330                         Label old_end = ec.LoopEnd;
331                         bool old_inloop = ec.InLoop;
332                         bool old_breaks = ec.Breaks;
333                         Label while_loop = ig.DefineLabel ();
334                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
335                         bool ret;
336                         
337                         ec.LoopBegin = ig.DefineLabel ();
338                         ec.LoopEnd = ig.DefineLabel ();
339                         ec.InLoop = true;
340                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
341
342                         ig.Emit (OpCodes.Br, ec.LoopBegin);
343                         ig.MarkLabel (while_loop);
344
345                         //
346                         // Inform whether we are infinite or not
347                         //
348                         if (expr is BoolConstant){
349                                 BoolConstant bc = (BoolConstant) expr;
350
351                                 ig.MarkLabel (ec.LoopBegin);
352                                 if (bc.Value == false){
353                                         Warning_DeadCodeFound (Statement.loc);
354                                         ret = false;
355                                 } else {
356                                         bool breaks;
357                                         
358                                         ec.Breaks = false;
359                                         Statement.Emit (ec);
360                                         breaks = ec.Breaks;
361                                         ig.Emit (OpCodes.Br, ec.LoopBegin);
362                                         
363                                         //
364                                         // Inform that we are infinite (ie, `we return'), only
365                                         // if we do not `break' inside the code.
366                                         //
367                                         ret = breaks == false;
368                                 }
369                                 ig.MarkLabel (ec.LoopEnd);
370                         } else {
371                                 Statement.Emit (ec);
372                         
373                                 ig.MarkLabel (ec.LoopBegin);
374
375                                 EmitBoolExpression (ec, expr, while_loop, true);
376                                 ig.MarkLabel (ec.LoopEnd);
377
378                                 ret = false;
379                         }       
380
381                         ec.LoopBegin = old_begin;
382                         ec.LoopEnd = old_end;
383                         ec.InLoop = old_inloop;
384                         ec.Breaks = old_breaks;
385                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
386
387                         return ret;
388                 }
389         }
390
391         public class For : Statement {
392                 Expression Test;
393                 readonly Statement InitStatement;
394                 readonly Statement Increment;
395                 readonly Statement Statement;
396                 
397                 public For (Statement initStatement,
398                             Expression test,
399                             Statement increment,
400                             Statement statement,
401                             Location l)
402                 {
403                         InitStatement = initStatement;
404                         Test = test;
405                         Increment = increment;
406                         Statement = statement;
407                         loc = l;
408                 }
409
410                 public override bool Resolve (EmitContext ec)
411                 {
412                         bool ok = true;
413
414                         if (InitStatement != null){
415                                 if (!InitStatement.Resolve (ec))
416                                         ok = false;
417                         }
418
419                         if (Test != null){
420                                 Test = ResolveBoolean (ec, Test, loc);
421                                 if (Test == null)
422                                         ok = false;
423                         }
424
425                         if (Increment != null){
426                                 if (!Increment.Resolve (ec))
427                                         ok = false;
428                         }
429                         
430                         return Statement.Resolve (ec) && ok;
431                 }
432                 
433                 public override bool Emit (EmitContext ec)
434                 {
435                         ILGenerator ig = ec.ig;
436                         Label old_begin = ec.LoopBegin;
437                         Label old_end = ec.LoopEnd;
438                         bool old_inloop = ec.InLoop;
439                         bool old_breaks = ec.Breaks;
440                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
441                         Label loop = ig.DefineLabel ();
442                         Label test = ig.DefineLabel ();
443                         
444                         if (InitStatement != null)
445                                 if (! (InitStatement is EmptyStatement))
446                                         InitStatement.Emit (ec);
447
448                         ec.LoopBegin = ig.DefineLabel ();
449                         ec.LoopEnd = ig.DefineLabel ();
450                         ec.InLoop = true;
451                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
452
453                         ig.Emit (OpCodes.Br, test);
454                         ig.MarkLabel (loop);
455                         ec.Breaks = false;
456                         Statement.Emit (ec);
457                         bool breaks = ec.Breaks;
458
459                         ig.MarkLabel (ec.LoopBegin);
460                         if (!(Increment is EmptyStatement))
461                                 Increment.Emit (ec);
462
463                         ig.MarkLabel (test);
464                         //
465                         // If test is null, there is no test, and we are just
466                         // an infinite loop
467                         //
468                         if (Test != null)
469                                 EmitBoolExpression (ec, Test, loop, true);
470                         else
471                                 ig.Emit (OpCodes.Br, loop);
472                         ig.MarkLabel (ec.LoopEnd);
473
474                         ec.LoopBegin = old_begin;
475                         ec.LoopEnd = old_end;
476                         ec.InLoop = old_inloop;
477                         ec.Breaks = old_breaks;
478                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
479                         
480                         //
481                         // Inform whether we are infinite or not
482                         //
483                         if (Test != null){
484                                 if (Test is BoolConstant){
485                                         BoolConstant bc = (BoolConstant) Test;
486
487                                         if (bc.Value)
488                                                 return breaks == false;
489                                 }
490                                 return false;
491                         } else
492                                 return true;
493                 }
494         }
495         
496         public class StatementExpression : Statement {
497                 Expression expr;
498                 
499                 public StatementExpression (ExpressionStatement expr, Location l)
500                 {
501                         this.expr = expr;
502                         loc = l;
503                 }
504
505                 public override bool Resolve (EmitContext ec)
506                 {
507                         expr = (Expression) expr.Resolve (ec);
508                         return expr != null;
509                 }
510                 
511                 public override bool Emit (EmitContext ec)
512                 {
513                         ILGenerator ig = ec.ig;
514                         
515                         if (expr is ExpressionStatement)
516                                 ((ExpressionStatement) expr).EmitStatement (ec);
517                         else {
518                                 expr.Emit (ec);
519                                 ig.Emit (OpCodes.Pop);
520                         }
521
522                         return false;
523                 }
524
525                 public override string ToString ()
526                 {
527                         return "StatementExpression (" + expr + ")";
528                 }
529         }
530
531         /// <summary>
532         ///   Implements the return statement
533         /// </summary>
534         public class Return : Statement {
535                 public Expression Expr;
536                 
537                 public Return (Expression expr, Location l)
538                 {
539                         Expr = expr;
540                         loc = l;
541                 }
542
543                 public override bool Resolve (EmitContext ec)
544                 {
545                         if (Expr != null){
546                                 Expr = Expr.Resolve (ec);
547                                 if (Expr == null)
548                                         return false;
549                         }
550
551                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
552
553                         if (ec.CurrentBranching.InTryBlock ())
554                                 ec.CurrentBranching.AddFinallyVector (vector);
555
556                         vector.Returns = FlowReturns.ALWAYS;
557                         vector.Breaks = FlowReturns.ALWAYS;
558
559                         return true;
560                 }
561                 
562                 public override bool Emit (EmitContext ec)
563                 {
564                         if (ec.InFinally){
565                                 Report.Error (157,loc,"Control can not leave the body of the finally block");
566                                 return false;
567                         }
568                         
569                         if (ec.ReturnType == null){
570                                 if (Expr != null){
571                                         Report.Error (127, loc, "Return with a value not allowed here");
572                                         return true;
573                                 }
574                         } else {
575                                 if (Expr == null){
576                                         Report.Error (126, loc, "An object of type `" +
577                                                       TypeManager.CSharpName (ec.ReturnType) + "' is " +
578                                                       "expected for the return statement");
579                                         return true;
580                                 }
581
582                                 if (Expr.Type != ec.ReturnType)
583                                         Expr = Expression.ConvertImplicitRequired (
584                                                 ec, Expr, ec.ReturnType, loc);
585
586                                 if (Expr == null)
587                                         return true;
588
589                                 Expr.Emit (ec);
590
591                                 if (ec.InTry || ec.InCatch)
592                                         ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
593                         }
594
595                         if (ec.InTry || ec.InCatch) {
596                                 if (!ec.HasReturnLabel) {
597                                         ec.ReturnLabel = ec.ig.DefineLabel ();
598                                         ec.HasReturnLabel = true;
599                                 }
600                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
601                         } else
602                                 ec.ig.Emit (OpCodes.Ret);
603
604                         return true; 
605                 }
606         }
607
608         public class Goto : Statement {
609                 string target;
610                 Block block;
611                 LabeledStatement label;
612                 
613                 public override bool Resolve (EmitContext ec)
614                 {
615                         label = block.LookupLabel (target);
616                         if (label == null){
617                                 Report.Error (
618                                         159, loc,
619                                         "No such label `" + target + "' in this scope");
620                                 return false;
621                         }
622
623                         // If this is a forward goto.
624                         if (!label.IsDefined)
625                                 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
626
627                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
628
629                         return true;
630                 }
631                 
632                 public Goto (Block parent_block, string label, Location l)
633                 {
634                         block = parent_block;
635                         loc = l;
636                         target = label;
637                 }
638
639                 public string Target {
640                         get {
641                                 return target;
642                         }
643                 }
644
645                 public override bool Emit (EmitContext ec)
646                 {
647                         Label l = label.LabelTarget (ec);
648                         ec.ig.Emit (OpCodes.Br, l);
649                         
650                         return false;
651                 }
652         }
653
654         public class LabeledStatement : Statement {
655                 public readonly Location Location;
656                 string label_name;
657                 bool defined;
658                 bool referenced;
659                 Label label;
660
661                 ArrayList vectors;
662                 
663                 public LabeledStatement (string label_name, Location l)
664                 {
665                         this.label_name = label_name;
666                         this.Location = l;
667                 }
668
669                 public Label LabelTarget (EmitContext ec)
670                 {
671                         if (defined)
672                                 return label;
673                         label = ec.ig.DefineLabel ();
674                         defined = true;
675
676                         return label;
677                 }
678
679                 public bool IsDefined {
680                         get {
681                                 return defined;
682                         }
683                 }
684
685                 public bool HasBeenReferenced {
686                         get {
687                                 return referenced;
688                         }
689                 }
690
691                 public void AddUsageVector (FlowBranching.UsageVector vector)
692                 {
693                         if (vectors == null)
694                                 vectors = new ArrayList ();
695
696                         vectors.Add (vector.Clone ());
697                 }
698
699                 public override bool Resolve (EmitContext ec)
700                 {
701                         if (vectors != null)
702                                 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
703
704                         referenced = true;
705
706                         return true;
707                 }
708
709                 public override bool Emit (EmitContext ec)
710                 {
711                         LabelTarget (ec);
712                         ec.ig.MarkLabel (label);
713
714                         return false;
715                 }
716         }
717         
718
719         /// <summary>
720         ///   `goto default' statement
721         /// </summary>
722         public class GotoDefault : Statement {
723                 
724                 public GotoDefault (Location l)
725                 {
726                         loc = l;
727                 }
728
729                 public override bool Resolve (EmitContext ec)
730                 {
731                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
732                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
733                         return true;
734                 }
735
736                 public override bool Emit (EmitContext ec)
737                 {
738                         if (ec.Switch == null){
739                                 Report.Error (153, loc, "goto default is only valid in a switch statement");
740                                 return false;
741                         }
742
743                         if (!ec.Switch.GotDefault){
744                                 Report.Error (159, loc, "No default target on switch statement");
745                                 return false;
746                         }
747                         ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
748                         return false;
749                 }
750         }
751
752         /// <summary>
753         ///   `goto case' statement
754         /// </summary>
755         public class GotoCase : Statement {
756                 Expression expr;
757                 Label label;
758                 
759                 public GotoCase (Expression e, Location l)
760                 {
761                         expr = e;
762                         loc = l;
763                 }
764
765                 public override bool Resolve (EmitContext ec)
766                 {
767                         if (ec.Switch == null){
768                                 Report.Error (153, loc, "goto case is only valid in a switch statement");
769                                 return false;
770                         }
771
772                         expr = expr.Resolve (ec);
773                         if (expr == null)
774                                 return false;
775
776                         if (!(expr is Constant)){
777                                 Report.Error (159, loc, "Target expression for goto case is not constant");
778                                 return false;
779                         }
780
781                         object val = Expression.ConvertIntLiteral (
782                                 (Constant) expr, ec.Switch.SwitchType, loc);
783
784                         if (val == null)
785                                 return false;
786                                         
787                         SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
788
789                         if (sl == null){
790                                 Report.Error (
791                                         159, loc,
792                                         "No such label 'case " + val + "': for the goto case");
793                         }
794
795                         label = sl.ILLabelCode;
796
797                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
798                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
799                         return true;
800                 }
801
802                 public override bool Emit (EmitContext ec)
803                 {
804                         ec.ig.Emit (OpCodes.Br, label);
805                         return true;
806                 }
807         }
808         
809         public class Throw : Statement {
810                 Expression expr;
811                 
812                 public Throw (Expression expr, Location l)
813                 {
814                         this.expr = expr;
815                         loc = l;
816                 }
817
818                 public override bool Resolve (EmitContext ec)
819                 {
820                         if (expr != null){
821                                 expr = expr.Resolve (ec);
822                                 if (expr == null)
823                                         return false;
824
825                                 ExprClass eclass = expr.eclass;
826
827                                 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
828                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
829                                         expr.Error118 ("value, variable, property or indexer access ");
830                                         return false;
831                                 }
832
833                                 Type t = expr.Type;
834                                 
835                                 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)) {
836                                         Report.Error (155, loc,
837                                                       "The type caught or thrown must be derived " +
838                                                       "from System.Exception");
839                                         return false;
840                                 }
841                         }
842
843                         ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
844                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
845                         return true;
846                 }
847                         
848                 public override bool Emit (EmitContext ec)
849                 {
850                         if (expr == null){
851                                 if (ec.InCatch)
852                                         ec.ig.Emit (OpCodes.Rethrow);
853                                 else {
854                                         Report.Error (
855                                                 156, loc,
856                                                 "A throw statement with no argument is only " +
857                                                 "allowed in a catch clause");
858                                 }
859                                 return false;
860                         }
861
862                         expr.Emit (ec);
863
864                         ec.ig.Emit (OpCodes.Throw);
865
866                         return true;
867                 }
868         }
869
870         public class Break : Statement {
871                 
872                 public Break (Location l)
873                 {
874                         loc = l;
875                 }
876
877                 public override bool Resolve (EmitContext ec)
878                 {
879                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
880                         return true;
881                 }
882
883                 public override bool Emit (EmitContext ec)
884                 {
885                         ILGenerator ig = ec.ig;
886
887                         if (ec.InLoop == false && ec.Switch == null){
888                                 Report.Error (139, loc, "No enclosing loop or switch to continue to");
889                                 return false;
890                         }
891
892                         ec.Breaks = true;
893                         if (ec.InTry || ec.InCatch)
894                                 ig.Emit (OpCodes.Leave, ec.LoopEnd);
895                         else
896                                 ig.Emit (OpCodes.Br, ec.LoopEnd);
897
898                         return false;
899                 }
900         }
901
902         public class Continue : Statement {
903                 
904                 public Continue (Location l)
905                 {
906                         loc = l;
907                 }
908
909                 public override bool Resolve (EmitContext ec)
910                 {
911                         ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
912                         return true;
913                 }
914
915                 public override bool Emit (EmitContext ec)
916                 {
917                         Label begin = ec.LoopBegin;
918                         
919                         if (!ec.InLoop){
920                                 Report.Error (139, loc, "No enclosing loop to continue to");
921                                 return false;
922                         } 
923
924                         //
925                         // UGH: Non trivial.  This Br might cross a try/catch boundary
926                         // How can we tell?
927                         //
928                         // while () {
929                         //   try { ... } catch { continue; }
930                         // }
931                         //
932                         // From:
933                         // try {} catch { while () { continue; }}
934                         //
935                         if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
936                                 ec.ig.Emit (OpCodes.Leave, begin);
937                         else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
938                                 throw new Exception ("Should never happen");
939                         else
940                                 ec.ig.Emit (OpCodes.Br, begin);
941                         return false;
942                 }
943         }
944
945         // <summary>
946         //   This is used in the control flow analysis code to specify whether the
947         //   current code block may return to its enclosing block before reaching
948         //   its end.
949         // </summary>
950         public enum FlowReturns {
951                 // It can never return.
952                 NEVER,
953
954                 // This means that the block contains a conditional return statement
955                 // somewhere.
956                 SOMETIMES,
957
958                 // The code always returns, ie. there's an unconditional return / break
959                 // statement in it.
960                 ALWAYS,
961
962                 // The code always throws an exception.
963                 EXCEPTION,
964
965                 // The current code block is unreachable.  This happens if it's immediately
966                 // following a FlowReturns.ALWAYS block.
967                 UNREACHABLE
968         }
969
970         // <summary>
971         //   This is a special bit vector which can inherit from another bit vector doing a
972         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
973         //   current one.
974         // </summary>
975         public class MyBitVector {
976                 public readonly int Count;
977                 public readonly MyBitVector InheritsFrom;
978
979                 bool is_dirty;
980                 BitArray vector;
981
982                 public MyBitVector (int Count)
983                         : this (null, Count)
984                 { }
985
986                 public MyBitVector (MyBitVector InheritsFrom, int Count)
987                 {
988                         this.InheritsFrom = InheritsFrom;
989                         this.Count = Count;
990                 }
991
992                 // <summary>
993                 //   Checks whether this bit vector has been modified.  After setting this to true,
994                 //   we won't use the inherited vector anymore, but our own copy of it.
995                 // </summary>
996                 public bool IsDirty {
997                         get {
998                                 return is_dirty;
999                         }
1000
1001                         set {
1002                                 if (!is_dirty)
1003                                         initialize_vector ();
1004                         }
1005                 }
1006
1007                 // <summary>
1008                 //   Get/set bit `index' in the bit vector.
1009                 // </summary>
1010                 public bool this [int index]
1011                 {
1012                         get {
1013                                 if (index > Count)
1014                                         throw new ArgumentOutOfRangeException ();
1015
1016                                 // We're doing a "copy-on-write" strategy here; as long
1017                                 // as nobody writes to the array, we can use our parent's
1018                                 // copy instead of duplicating the vector.
1019
1020                                 if (vector != null)
1021                                         return vector [index];
1022                                 else if (InheritsFrom != null) {
1023                                         BitArray inherited = InheritsFrom.Vector;
1024
1025                                         if (index < inherited.Count)
1026                                                 return inherited [index];
1027                                         else
1028                                                 return false;
1029                                 } else
1030                                         return false;
1031                         }
1032
1033                         set {
1034                                 if (index > Count)
1035                                         throw new ArgumentOutOfRangeException ();
1036
1037                                 // Only copy the vector if we're actually modifying it.
1038
1039                                 if (this [index] != value) {
1040                                         initialize_vector ();
1041
1042                                         vector [index] = value;
1043                                 }
1044                         }
1045                 }
1046
1047                 // <summary>
1048                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1049                 //   copy of the bit vector.
1050                 // </summary>
1051                 public static explicit operator BitArray (MyBitVector vector)
1052                 {
1053                         vector.initialize_vector ();
1054                         return vector.Vector;
1055                 }
1056
1057                 // <summary>
1058                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1059                 //   different size than the current one.
1060                 // </summary>
1061                 public void Or (MyBitVector new_vector)
1062                 {
1063                         BitArray new_array = new_vector.Vector;
1064
1065                         initialize_vector ();
1066
1067                         int upper;
1068                         if (vector.Count < new_array.Count)
1069                                 upper = vector.Count;
1070                         else
1071                                 upper = new_array.Count;
1072
1073                         for (int i = 0; i < upper; i++)
1074                                 vector [i] = vector [i] | new_array [i];
1075                 }
1076
1077                 // <summary>
1078                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1079                 //   a different size than the current one.
1080                 // </summary>
1081                 public void And (MyBitVector new_vector)
1082                 {
1083                         BitArray new_array = new_vector.Vector;
1084
1085                         initialize_vector ();
1086
1087                         int lower, upper;
1088                         if (vector.Count < new_array.Count)
1089                                 lower = upper = vector.Count;
1090                         else {
1091                                 lower = new_array.Count;
1092                                 upper = vector.Count;
1093                         }
1094
1095                         for (int i = 0; i < lower; i++)
1096                                 vector [i] = vector [i] & new_array [i];
1097
1098                         for (int i = lower; i < upper; i++)
1099                                 vector [i] = false;
1100                 }
1101
1102                 // <summary>
1103                 //   This does a deep copy of the bit vector.
1104                 // </summary>
1105                 public MyBitVector Clone ()
1106                 {
1107                         MyBitVector retval = new MyBitVector (Count);
1108
1109                         retval.Vector = Vector;
1110
1111                         return retval;
1112                 }
1113
1114                 BitArray Vector {
1115                         get {
1116                                 if (vector != null)
1117                                         return vector;
1118                                 else if (!is_dirty && (InheritsFrom != null))
1119                                         return InheritsFrom.Vector;
1120
1121                                 initialize_vector ();
1122
1123                                 return vector;
1124                         }
1125
1126                         set {
1127                                 initialize_vector ();
1128
1129                                 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1130                                         vector [i] = value [i];
1131                         }
1132                 }
1133
1134                 void initialize_vector ()
1135                 {
1136                         if (vector != null)
1137                                 return;
1138
1139                         vector = new BitArray (Count, false);
1140                         if (InheritsFrom != null)
1141                                 Vector = InheritsFrom.Vector;
1142
1143                         is_dirty = true;
1144                 }
1145
1146                 public override string ToString ()
1147                 {
1148                         StringBuilder sb = new StringBuilder ("MyBitVector (");
1149
1150                         BitArray vector = Vector;
1151                         sb.Append (Count);
1152                         sb.Append (",");
1153                         if (!IsDirty)
1154                                 sb.Append ("INHERITED - ");
1155                         for (int i = 0; i < vector.Count; i++) {
1156                                 if (i > 0)
1157                                         sb.Append (",");
1158                                 sb.Append (vector [i]);
1159                         }
1160                         
1161                         sb.Append (")");
1162                         return sb.ToString ();
1163                 }
1164         }
1165
1166         // <summary>
1167         //   The type of a FlowBranching.
1168         // </summary>
1169         public enum FlowBranchingType {
1170                 // Normal (conditional or toplevel) block.
1171                 BLOCK,
1172
1173                 // Try/Catch block.
1174                 EXCEPTION,
1175
1176                 // Switch block.
1177                 SWITCH,
1178
1179                 // Switch section.
1180                 SWITCH_SECTION
1181         }
1182
1183         // <summary>
1184         //   A new instance of this class is created every time a new block is resolved
1185         //   and if there's branching in the block's control flow.
1186         // </summary>
1187         public class FlowBranching {
1188                 // <summary>
1189                 //   The type of this flow branching.
1190                 // </summary>
1191                 public readonly FlowBranchingType Type;
1192
1193                 // <summary>
1194                 //   The block this branching is contained in.  This may be null if it's not
1195                 //   a top-level block and it doesn't declare any local variables.
1196                 // </summary>
1197                 public readonly Block Block;
1198
1199                 // <summary>
1200                 //   The parent of this branching or null if this is the top-block.
1201                 // </summary>
1202                 public readonly FlowBranching Parent;
1203
1204                 // <summary>
1205                 //   Start-Location of this flow branching.
1206                 // </summary>
1207                 public readonly Location Location;
1208
1209                 // <summary>
1210                 //   A list of UsageVectors.  A new vector is added each time control flow may
1211                 //   take a different path.
1212                 // </summary>
1213                 public ArrayList Siblings;
1214
1215                 //
1216                 // Private
1217                 //
1218                 InternalParameters param_info;
1219                 int[] param_map;
1220                 int num_params;
1221                 ArrayList finally_vectors;
1222
1223                 static int next_id = 0;
1224                 int id;
1225
1226                 // <summary>
1227                 //   Performs an `And' operation on the FlowReturns status
1228                 //   (for instance, a block only returns ALWAYS if all its siblings
1229                 //   always return).
1230                 // </summary>
1231                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1232                 {
1233                         if (b == FlowReturns.UNREACHABLE)
1234                                 return a;
1235
1236                         switch (a) {
1237                         case FlowReturns.NEVER:
1238                                 if (b == FlowReturns.NEVER)
1239                                         return FlowReturns.NEVER;
1240                                 else
1241                                         return FlowReturns.SOMETIMES;
1242
1243                         case FlowReturns.SOMETIMES:
1244                                 return FlowReturns.SOMETIMES;
1245
1246                         case FlowReturns.ALWAYS:
1247                                 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1248                                         return FlowReturns.ALWAYS;
1249                                 else
1250                                         return FlowReturns.SOMETIMES;
1251
1252                         case FlowReturns.EXCEPTION:
1253                                 if (b == FlowReturns.EXCEPTION)
1254                                         return FlowReturns.EXCEPTION;
1255                                 else if (b == FlowReturns.ALWAYS)
1256                                         return FlowReturns.ALWAYS;
1257                                 else
1258                                         return FlowReturns.SOMETIMES;
1259                         }
1260
1261                         return b;
1262                 }
1263
1264                 // <summary>
1265                 //   The vector contains a BitArray with information about which local variables
1266                 //   and parameters are already initialized at the current code position.
1267                 // </summary>
1268                 public class UsageVector {
1269                         // <summary>
1270                         //   If this is true, then the usage vector has been modified and must be
1271                         //   merged when we're done with this branching.
1272                         // </summary>
1273                         public bool IsDirty;
1274
1275                         // <summary>
1276                         //   The number of parameters in this block.
1277                         // </summary>
1278                         public readonly int CountParameters;
1279
1280                         // <summary>
1281                         //   The number of locals in this block.
1282                         // </summary>
1283                         public readonly int CountLocals;
1284
1285                         // <summary>
1286                         //   If not null, then we inherit our state from this vector and do a
1287                         //   copy-on-write.  If null, then we're the first sibling in a top-level
1288                         //   block and inherit from the empty vector.
1289                         // </summary>
1290                         public readonly UsageVector InheritsFrom;
1291
1292                         //
1293                         // Private.
1294                         //
1295                         MyBitVector locals, parameters;
1296                         FlowReturns real_returns, real_breaks;
1297                         bool returns_set, breaks_set, is_finally;
1298
1299                         static int next_id = 0;
1300                         int id;
1301
1302                         //
1303                         // Normally, you should not use any of these constructors.
1304                         //
1305                         public UsageVector (UsageVector parent, int num_params, int num_locals)
1306                         {
1307                                 this.InheritsFrom = parent;
1308                                 this.CountParameters = num_params;
1309                                 this.CountLocals = num_locals;
1310                                 this.real_returns = FlowReturns.NEVER;
1311                                 this.real_breaks = FlowReturns.NEVER;
1312
1313                                 if (parent != null) {
1314                                         locals = new MyBitVector (parent.locals, CountLocals);
1315                                         if (num_params > 0)
1316                                                 parameters = new MyBitVector (parent.parameters, num_params);
1317                                 } else {
1318                                         locals = new MyBitVector (null, CountLocals);
1319                                         if (num_params > 0)
1320                                                 parameters = new MyBitVector (null, num_params);
1321                                 }
1322
1323                                 id = ++next_id;
1324                         }
1325
1326                         public UsageVector (UsageVector parent)
1327                                 : this (parent, parent.CountParameters, parent.CountLocals)
1328                         { }
1329
1330                         // <summary>
1331                         //   This does a deep copy of the usage vector.
1332                         // </summary>
1333                         public UsageVector Clone ()
1334                         {
1335                                 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1336
1337                                 retval.locals = locals.Clone ();
1338                                 if (parameters != null)
1339                                         retval.parameters = parameters.Clone ();
1340                                 retval.real_returns = real_returns;
1341                                 retval.real_breaks = real_breaks;
1342
1343                                 return retval;
1344                         }
1345
1346                         // 
1347                         // State of parameter `number'.
1348                         //
1349                         public bool this [int number]
1350                         {
1351                                 get {
1352                                         if (number == -1)
1353                                                 return true;
1354                                         else if (number == 0)
1355                                                 throw new ArgumentException ();
1356
1357                                         return parameters [number - 1];
1358                                 }
1359
1360                                 set {
1361                                         if (number == -1)
1362                                                 return;
1363                                         else if (number == 0)
1364                                                 throw new ArgumentException ();
1365
1366                                         parameters [number - 1] = value;
1367                                 }
1368                         }
1369
1370                         //
1371                         // State of the local variable `vi'.
1372                         //
1373                         public bool this [VariableInfo vi]
1374                         {
1375                                 get {
1376                                         if (vi.Number == -1)
1377                                                 return true;
1378                                         else if (vi.Number == 0)
1379                                                 throw new ArgumentException ();
1380
1381                                         return locals [vi.Number - 1];
1382                                 }
1383
1384                                 set {
1385                                         if (vi.Number == -1)
1386                                                 return;
1387                                         else if (vi.Number == 0)
1388                                                 throw new ArgumentException ();
1389
1390                                         locals [vi.Number - 1] = value;
1391                                 }
1392                         }
1393
1394                         // <summary>
1395                         //   Specifies when the current block returns.
1396                         // </summary>
1397                         public FlowReturns Returns {
1398                                 get {
1399                                         return real_returns;
1400                                 }
1401
1402                                 set {
1403                                         real_returns = value;
1404                                         returns_set = true;
1405                                 }
1406                         }
1407
1408                         // <summary>
1409                         //   Specifies whether control may return to our containing block
1410                         //   before reaching the end of this block.  This happens if there
1411                         //   is a break/continue/goto/return in it.
1412                         // </summary>
1413                         public FlowReturns Breaks {
1414                                 get {
1415                                         return real_breaks;
1416                                 }
1417
1418                                 set {
1419                                         real_breaks = value;
1420                                         breaks_set = true;
1421                                 }
1422                         }
1423
1424                         // <summary>
1425                         //   Merge a child branching.
1426                         // </summary>
1427                         public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1428                         {
1429                                 MyBitVector new_locals = null;
1430                                 MyBitVector new_params = null;
1431
1432                                 FlowReturns new_returns = FlowReturns.NEVER;
1433                                 FlowReturns new_breaks = FlowReturns.NEVER;
1434                                 bool new_returns_set = false, new_breaks_set = false;
1435                                 FlowReturns breaks;
1436
1437                                 Report.Debug (1, "MERGING CHILDREN", branching, this);
1438
1439                                 foreach (UsageVector child in children) {
1440                                         Report.Debug (1, "  MERGING CHILD", child);
1441
1442                                         // If Returns is already set, perform an `And' operation on it,
1443                                         // otherwise just set just.
1444                                         if (!new_returns_set) {
1445                                                 new_returns = child.Returns;
1446                                                 new_returns_set = true;
1447                                         } else
1448                                                 new_returns = AndFlowReturns (new_returns, child.Returns);
1449
1450                                         // If Breaks is already set, perform an `And' operation on it,
1451                                         // otherwise just set just.
1452                                         if (!new_breaks_set) {
1453                                                 new_breaks = child.Breaks;
1454                                                 new_breaks_set = true;
1455                                         } else
1456                                                 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1457
1458                                         // Ignore unreachable children.
1459                                         if (child.Returns == FlowReturns.UNREACHABLE)
1460                                                 continue;
1461
1462                                         // If we're a switch section, `break' won't leave the current
1463                                         // branching (NOTE: the type check here means that we're "a"
1464                                         // switch section, not that we're "in" a switch section!).
1465                                         breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1466                                                 child.Returns : child.Breaks;
1467
1468                                         // A local variable is initialized after a flow branching if it
1469                                         // has been initialized in all its branches which do neither
1470                                         // always return or always throw an exception.
1471                                         //
1472                                         // If a branch may return, but does not always return, then we
1473                                         // can treat it like a never-returning branch here: control will
1474                                         // only reach the code position after the branching if we did not
1475                                         // return here.
1476                                         //
1477                                         // It's important to distinguish between always and sometimes
1478                                         // returning branches here:
1479                                         //
1480                                         //    1   int a;
1481                                         //    2   if (something) {
1482                                         //    3      return;
1483                                         //    4      a = 5;
1484                                         //    5   }
1485                                         //    6   Console.WriteLine (a);
1486                                         //
1487                                         // The if block in lines 3-4 always returns, so we must not look
1488                                         // at the initialization of `a' in line 4 - thus it'll still be
1489                                         // uninitialized in line 6.
1490                                         //
1491                                         // On the other hand, the following is allowed:
1492                                         //
1493                                         //    1   int a;
1494                                         //    2   if (something)
1495                                         //    3      a = 5;
1496                                         //    4   else
1497                                         //    5      return;
1498                                         //    6   Console.WriteLine (a);
1499                                         //
1500                                         // Here, `a' is initialized in line 3 and we must not look at
1501                                         // line 5 since it always returns.
1502                                         // 
1503                                         if ((breaks != FlowReturns.EXCEPTION) &&
1504                                             (breaks != FlowReturns.ALWAYS)) {
1505                                                 if (new_locals != null)
1506                                                         new_locals.And (child.locals);
1507                                                 else {
1508                                                         new_locals = locals.Clone ();
1509                                                         new_locals.Or (child.locals);
1510                                                 }
1511                                         }
1512
1513                                         // An `out' parameter must be assigned in all branches which do
1514                                         // not always throw an exception.
1515                                         if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1516                                                 if (parameters != null) {
1517                                                         if (new_params != null)
1518                                                                 new_params.And (child.parameters);
1519                                                         else {
1520                                                                 new_params = parameters.Clone ();
1521                                                                 new_params.Or (child.parameters);
1522                                                         }
1523                                                 }
1524                                         }
1525
1526                                         // If we always return, check whether all `out' parameters have
1527                                         // been assigned.
1528                                         if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1529                                                 branching.CheckOutParameters (
1530                                                         child.parameters, branching.Location);
1531                                         }
1532                                 }
1533
1534                                 // Set new `Returns' status.
1535                                 if (!returns_set) {
1536                                         Returns = new_returns;
1537                                         returns_set = true;
1538                                 } else
1539                                         Returns = AndFlowReturns (Returns, new_returns);
1540
1541                                 //
1542                                 // We've now either reached the point after the branching or we will
1543                                 // never get there since we always return or always throw an exception.
1544                                 //
1545                                 // If we can reach the point after the branching, mark all locals and
1546                                 // parameters as initialized which have been initialized in all branches
1547                                 // we need to look at (see above).
1548                                 //
1549
1550                                 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1551                                         Returns : Breaks;
1552
1553                                 if ((new_locals != null) &&
1554                                     ((breaks == FlowReturns.NEVER) || (breaks == FlowReturns.SOMETIMES))) {
1555                                         locals.Or (new_locals);
1556                                 }
1557
1558                                 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1559                                         parameters.Or (new_params);
1560
1561                                 //
1562                                 // If we may have returned (this only happens if there was a reachable
1563                                 // `return' statement in one of the branches), then we may return to our
1564                                 // parent block before reaching the end of the block, so set `Breaks'.
1565                                 //
1566
1567                                 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1568                                         real_breaks = Returns;
1569                                         breaks_set = true;
1570                                 }
1571
1572                                 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1573                                               new_returns, new_breaks, this);
1574
1575                                 return new_returns;
1576                         }
1577
1578                         // <summary>
1579                         //   Tells control flow analysis that the current code position may be reached with
1580                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
1581                         //   list of UsageVectors.
1582                         //
1583                         //   This is used when resolving forward gotos - in the following example, the
1584                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
1585                         //   the goto in line 4:
1586                         //
1587                         //      1     int a;
1588                         //
1589                         //      3     if (something)
1590                         //      4        goto World;
1591                         //
1592                         //      6     a = 5;
1593                         //
1594                         //      7  World:
1595                         //      8     Console.WriteLine (a);
1596                         //
1597                         // </summary>
1598                         public void MergeJumpOrigins (ICollection origin_vectors)
1599                         {
1600                                 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1601
1602                                 real_breaks = FlowReturns.NEVER;
1603                                 breaks_set = false;
1604
1605                                 foreach (UsageVector vector in origin_vectors) {
1606                                         Report.Debug (1, "  MERGING JUMP ORIGIN", vector);
1607
1608                                         locals.And (vector.locals);
1609                                         if (parameters != null)
1610                                                 parameters.And (vector.parameters);
1611                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1612                                 }
1613
1614                                 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1615                         }
1616
1617                         // <summary>
1618                         //   This is used at the beginning of a finally block if there were
1619                         //   any return statements in the try block or one of the catch blocks.
1620                         // </summary>
1621                         public void MergeFinallyOrigins (ICollection finally_vectors)
1622                         {
1623                                 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1624
1625                                 real_breaks = FlowReturns.NEVER;
1626                                 breaks_set = false;
1627
1628                                 foreach (UsageVector vector in finally_vectors) {
1629                                         Report.Debug (1, "  MERGING FINALLY ORIGIN", vector);
1630
1631                                         if (parameters != null)
1632                                                 parameters.And (vector.parameters);
1633                                         Breaks = AndFlowReturns (Breaks, vector.Breaks);
1634                                 }
1635
1636                                 is_finally = true;
1637
1638                                 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1639                         }
1640
1641                         // <summary>
1642                         //   Performs an `or' operation on the locals and the parameters.
1643                         // </summary>
1644                         public void Or (UsageVector new_vector)
1645                         {
1646                                 locals.Or (new_vector.locals);
1647                                 if (parameters != null)
1648                                         parameters.Or (new_vector.parameters);
1649                         }
1650
1651                         // <summary>
1652                         //   Performs an `and' operation on the locals.
1653                         // </summary>
1654                         public void AndLocals (UsageVector new_vector)
1655                         {
1656                                 locals.And (new_vector.locals);
1657                         }
1658
1659                         // <summary>
1660                         //   Returns a deep copy of the parameters.
1661                         // </summary>
1662                         public MyBitVector Parameters {
1663                                 get {
1664                                         if (parameters != null)
1665                                                 return parameters.Clone ();
1666                                         else
1667                                                 return null;
1668                                 }
1669                         }
1670
1671                         // <summary>
1672                         //   Returns a deep copy of the locals.
1673                         // </summary>
1674                         public MyBitVector Locals {
1675                                 get {
1676                                         return locals.Clone ();
1677                                 }
1678                         }
1679
1680                         //
1681                         // Debugging stuff.
1682                         //
1683
1684                         public override string ToString ()
1685                         {
1686                                 StringBuilder sb = new StringBuilder ();
1687
1688                                 sb.Append ("Vector (");
1689                                 sb.Append (id);
1690                                 sb.Append (",");
1691                                 sb.Append (Returns);
1692                                 sb.Append (",");
1693                                 sb.Append (Breaks);
1694                                 if (parameters != null) {
1695                                         sb.Append (" - ");
1696                                         sb.Append (parameters);
1697                                 }
1698                                 sb.Append (" - ");
1699                                 sb.Append (locals);
1700                                 sb.Append (")");
1701
1702                                 return sb.ToString ();
1703                         }
1704                 }
1705
1706                 FlowBranching (FlowBranchingType type, Location loc)
1707                 {
1708                         this.Siblings = new ArrayList ();
1709                         this.Block = null;
1710                         this.Location = loc;
1711                         this.Type = type;
1712                         id = ++next_id;
1713                 }
1714
1715                 // <summary>
1716                 //   Creates a new flow branching for `block'.
1717                 //   This is used from Block.Resolve to create the top-level branching of
1718                 //   the block.
1719                 // </summary>
1720                 public FlowBranching (Block block, InternalParameters ip, Location loc)
1721                         : this (FlowBranchingType.BLOCK, loc)
1722                 {
1723                         Block = block;
1724                         Parent = null;
1725
1726                         param_info = ip;
1727                         param_map = new int [(param_info != null) ? param_info.Count : 0];
1728                         num_params = 0;
1729
1730                         for (int i = 0; i < param_map.Length; i++) {
1731                                 Parameter.Modifier mod = param_info.ParameterModifier (i);
1732
1733                                 if ((mod & Parameter.Modifier.OUT) == 0)
1734                                         continue;
1735
1736                                 param_map [i] = ++num_params;
1737                         }
1738
1739                         Siblings = new ArrayList ();
1740                         Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1741                 }
1742
1743                 // <summary>
1744                 //   Creates a new flow branching which is contained in `parent'.
1745                 //   You should only pass non-null for the `block' argument if this block
1746                 //   introduces any new variables - in this case, we need to create a new
1747                 //   usage vector with a different size than our parent's one.
1748                 // </summary>
1749                 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1750                                       Block block, Location loc)
1751                         : this (type, loc)
1752                 {
1753                         Parent = parent;
1754                         Block = block;
1755
1756                         if (parent != null) {
1757                                 param_info = parent.param_info;
1758                                 param_map = parent.param_map;
1759                                 num_params = parent.num_params;
1760                         }
1761
1762                         UsageVector vector;
1763                         if (Block != null)
1764                                 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1765                                                           Block.CountVariables);
1766                         else
1767                                 vector = new UsageVector (Parent.CurrentUsageVector);
1768
1769                         Siblings.Add (vector);
1770
1771                         switch (Type) {
1772                         case FlowBranchingType.EXCEPTION:
1773                                 finally_vectors = new ArrayList ();
1774                                 break;
1775
1776                         default:
1777                                 break;
1778                         }
1779                 }
1780
1781                 // <summary>
1782                 //   Returns the branching's current usage vector.
1783                 // </summary>
1784                 public UsageVector CurrentUsageVector
1785                 {
1786                         get {
1787                                 return (UsageVector) Siblings [Siblings.Count - 1];
1788                         }
1789                 }
1790
1791                 // <summary>
1792                 //   Creates a sibling of the current usage vector.
1793                 // </summary>
1794                 public void CreateSibling ()
1795                 {
1796                         Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1797
1798                         Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1799                 }
1800
1801                 // <summary>
1802                 //   Creates a sibling for a `finally' block.
1803                 // </summary>
1804                 public void CreateSiblingForFinally ()
1805                 {
1806                         if (Type != FlowBranchingType.EXCEPTION)
1807                                 throw new NotSupportedException ();
1808
1809                         CreateSibling ();
1810
1811                         CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1812                 }
1813
1814                 // <summary>
1815                 //   Check whether all `out' parameters have been assigned.
1816                 // </summary>
1817                 public void CheckOutParameters (MyBitVector parameters, Location loc)
1818                 {
1819                         if (InTryBlock ())
1820                                 return;
1821
1822                         for (int i = 0; i < param_map.Length; i++) {
1823                                 if (param_map [i] == 0)
1824                                         continue;
1825
1826                                 if (!parameters [param_map [i] - 1]) {
1827                                         Report.Error (
1828                                                 177, loc, "The out parameter `" +
1829                                                 param_info.ParameterName (i) + "` must be " +
1830                                                 "assigned before control leave the current method.");
1831                                         param_map [i] = 0;
1832                                 }
1833                         }
1834                 }
1835
1836                 // <summary>
1837                 //   Merge a child branching.
1838                 // </summary>
1839                 public FlowReturns MergeChild (FlowBranching child)
1840                 {
1841                         return CurrentUsageVector.MergeChildren (child, child.Siblings);
1842                 }
1843
1844                 // <summary>
1845                 //   Does the toplevel merging.
1846                 // </summary>
1847                 public FlowReturns MergeTopBlock ()
1848                 {
1849                         if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1850                                 throw new NotSupportedException ();
1851
1852                         UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1853
1854                         vector.MergeChildren (this, Siblings);
1855
1856                         Siblings.Clear ();
1857                         Siblings.Add (vector);
1858
1859                         Report.Debug (1, "MERGING TOP BLOCK", vector);
1860
1861                         if (vector.Returns != FlowReturns.EXCEPTION)
1862                                 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1863
1864                         return vector.Returns;
1865                 }
1866
1867                 public bool InTryBlock ()
1868                 {
1869                         if (finally_vectors != null)
1870                                 return true;
1871                         else if (Parent != null)
1872                                 return Parent.InTryBlock ();
1873                         else
1874                                 return false;
1875                 }
1876
1877                 public void AddFinallyVector (UsageVector vector)
1878                 {
1879                         if (finally_vectors != null) {
1880                                 finally_vectors.Add (vector.Clone ());
1881                                 return;
1882                         }
1883
1884                         if (Parent != null)
1885                                 Parent.AddFinallyVector (vector);
1886                         else
1887                                 throw new NotSupportedException ();
1888                 }
1889
1890                 public bool IsVariableAssigned (VariableInfo vi)
1891                 {
1892                         Report.Debug (2, "CHECK VARIABLE ACCESS", this, vi);
1893
1894                         if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1895                                 return true;
1896                         else
1897                                 return CurrentUsageVector [vi];
1898                 }
1899
1900                 public void SetVariableAssigned (VariableInfo vi)
1901                 {
1902                         Report.Debug (2, "SET VARIABLE ACCESS", this, vi, CurrentUsageVector);
1903
1904                         if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1905                                 return;
1906
1907                         CurrentUsageVector [vi] = true;
1908                 }
1909
1910                 public bool IsParameterAssigned (int number)
1911                 {
1912                         Report.Debug (2, "IS PARAMETER ASSIGNED", this, number);
1913
1914                         if (param_map [number] == 0)
1915                                 return true;
1916                         else
1917                                 return CurrentUsageVector [param_map [number]];
1918                 }
1919
1920                 public void SetParameterAssigned (int number)
1921                 {
1922                         Report.Debug (2, "SET PARAMETER ACCESS", this, number, param_map [number],
1923                                       CurrentUsageVector);
1924
1925                         if (param_map [number] == 0)
1926                                 return;
1927
1928                         if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
1929                                 CurrentUsageVector [param_map [number]] = true;
1930                 }
1931
1932                 public override string ToString ()
1933                 {
1934                         StringBuilder sb = new StringBuilder ("FlowBranching (");
1935
1936                         sb.Append (id);
1937                         sb.Append (",");
1938                         sb.Append (Type);
1939                         if (Block != null) {
1940                                 sb.Append (" - ");
1941                                 sb.Append (Block.ID);
1942                                 sb.Append (" - ");
1943                                 sb.Append (Block.StartLocation);
1944                         }
1945                         sb.Append (" - ");
1946                         sb.Append (Siblings.Count);
1947                         sb.Append (" - ");
1948                         sb.Append (CurrentUsageVector);
1949                         sb.Append (")");
1950                         return sb.ToString ();
1951                 }
1952         }
1953         
1954         public class VariableInfo {
1955                 public Expression Type;
1956                 public LocalBuilder LocalBuilder;
1957                 public Type VariableType;
1958                 public readonly Location Location;
1959                 public readonly int Block;
1960
1961                 public int Number;
1962                 
1963                 public bool Used;
1964                 public bool Assigned;
1965                 public bool ReadOnly;
1966                 
1967                 public VariableInfo (Expression type, int block, Location l)
1968                 {
1969                         Type = type;
1970                         Block = block;
1971                         LocalBuilder = null;
1972                         Location = l;
1973                 }
1974
1975                 public void MakePinned ()
1976                 {
1977                         TypeManager.MakePinned (LocalBuilder);
1978                 }
1979
1980                 public override string ToString ()
1981                 {
1982                         return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
1983                 }
1984         }
1985                 
1986         /// <summary>
1987         ///   Block represents a C# block.
1988         /// </summary>
1989         ///
1990         /// <remarks>
1991         ///   This class is used in a number of places: either to represent
1992         ///   explicit blocks that the programmer places or implicit blocks.
1993         ///
1994         ///   Implicit blocks are used as labels or to introduce variable
1995         ///   declarations.
1996         /// </remarks>
1997         public class Block : Statement {
1998                 public readonly Block     Parent;
1999                 public readonly bool      Implicit;
2000                 public readonly Location  StartLocation;
2001                 public Location           EndLocation;
2002
2003                 //
2004                 // The statements in this block
2005                 //
2006                 ArrayList statements;
2007
2008                 //
2009                 // An array of Blocks.  We keep track of children just
2010                 // to generate the local variable declarations.
2011                 //
2012                 // Statements and child statements are handled through the
2013                 // statements.
2014                 //
2015                 ArrayList children;
2016                 
2017                 //
2018                 // Labels.  (label, block) pairs.
2019                 //
2020                 Hashtable labels;
2021
2022                 //
2023                 // Keeps track of (name, type) pairs
2024                 //
2025                 Hashtable variables;
2026
2027                 //
2028                 // Keeps track of constants
2029                 Hashtable constants;
2030
2031                 //
2032                 // Maps variable names to ILGenerator.LocalBuilders
2033                 //
2034                 Hashtable local_builders;
2035
2036                 bool used = false;
2037
2038                 static int id;
2039
2040                 int this_id;
2041                 
2042                 public Block (Block parent)
2043                         : this (parent, false, Location.Null, Location.Null)
2044                 { }
2045
2046                 public Block (Block parent, bool implicit_block)
2047                         : this (parent, implicit_block, Location.Null, Location.Null)
2048                 { }
2049
2050                 public Block (Block parent, Location start, Location end)
2051                         : this (parent, false, start, end)
2052                 { }
2053
2054                 public Block (Block parent, bool implicit_block, Location start, Location end)
2055                 {
2056                         if (parent != null)
2057                                 parent.AddChild (this);
2058                         
2059                         this.Parent = parent;
2060                         this.Implicit = implicit_block;
2061                         this.StartLocation = start;
2062                         this.EndLocation = end;
2063                         this.loc = start;
2064                         this_id = id++;
2065                         statements = new ArrayList ();
2066                 }
2067
2068                 public int ID {
2069                         get {
2070                                 if (Implicit)
2071                                         return Parent.ID;
2072                                 else
2073                                         return this_id;
2074                         }
2075                 }
2076                 
2077                 void AddChild (Block b)
2078                 {
2079                         if (children == null)
2080                                 children = new ArrayList ();
2081                         
2082                         children.Add (b);
2083                 }
2084
2085                 public void SetEndLocation (Location loc)
2086                 {
2087                         EndLocation = loc;
2088                 }
2089
2090                 /// <summary>
2091                 ///   Adds a label to the current block. 
2092                 /// </summary>
2093                 ///
2094                 /// <returns>
2095                 ///   false if the name already exists in this block. true
2096                 ///   otherwise.
2097                 /// </returns>
2098                 ///
2099                 public bool AddLabel (string name, LabeledStatement target)
2100                 {
2101                         if (labels == null)
2102                                 labels = new Hashtable ();
2103                         if (labels.Contains (name))
2104                                 return false;
2105                         
2106                         labels.Add (name, target);
2107                         return true;
2108                 }
2109
2110                 public LabeledStatement LookupLabel (string name)
2111                 {
2112                         if (labels != null){
2113                                 if (labels.Contains (name))
2114                                         return ((LabeledStatement) labels [name]);
2115                         }
2116
2117                         if (Parent != null)
2118                                 return Parent.LookupLabel (name);
2119
2120                         return null;
2121                 }
2122
2123                 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2124                 {
2125                         if (variables == null)
2126                                 variables = new Hashtable ();
2127
2128                         VariableInfo vi = GetVariableInfo (name);
2129                         if (vi != null) {
2130                                 if (vi.Block != ID)
2131                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2132                                                       "cannot be declared in this scope since it would " +
2133                                                       "give a different meaning to `" + name + "', which " +
2134                                                       "is already used in a `parent or current' scope to " +
2135                                                       "denote something else");
2136                                 else
2137                                         Report.Error (128, l, "A local variable `" + name + "' is already " +
2138                                                       "defined in this scope");
2139                                 return null;
2140                         }
2141
2142                         if (pars != null) {
2143                                 int idx = 0;
2144                                 Parameter p = pars.GetParameterByName (name, out idx);
2145                                 if (p != null) {
2146                                         Report.Error (136, l, "A local variable named `" + name + "' " +
2147                                                       "cannot be declared in this scope since it would " +
2148                                                       "give a different meaning to `" + name + "', which " +
2149                                                       "is already used in a `parent or current' scope to " +
2150                                                       "denote something else");
2151                                         return null;
2152                                 }
2153                         }
2154                         
2155                         vi = new VariableInfo (type, ID, l);
2156
2157                         variables.Add (name, vi);
2158
2159                         if (variables_initialized)
2160                                 throw new Exception ();
2161
2162                         // Console.WriteLine ("Adding {0} to {1}", name, ID);
2163                         return vi;
2164                 }
2165
2166                 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2167                 {
2168                         if (AddVariable (type, name, pars, l) == null)
2169                                 return false;
2170                         
2171                         if (constants == null)
2172                                 constants = new Hashtable ();
2173
2174                         constants.Add (name, value);
2175                         return true;
2176                 }
2177
2178                 public Hashtable Variables {
2179                         get {
2180                                 return variables;
2181                         }
2182                 }
2183
2184                 public VariableInfo GetVariableInfo (string name)
2185                 {
2186                         if (variables != null) {
2187                                 object temp;
2188                                 temp = variables [name];
2189
2190                                 if (temp != null){
2191                                         return (VariableInfo) temp;
2192                                 }
2193                         }
2194
2195                         if (Parent != null)
2196                                 return Parent.GetVariableInfo (name);
2197
2198                         return null;
2199                 }
2200                 
2201                 public Expression GetVariableType (string name)
2202                 {
2203                         VariableInfo vi = GetVariableInfo (name);
2204
2205                         if (vi != null)
2206                                 return vi.Type;
2207
2208                         return null;
2209                 }
2210
2211                 public Expression GetConstantExpression (string name)
2212                 {
2213                         if (constants != null) {
2214                                 object temp;
2215                                 temp = constants [name];
2216                                 
2217                                 if (temp != null)
2218                                         return (Expression) temp;
2219                         }
2220                         
2221                         if (Parent != null)
2222                                 return Parent.GetConstantExpression (name);
2223
2224                         return null;
2225                 }
2226                 
2227                 /// <summary>
2228                 ///   True if the variable named @name has been defined
2229                 ///   in this block
2230                 /// </summary>
2231                 public bool IsVariableDefined (string name)
2232                 {
2233                         // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2234                         if (variables != null) {
2235                                 if (variables.Contains (name))
2236                                         return true;
2237                         }
2238                         
2239                         if (Parent != null)
2240                                 return Parent.IsVariableDefined (name);
2241
2242                         return false;
2243                 }
2244
2245                 /// <summary>
2246                 ///   True if the variable named @name is a constant
2247                 ///  </summary>
2248                 public bool IsConstant (string name)
2249                 {
2250                         Expression e = null;
2251                         
2252                         e = GetConstantExpression (name);
2253                         
2254                         return e != null;
2255                 }
2256                 
2257                 /// <summary>
2258                 ///   Use to fetch the statement associated with this label
2259                 /// </summary>
2260                 public Statement this [string name] {
2261                         get {
2262                                 return (Statement) labels [name];
2263                         }
2264                 }
2265
2266                 /// <returns>
2267                 ///   A list of labels that were not used within this block
2268                 /// </returns>
2269                 public string [] GetUnreferenced ()
2270                 {
2271                         // FIXME: Implement me
2272                         return null;
2273                 }
2274
2275                 public void AddStatement (Statement s)
2276                 {
2277                         statements.Add (s);
2278                         used = true;
2279                 }
2280
2281                 public bool Used {
2282                         get {
2283                                 return used;
2284                         }
2285                 }
2286
2287                 public void Use ()
2288                 {
2289                         used = true;
2290                 }
2291
2292                 bool variables_initialized = false;
2293                 int count_variables = 0, first_variable = 0;
2294
2295                 void UpdateVariableInfo (EmitContext ec)
2296                 {
2297                         DeclSpace ds = ec.DeclSpace;
2298
2299                         first_variable = 0;
2300
2301                         if (Parent != null)
2302                                 first_variable += Parent.CountVariables;
2303
2304                         count_variables = first_variable;
2305                         if (variables != null) {
2306                                 foreach (VariableInfo vi in variables.Values) {
2307                                         Report.Debug (2, "VARIABLE", vi);
2308
2309                                         Type type = ds.ResolveType (vi.Type, false, vi.Location);
2310                                         if (type == null) {
2311                                                 vi.Number = -1;
2312                                                 continue;
2313                                         }
2314
2315                                         vi.VariableType = type;
2316
2317                                         Report.Debug (2, "VARIABLE", vi, type, type.IsValueType,
2318                                                       TypeManager.IsValueType (type),
2319                                                       TypeManager.IsBuiltinType (type));
2320
2321                                         // FIXME: we don't have support for structs yet.
2322                                         if (TypeManager.IsValueType (type) && !TypeManager.IsBuiltinType (type))
2323                                                 vi.Number = -1;
2324                                         else
2325                                                 vi.Number = ++count_variables;
2326                                 }
2327                         }
2328
2329                         variables_initialized = true;
2330                 }
2331
2332                 //
2333                 // <returns>
2334                 //   The number of local variables in this block
2335                 // </returns>
2336                 public int CountVariables
2337                 {
2338                         get {
2339                                 if (!variables_initialized)
2340                                         throw new Exception ();
2341
2342                                 return count_variables;
2343                         }
2344                 }
2345
2346                 /// <summary>
2347                 ///   Emits the variable declarations and labels.
2348                 /// </summary>
2349                 /// <remarks>
2350                 ///   tc: is our typecontainer (to resolve type references)
2351                 ///   ig: is the code generator:
2352                 ///   toplevel: the toplevel block.  This is used for checking 
2353                 ///             that no two labels with the same name are used.
2354                 /// </remarks>
2355                 public void EmitMeta (EmitContext ec, Block toplevel)
2356                 {
2357                         DeclSpace ds = ec.DeclSpace;
2358                         ILGenerator ig = ec.ig;
2359
2360                         if (!variables_initialized)
2361                                 UpdateVariableInfo (ec);
2362
2363                         //
2364                         // Process this block variables
2365                         //
2366                         if (variables != null){
2367                                 local_builders = new Hashtable ();
2368                                 
2369                                 foreach (DictionaryEntry de in variables){
2370                                         string name = (string) de.Key;
2371                                         VariableInfo vi = (VariableInfo) de.Value;
2372
2373                                         if (vi.VariableType == null)
2374                                                 continue;
2375
2376                                         vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2377
2378                                         if (CodeGen.SymbolWriter != null)
2379                                                 vi.LocalBuilder.SetLocalSymInfo (name);
2380
2381                                         if (constants == null)
2382                                                 continue;
2383
2384                                         Expression cv = (Expression) constants [name];
2385                                         if (cv == null)
2386                                                 continue;
2387
2388                                         Expression e = cv.Resolve (ec);
2389                                         if (e == null)
2390                                                 continue;
2391
2392                                         if (!(e is Constant)){
2393                                                 Report.Error (133, vi.Location,
2394                                                               "The expression being assigned to `" +
2395                                                               name + "' must be constant (" + e + ")");
2396                                                 continue;
2397                                         }
2398
2399                                         constants.Remove (name);
2400                                         constants.Add (name, e);
2401                                 }
2402                         }
2403
2404                         //
2405                         // Now, handle the children
2406                         //
2407                         if (children != null){
2408                                 foreach (Block b in children)
2409                                         b.EmitMeta (ec, toplevel);
2410                         }
2411                 }
2412
2413                 public void UsageWarning ()
2414                 {
2415                         string name;
2416                         
2417                         if (variables != null){
2418                                 foreach (DictionaryEntry de in variables){
2419                                         VariableInfo vi = (VariableInfo) de.Value;
2420                                         
2421                                         if (vi.Used)
2422                                                 continue;
2423                                         
2424                                         name = (string) de.Key;
2425                                                 
2426                                         if (vi.Assigned){
2427                                                 Report.Warning (
2428                                                         219, vi.Location, "The variable `" + name +
2429                                                         "' is assigned but its value is never used");
2430                                         } else {
2431                                                 Report.Warning (
2432                                                         168, vi.Location, "The variable `" +
2433                                                         name +
2434                                                         "' is declared but never used");
2435                                         } 
2436                                 }
2437                         }
2438
2439                         if (children != null)
2440                                 foreach (Block b in children)
2441                                         b.UsageWarning ();
2442                 }
2443
2444                 public override bool Resolve (EmitContext ec)
2445                 {
2446                         Block prev_block = ec.CurrentBlock;
2447                         bool ok = true;
2448
2449                         ec.CurrentBlock = this;
2450                         ec.StartFlowBranching (this);
2451
2452                         Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2453
2454                         if (!variables_initialized)
2455                                 UpdateVariableInfo (ec);
2456
2457                         foreach (Statement s in statements){
2458                                 if (s.Resolve (ec) == false)
2459                                         ok = false;
2460                         }
2461
2462                         Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2463
2464                         ec.EndFlowBranching ();
2465                         ec.CurrentBlock = prev_block;
2466
2467                         if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2468                                 foreach (LabeledStatement label in labels.Values)
2469                                         if (!label.HasBeenReferenced)
2470                                                 Report.Warning (164, label.Location,
2471                                                                 "This label has not been referenced");
2472                         }
2473
2474                         return ok;
2475                 }
2476                 
2477                 public override bool Emit (EmitContext ec)
2478                 {
2479                         bool is_ret = false, this_ret = false;
2480                         Block prev_block = ec.CurrentBlock;
2481                         bool warning_shown = false;
2482
2483                         ec.CurrentBlock = this;
2484
2485                         if (CodeGen.SymbolWriter != null) {
2486                                 ec.Mark (StartLocation);
2487                                 
2488                                 foreach (Statement s in statements) {
2489                                         ec.Mark (s.loc);
2490                                         
2491                                         if (is_ret && !warning_shown && !(s is EmptyStatement)){
2492                                                 warning_shown = true;
2493                                                 Warning_DeadCodeFound (s.loc);
2494                                         }
2495                                         this_ret = s.Emit (ec);
2496                                         if (this_ret)
2497                                                 is_ret = true;
2498                                 }
2499
2500                                 ec.Mark (EndLocation); 
2501                         } else {
2502                                 foreach (Statement s in statements){
2503                                         if (is_ret && !warning_shown && !(s is EmptyStatement)){
2504                                                 warning_shown = true;
2505                                                 Warning_DeadCodeFound (s.loc);
2506                                         }
2507                                         this_ret = s.Emit (ec);
2508                                         if (this_ret)
2509                                                 is_ret = true;
2510                                 }
2511                         }
2512                         
2513                         ec.CurrentBlock = prev_block;
2514                         return is_ret;
2515                 }
2516         }
2517
2518         public class SwitchLabel {
2519                 Expression label;
2520                 object converted;
2521                 public Location loc;
2522                 public Label ILLabel;
2523                 public Label ILLabelCode;
2524
2525                 //
2526                 // if expr == null, then it is the default case.
2527                 //
2528                 public SwitchLabel (Expression expr, Location l)
2529                 {
2530                         label = expr;
2531                         loc = l;
2532                 }
2533
2534                 public Expression Label {
2535                         get {
2536                                 return label;
2537                         }
2538                 }
2539
2540                 public object Converted {
2541                         get {
2542                                 return converted;
2543                         }
2544                 }
2545
2546                 //
2547                 // Resolves the expression, reduces it to a literal if possible
2548                 // and then converts it to the requested type.
2549                 //
2550                 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2551                 {
2552                         ILLabel = ec.ig.DefineLabel ();
2553                         ILLabelCode = ec.ig.DefineLabel ();
2554
2555                         if (label == null)
2556                                 return true;
2557                         
2558                         Expression e = label.Resolve (ec);
2559
2560                         if (e == null)
2561                                 return false;
2562
2563                         if (!(e is Constant)){
2564                                 Console.WriteLine ("Value is: " + label);
2565                                 Report.Error (150, loc, "A constant value is expected");
2566                                 return false;
2567                         }
2568
2569                         if (e is StringConstant || e is NullLiteral){
2570                                 if (required_type == TypeManager.string_type){
2571                                         converted = label;
2572                                         ILLabel = ec.ig.DefineLabel ();
2573                                         return true;
2574                                 }
2575                         }
2576
2577                         converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2578                         if (converted == null)
2579                                 return false;
2580
2581                         return true;
2582                 }
2583         }
2584
2585         public class SwitchSection {
2586                 // An array of SwitchLabels.
2587                 public readonly ArrayList Labels;
2588                 public readonly Block Block;
2589                 
2590                 public SwitchSection (ArrayList labels, Block block)
2591                 {
2592                         Labels = labels;
2593                         Block = block;
2594                 }
2595         }
2596         
2597         public class Switch : Statement {
2598                 public readonly ArrayList Sections;
2599                 public Expression Expr;
2600
2601                 /// <summary>
2602                 ///   Maps constants whose type type SwitchType to their  SwitchLabels.
2603                 /// </summary>
2604                 public Hashtable Elements;
2605
2606                 /// <summary>
2607                 ///   The governing switch type
2608                 /// </summary>
2609                 public Type SwitchType;
2610
2611                 //
2612                 // Computed
2613                 //
2614                 bool got_default;
2615                 Label default_target;
2616                 Expression new_expr;
2617
2618                 //
2619                 // The types allowed to be implicitly cast from
2620                 // on the governing type
2621                 //
2622                 static Type [] allowed_types;
2623                 
2624                 public Switch (Expression e, ArrayList sects, Location l)
2625                 {
2626                         Expr = e;
2627                         Sections = sects;
2628                         loc = l;
2629                 }
2630
2631                 public bool GotDefault {
2632                         get {
2633                                 return got_default;
2634                         }
2635                 }
2636
2637                 public Label DefaultTarget {
2638                         get {
2639                                 return default_target;
2640                         }
2641                 }
2642
2643                 //
2644                 // Determines the governing type for a switch.  The returned
2645                 // expression might be the expression from the switch, or an
2646                 // expression that includes any potential conversions to the
2647                 // integral types or to string.
2648                 //
2649                 Expression SwitchGoverningType (EmitContext ec, Type t)
2650                 {
2651                         if (t == TypeManager.int32_type ||
2652                             t == TypeManager.uint32_type ||
2653                             t == TypeManager.char_type ||
2654                             t == TypeManager.byte_type ||
2655                             t == TypeManager.sbyte_type ||
2656                             t == TypeManager.ushort_type ||
2657                             t == TypeManager.short_type ||
2658                             t == TypeManager.uint64_type ||
2659                             t == TypeManager.int64_type ||
2660                             t == TypeManager.string_type ||
2661                                 t == TypeManager.bool_type ||
2662                                 t.IsSubclassOf (TypeManager.enum_type))
2663                                 return Expr;
2664
2665                         if (allowed_types == null){
2666                                 allowed_types = new Type [] {
2667                                         TypeManager.sbyte_type,
2668                                         TypeManager.byte_type,
2669                                         TypeManager.short_type,
2670                                         TypeManager.ushort_type,
2671                                         TypeManager.int32_type,
2672                                         TypeManager.uint32_type,
2673                                         TypeManager.int64_type,
2674                                         TypeManager.uint64_type,
2675                                         TypeManager.char_type,
2676                                         TypeManager.bool_type,
2677                                         TypeManager.string_type
2678                                 };
2679                         }
2680
2681                         //
2682                         // Try to find a *user* defined implicit conversion.
2683                         //
2684                         // If there is no implicit conversion, or if there are multiple
2685                         // conversions, we have to report an error
2686                         //
2687                         Expression converted = null;
2688                         foreach (Type tt in allowed_types){
2689                                 Expression e;
2690                                 
2691                                 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
2692                                 if (e == null)
2693                                         continue;
2694
2695                                 if (converted != null){
2696                                         Report.Error (-12, loc, "More than one conversion to an integral " +
2697                                                       " type exists for type `" +
2698                                                       TypeManager.CSharpName (Expr.Type)+"'");
2699                                         return null;
2700                                 } else
2701                                         converted = e;
2702                         }
2703                         return converted;
2704                 }
2705
2706                 void error152 (string n)
2707                 {
2708                         Report.Error (
2709                                 152, "The label `" + n + ":' " +
2710                                 "is already present on this switch statement");
2711                 }
2712                 
2713                 //
2714                 // Performs the basic sanity checks on the switch statement
2715                 // (looks for duplicate keys and non-constant expressions).
2716                 //
2717                 // It also returns a hashtable with the keys that we will later
2718                 // use to compute the switch tables
2719                 //
2720                 bool CheckSwitch (EmitContext ec)
2721                 {
2722                         Type compare_type;
2723                         bool error = false;
2724                         Elements = new Hashtable ();
2725                                 
2726                         got_default = false;
2727
2728                         if (TypeManager.IsEnumType (SwitchType)){
2729                                 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2730                         } else
2731                                 compare_type = SwitchType;
2732                         
2733                         foreach (SwitchSection ss in Sections){
2734                                 foreach (SwitchLabel sl in ss.Labels){
2735                                         if (!sl.ResolveAndReduce (ec, SwitchType)){
2736                                                 error = true;
2737                                                 continue;
2738                                         }
2739
2740                                         if (sl.Label == null){
2741                                                 if (got_default){
2742                                                         error152 ("default");
2743                                                         error = true;
2744                                                 }
2745                                                 got_default = true;
2746                                                 continue;
2747                                         }
2748                                         
2749                                         object key = sl.Converted;
2750
2751                                         if (key is Constant)
2752                                                 key = ((Constant) key).GetValue ();
2753
2754                                         if (key == null)
2755                                                 key = NullLiteral.Null;
2756                                         
2757                                         string lname = null;
2758                                         if (compare_type == TypeManager.uint64_type){
2759                                                 ulong v = (ulong) key;
2760
2761                                                 if (Elements.Contains (v))
2762                                                         lname = v.ToString ();
2763                                                 else
2764                                                         Elements.Add (v, sl);
2765                                         } else if (compare_type == TypeManager.int64_type){
2766                                                 long v = (long) key;
2767
2768                                                 if (Elements.Contains (v))
2769                                                         lname = v.ToString ();
2770                                                 else
2771                                                         Elements.Add (v, sl);
2772                                         } else if (compare_type == TypeManager.uint32_type){
2773                                                 uint v = (uint) key;
2774
2775                                                 if (Elements.Contains (v))
2776                                                         lname = v.ToString ();
2777                                                 else
2778                                                         Elements.Add (v, sl);
2779                                         } else if (compare_type == TypeManager.char_type){
2780                                                 char v = (char) key;
2781                                                 
2782                                                 if (Elements.Contains (v))
2783                                                         lname = v.ToString ();
2784                                                 else
2785                                                         Elements.Add (v, sl);
2786                                         } else if (compare_type == TypeManager.byte_type){
2787                                                 byte v = (byte) key;
2788                                                 
2789                                                 if (Elements.Contains (v))
2790                                                         lname = v.ToString ();
2791                                                 else
2792                                                         Elements.Add (v, sl);
2793                                         } else if (compare_type == TypeManager.sbyte_type){
2794                                                 sbyte v = (sbyte) key;
2795                                                 
2796                                                 if (Elements.Contains (v))
2797                                                         lname = v.ToString ();
2798                                                 else
2799                                                         Elements.Add (v, sl);
2800                                         } else if (compare_type == TypeManager.short_type){
2801                                                 short v = (short) key;
2802                                                 
2803                                                 if (Elements.Contains (v))
2804                                                         lname = v.ToString ();
2805                                                 else
2806                                                         Elements.Add (v, sl);
2807                                         } else if (compare_type == TypeManager.ushort_type){
2808                                                 ushort v = (ushort) key;
2809                                                 
2810                                                 if (Elements.Contains (v))
2811                                                         lname = v.ToString ();
2812                                                 else
2813                                                         Elements.Add (v, sl);
2814                                         } else if (compare_type == TypeManager.string_type){
2815                                                 if (key is NullLiteral){
2816                                                         if (Elements.Contains (NullLiteral.Null))
2817                                                                 lname = "null";
2818                                                         else
2819                                                                 Elements.Add (NullLiteral.Null, null);
2820                                                 } else {
2821                                                         string s = (string) key;
2822
2823                                                         if (Elements.Contains (s))
2824                                                                 lname = s;
2825                                                         else
2826                                                                 Elements.Add (s, sl);
2827                                                 }
2828                                         } else if (compare_type == TypeManager.int32_type) {
2829                                                 int v = (int) key;
2830
2831                                                 if (Elements.Contains (v))
2832                                                         lname = v.ToString ();
2833                                                 else
2834                                                         Elements.Add (v, sl);
2835                                         } else if (compare_type == TypeManager.bool_type) {
2836                                                 bool v = (bool) key;
2837
2838                                                 if (Elements.Contains (v))
2839                                                         lname = v.ToString ();
2840                                                 else
2841                                                         Elements.Add (v, sl);
2842                                         }
2843                                         else
2844                                         {
2845                                                 throw new Exception ("Unknown switch type!" +
2846                                                                      SwitchType + " " + compare_type);
2847                                         }
2848
2849                                         if (lname != null){
2850                                                 error152 ("case + " + lname);
2851                                                 error = true;
2852                                         }
2853                                 }
2854                         }
2855                         if (error)
2856                                 return false;
2857                         
2858                         return true;
2859                 }
2860
2861                 void EmitObjectInteger (ILGenerator ig, object k)
2862                 {
2863                         if (k is int)
2864                                 IntConstant.EmitInt (ig, (int) k);
2865                         else if (k is Constant) {
2866                                 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2867                         } 
2868                         else if (k is uint)
2869                                 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2870                         else if (k is long)
2871                         {
2872                                 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2873                                 {
2874                                         IntConstant.EmitInt (ig, (int) (long) k);
2875                                         ig.Emit (OpCodes.Conv_I8);
2876                                 }
2877                                 else
2878                                         LongConstant.EmitLong (ig, (long) k);
2879                         }
2880                         else if (k is ulong)
2881                         {
2882                                 if ((ulong) k < (1L<<32))
2883                                 {
2884                                         IntConstant.EmitInt (ig, (int) (long) k);
2885                                         ig.Emit (OpCodes.Conv_U8);
2886                                 }
2887                                 else
2888                                 {
2889                                         LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2890                                 }
2891                         }
2892                         else if (k is char)
2893                                 IntConstant.EmitInt (ig, (int) ((char) k));
2894                         else if (k is sbyte)
2895                                 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2896                         else if (k is byte)
2897                                 IntConstant.EmitInt (ig, (int) ((byte) k));
2898                         else if (k is short)
2899                                 IntConstant.EmitInt (ig, (int) ((short) k));
2900                         else if (k is ushort)
2901                                 IntConstant.EmitInt (ig, (int) ((ushort) k));
2902                         else if (k is bool)
2903                                 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2904                         else
2905                                 throw new Exception ("Unhandled case");
2906                 }
2907                 
2908                 // structure used to hold blocks of keys while calculating table switch
2909                 class KeyBlock : IComparable
2910                 {
2911                         public KeyBlock (long _nFirst)
2912                         {
2913                                 nFirst = nLast = _nFirst;
2914                         }
2915                         public long nFirst;
2916                         public long nLast;
2917                         public ArrayList rgKeys = null;
2918                         public int Length
2919                         {
2920                                 get { return (int) (nLast - nFirst + 1); }
2921                         }
2922                         public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2923                         {
2924                                 return kbLast.nLast - kbFirst.nFirst + 1;
2925                         }
2926                         public int CompareTo (object obj)
2927                         {
2928                                 KeyBlock kb = (KeyBlock) obj;
2929                                 int nLength = Length;
2930                                 int nLengthOther = kb.Length;
2931                                 if (nLengthOther == nLength)
2932                                         return (int) (kb.nFirst - nFirst);
2933                                 return nLength - nLengthOther;
2934                         }
2935                 }
2936
2937                 /// <summary>
2938                 /// This method emits code for a lookup-based switch statement (non-string)
2939                 /// Basically it groups the cases into blocks that are at least half full,
2940                 /// and then spits out individual lookup opcodes for each block.
2941                 /// It emits the longest blocks first, and short blocks are just
2942                 /// handled with direct compares.
2943                 /// </summary>
2944                 /// <param name="ec"></param>
2945                 /// <param name="val"></param>
2946                 /// <returns></returns>
2947                 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2948                 {
2949                         int cElements = Elements.Count;
2950                         object [] rgKeys = new object [cElements];
2951                         Elements.Keys.CopyTo (rgKeys, 0);
2952                         Array.Sort (rgKeys);
2953
2954                         // initialize the block list with one element per key
2955                         ArrayList rgKeyBlocks = new ArrayList ();
2956                         foreach (object key in rgKeys)
2957                                 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
2958
2959                         KeyBlock kbCurr;
2960                         // iteratively merge the blocks while they are at least half full
2961                         // there's probably a really cool way to do this with a tree...
2962                         while (rgKeyBlocks.Count > 1)
2963                         {
2964                                 ArrayList rgKeyBlocksNew = new ArrayList ();
2965                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2966                                 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2967                                 {
2968                                         KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2969                                         if ((kbCurr.Length + kb.Length) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
2970                                         {
2971                                                 // merge blocks
2972                                                 kbCurr.nLast = kb.nLast;
2973                                         }
2974                                         else
2975                                         {
2976                                                 // start a new block
2977                                                 rgKeyBlocksNew.Add (kbCurr);
2978                                                 kbCurr = kb;
2979                                         }
2980                                 }
2981                                 rgKeyBlocksNew.Add (kbCurr);
2982                                 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2983                                         break;
2984                                 rgKeyBlocks = rgKeyBlocksNew;
2985                         }
2986
2987                         // initialize the key lists
2988                         foreach (KeyBlock kb in rgKeyBlocks)
2989                                 kb.rgKeys = new ArrayList ();
2990
2991                         // fill the key lists
2992                         int iBlockCurr = 0;
2993                         if (rgKeyBlocks.Count > 0) {
2994                                 kbCurr = (KeyBlock) rgKeyBlocks [0];
2995                                 foreach (object key in rgKeys)
2996                                 {
2997                                         bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
2998                                         if (fNextBlock)
2999                                                 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3000                                         kbCurr.rgKeys.Add (key);
3001                                 }
3002                         }
3003
3004                         // sort the blocks so we can tackle the largest ones first
3005                         rgKeyBlocks.Sort ();
3006
3007                         // okay now we can start...
3008                         ILGenerator ig = ec.ig;
3009                         Label lblEnd = ig.DefineLabel ();       // at the end ;-)
3010                         Label lblDefault = ig.DefineLabel ();
3011
3012                         Type typeKeys = null;
3013                         if (rgKeys.Length > 0)
3014                                 typeKeys = rgKeys [0].GetType ();       // used for conversions
3015
3016                         for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3017                         {
3018                                 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3019                                 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3020                                 if (kb.Length <= 2)
3021                                 {
3022                                         foreach (object key in kb.rgKeys)
3023                                         {
3024                                                 ig.Emit (OpCodes.Ldloc, val);
3025                                                 EmitObjectInteger (ig, key);
3026                                                 SwitchLabel sl = (SwitchLabel) Elements [key];
3027                                                 ig.Emit (OpCodes.Beq, sl.ILLabel);
3028                                         }
3029                                 }
3030                                 else
3031                                 {
3032                                         // TODO: if all the keys in the block are the same and there are
3033                                         //       no gaps/defaults then just use a range-check.
3034                                         if (SwitchType == TypeManager.int64_type ||
3035                                                 SwitchType == TypeManager.uint64_type)
3036                                         {
3037                                                 // TODO: optimize constant/I4 cases
3038
3039                                                 // check block range (could be > 2^31)
3040                                                 ig.Emit (OpCodes.Ldloc, val);
3041                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3042                                                 ig.Emit (OpCodes.Blt, lblDefault);
3043                                                 ig.Emit (OpCodes.Ldloc, val);
3044                                                 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3045                                                 ig.Emit (OpCodes.Bgt, lblDefault);
3046
3047                                                 // normalize range
3048                                                 ig.Emit (OpCodes.Ldloc, val);
3049                                                 if (kb.nFirst != 0)
3050                                                 {
3051                                                         EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3052                                                         ig.Emit (OpCodes.Sub);
3053                                                 }
3054                                                 ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
3055                                         }
3056                                         else
3057                                         {
3058                                                 // normalize range
3059                                                 ig.Emit (OpCodes.Ldloc, val);
3060                                                 int nFirst = (int) kb.nFirst;
3061                                                 if (nFirst > 0)
3062                                                 {
3063                                                         IntConstant.EmitInt (ig, nFirst);
3064                                                         ig.Emit (OpCodes.Sub);
3065                                                 }
3066                                                 else if (nFirst < 0)
3067                                                 {
3068                                                         IntConstant.EmitInt (ig, -nFirst);
3069                                                         ig.Emit (OpCodes.Add);
3070                                                 }
3071                                         }
3072
3073                                         // first, build the list of labels for the switch
3074                                         int iKey = 0;
3075                                         int cJumps = kb.Length;
3076                                         Label [] rgLabels = new Label [cJumps];
3077                                         for (int iJump = 0; iJump < cJumps; iJump++)
3078                                         {
3079                                                 object key = kb.rgKeys [iKey];
3080                                                 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3081                                                 {
3082                                                         SwitchLabel sl = (SwitchLabel) Elements [key];
3083                                                         rgLabels [iJump] = sl.ILLabel;
3084                                                         iKey++;
3085                                                 }
3086                                                 else
3087                                                         rgLabels [iJump] = lblDefault;
3088                                         }
3089                                         // emit the switch opcode
3090                                         ig.Emit (OpCodes.Switch, rgLabels);
3091                                 }
3092
3093                                 // mark the default for this block
3094                                 if (iBlock != 0)
3095                                         ig.MarkLabel (lblDefault);
3096                         }
3097
3098                         // TODO: find the default case and emit it here,
3099                         //       to prevent having to do the following jump.
3100                         //       make sure to mark other labels in the default section
3101
3102                         // the last default just goes to the end
3103                         ig.Emit (OpCodes.Br, lblDefault);
3104
3105                         // now emit the code for the sections
3106                         bool fFoundDefault = false;
3107                         bool fAllReturn = true;
3108                         foreach (SwitchSection ss in Sections)
3109                         {
3110                                 foreach (SwitchLabel sl in ss.Labels)
3111                                 {
3112                                         ig.MarkLabel (sl.ILLabel);
3113                                         ig.MarkLabel (sl.ILLabelCode);
3114                                         if (sl.Label == null)
3115                                         {
3116                                                 ig.MarkLabel (lblDefault);
3117                                                 fFoundDefault = true;
3118                                         }
3119                                 }
3120                                 fAllReturn &= ss.Block.Emit (ec);
3121                                 //ig.Emit (OpCodes.Br, lblEnd);
3122                         }
3123                         
3124                         if (!fFoundDefault) {
3125                                 ig.MarkLabel (lblDefault);
3126                                 fAllReturn = false;
3127                         }
3128                         ig.MarkLabel (lblEnd);
3129
3130                         return fAllReturn;
3131                 }
3132                 //
3133                 // This simple emit switch works, but does not take advantage of the
3134                 // `switch' opcode. 
3135                 // TODO: remove non-string logic from here
3136                 // TODO: binary search strings?
3137                 //
3138                 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3139                 {
3140                         ILGenerator ig = ec.ig;
3141                         Label end_of_switch = ig.DefineLabel ();
3142                         Label next_test = ig.DefineLabel ();
3143                         Label null_target = ig.DefineLabel ();
3144                         bool default_found = false;
3145                         bool first_test = true;
3146                         bool pending_goto_end = false;
3147                         bool all_return = true;
3148                         bool is_string = false;
3149                         bool null_found;
3150                         
3151                         //
3152                         // Special processing for strings: we cant compare
3153                         // against null.
3154                         //
3155                         if (SwitchType == TypeManager.string_type){
3156                                 ig.Emit (OpCodes.Ldloc, val);
3157                                 is_string = true;
3158                                 
3159                                 if (Elements.Contains (NullLiteral.Null)){
3160                                         ig.Emit (OpCodes.Brfalse, null_target);
3161                                 } else
3162                                         ig.Emit (OpCodes.Brfalse, default_target);
3163
3164                                 ig.Emit (OpCodes.Ldloc, val);
3165                                 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3166                                 ig.Emit (OpCodes.Stloc, val);
3167                         }
3168
3169                         SwitchSection last_section;
3170                         last_section = (SwitchSection) Sections [Sections.Count-1];
3171                         
3172                         foreach (SwitchSection ss in Sections){
3173                                 Label sec_begin = ig.DefineLabel ();
3174
3175                                 if (pending_goto_end)
3176                                         ig.Emit (OpCodes.Br, end_of_switch);
3177
3178                                 int label_count = ss.Labels.Count;
3179                                 null_found = false;
3180                                 foreach (SwitchLabel sl in ss.Labels){
3181                                         ig.MarkLabel (sl.ILLabel);
3182                                         
3183                                         if (!first_test){
3184                                                 ig.MarkLabel (next_test);
3185                                                 next_test = ig.DefineLabel ();
3186                                         }
3187                                         //
3188                                         // If we are the default target
3189                                         //
3190                                         if (sl.Label == null){
3191                                                 ig.MarkLabel (default_target);
3192                                                 default_found = true;
3193                                         } else {
3194                                                 object lit = sl.Converted;
3195
3196                                                 if (lit is NullLiteral){
3197                                                         null_found = true;
3198                                                         if (label_count == 1)
3199                                                                 ig.Emit (OpCodes.Br, next_test);
3200                                                         continue;
3201                                                                               
3202                                                 }
3203                                                 if (is_string){
3204                                                         StringConstant str = (StringConstant) lit;
3205
3206                                                         ig.Emit (OpCodes.Ldloc, val);
3207                                                         ig.Emit (OpCodes.Ldstr, str.Value);
3208                                                         if (label_count == 1)
3209                                                                 ig.Emit (OpCodes.Bne_Un, next_test);
3210                                                         else
3211                                                                 ig.Emit (OpCodes.Beq, sec_begin);
3212                                                 } else {
3213                                                         ig.Emit (OpCodes.Ldloc, val);
3214                                                         EmitObjectInteger (ig, lit);
3215                                                         ig.Emit (OpCodes.Ceq);
3216                                                         if (label_count == 1)
3217                                                                 ig.Emit (OpCodes.Brfalse, next_test);
3218                                                         else
3219                                                                 ig.Emit (OpCodes.Brtrue, sec_begin);
3220                                                 }
3221                                         }
3222                                 }
3223                                 if (label_count != 1 && ss != last_section)
3224                                         ig.Emit (OpCodes.Br, next_test);
3225                                 
3226                                 if (null_found)
3227                                         ig.MarkLabel (null_target);
3228                                 ig.MarkLabel (sec_begin);
3229                                 foreach (SwitchLabel sl in ss.Labels)
3230                                         ig.MarkLabel (sl.ILLabelCode);
3231                                 if (ss.Block.Emit (ec))
3232                                         pending_goto_end = false;
3233                                 else {
3234                                         all_return = false;
3235                                         pending_goto_end = true;
3236                                 }
3237                                 first_test = false;
3238                         }
3239                         if (!default_found){
3240                                 ig.MarkLabel (default_target);
3241                                 all_return = false;
3242                         }
3243                         ig.MarkLabel (next_test);
3244                         ig.MarkLabel (end_of_switch);
3245                         
3246                         return all_return;
3247                 }
3248
3249                 public override bool Resolve (EmitContext ec)
3250                 {
3251                         Expr = Expr.Resolve (ec);
3252                         if (Expr == null)
3253                                 return false;
3254
3255                         new_expr = SwitchGoverningType (ec, Expr.Type);
3256                         if (new_expr == null){
3257                                 Report.Error (151, loc, "An integer type or string was expected for switch");
3258                                 return false;
3259                         }
3260
3261                         // Validate switch.
3262                         SwitchType = new_expr.Type;
3263
3264                         if (!CheckSwitch (ec))
3265                                 return false;
3266
3267                         Switch old_switch = ec.Switch;
3268                         ec.Switch = this;
3269                         ec.Switch.SwitchType = SwitchType;
3270
3271                         ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3272
3273                         bool first = true;
3274                         foreach (SwitchSection ss in Sections){
3275                                 if (!first)
3276                                         ec.CurrentBranching.CreateSibling ();
3277                                 else
3278                                         first = false;
3279
3280                                 if (ss.Block.Resolve (ec) != true)
3281                                         return false;
3282                         }
3283
3284                         ec.EndFlowBranching ();
3285                         ec.Switch = old_switch;
3286
3287                         return true;
3288                 }
3289                 
3290                 public override bool Emit (EmitContext ec)
3291                 {
3292                         // Store variable for comparission purposes
3293                         LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3294                         new_expr.Emit (ec);
3295                         ec.ig.Emit (OpCodes.Stloc, value);
3296
3297                         ILGenerator ig = ec.ig;
3298
3299                         default_target = ig.DefineLabel ();
3300
3301                         //
3302                         // Setup the codegen context
3303                         //
3304                         Label old_end = ec.LoopEnd;
3305                         Switch old_switch = ec.Switch;
3306                         
3307                         ec.LoopEnd = ig.DefineLabel ();
3308                         ec.Switch = this;
3309
3310                         // Emit Code.
3311                         bool all_return;
3312                         if (SwitchType == TypeManager.string_type)
3313                                 all_return = SimpleSwitchEmit (ec, value);
3314                         else
3315                                 all_return = TableSwitchEmit (ec, value);
3316
3317                         // Restore context state. 
3318                         ig.MarkLabel (ec.LoopEnd);
3319
3320                         //
3321                         // Restore the previous context
3322                         //
3323                         ec.LoopEnd = old_end;
3324                         ec.Switch = old_switch;
3325                         
3326                         return all_return;
3327                 }
3328         }
3329
3330         public class Lock : Statement {
3331                 Expression expr;
3332                 Statement Statement;
3333                         
3334                 public Lock (Expression expr, Statement stmt, Location l)
3335                 {
3336                         this.expr = expr;
3337                         Statement = stmt;
3338                         loc = l;
3339                 }
3340
3341                 public override bool Resolve (EmitContext ec)
3342                 {
3343                         expr = expr.Resolve (ec);
3344                         return Statement.Resolve (ec) && expr != null;
3345                 }
3346                 
3347                 public override bool Emit (EmitContext ec)
3348                 {
3349                         Type type = expr.Type;
3350                         bool val;
3351                         
3352                         if (type.IsValueType){
3353                                 Report.Error (185, loc, "lock statement requires the expression to be " +
3354                                               " a reference type (type is: `" +
3355                                               TypeManager.CSharpName (type) + "'");
3356                                 return false;
3357                         }
3358
3359                         ILGenerator ig = ec.ig;
3360                         LocalBuilder temp = ig.DeclareLocal (type);
3361                                 
3362                         expr.Emit (ec);
3363                         ig.Emit (OpCodes.Dup);
3364                         ig.Emit (OpCodes.Stloc, temp);
3365                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3366
3367                         // try
3368                         Label end = ig.BeginExceptionBlock ();
3369                         bool old_in_try = ec.InTry;
3370                         ec.InTry = true;
3371                         Label finish = ig.DefineLabel ();
3372                         val = Statement.Emit (ec);
3373                         ec.InTry = old_in_try;
3374                         // ig.Emit (OpCodes.Leave, finish);
3375
3376                         ig.MarkLabel (finish);
3377                         
3378                         // finally
3379                         ig.BeginFinallyBlock ();
3380                         ig.Emit (OpCodes.Ldloc, temp);
3381                         ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3382                         ig.EndExceptionBlock ();
3383                         
3384                         return val;
3385                 }
3386         }
3387
3388         public class Unchecked : Statement {
3389                 public readonly Block Block;
3390                 
3391                 public Unchecked (Block b)
3392                 {
3393                         Block = b;
3394                 }
3395
3396                 public override bool Resolve (EmitContext ec)
3397                 {
3398                         return Block.Resolve (ec);
3399                 }
3400                 
3401                 public override bool Emit (EmitContext ec)
3402                 {
3403                         bool previous_state = ec.CheckState;
3404                         bool previous_state_const = ec.ConstantCheckState;
3405                         bool val;
3406                         
3407                         ec.CheckState = false;
3408                         ec.ConstantCheckState = false;
3409                         val = Block.Emit (ec);
3410                         ec.CheckState = previous_state;
3411                         ec.ConstantCheckState = previous_state_const;
3412
3413                         return val;
3414                 }
3415         }
3416
3417         public class Checked : Statement {
3418                 public readonly Block Block;
3419                 
3420                 public Checked (Block b)
3421                 {
3422                         Block = b;
3423                 }
3424
3425                 public override bool Resolve (EmitContext ec)
3426                 {
3427                         bool previous_state = ec.CheckState;
3428                         bool previous_state_const = ec.ConstantCheckState;
3429                         
3430                         ec.CheckState = true;
3431                         ec.ConstantCheckState = true;
3432                         bool ret = Block.Resolve (ec);
3433                         ec.CheckState = previous_state;
3434                         ec.ConstantCheckState = previous_state_const;
3435
3436                         return ret;
3437                 }
3438
3439                 public override bool Emit (EmitContext ec)
3440                 {
3441                         bool previous_state = ec.CheckState;
3442                         bool previous_state_const = ec.ConstantCheckState;
3443                         bool val;
3444                         
3445                         ec.CheckState = true;
3446                         ec.ConstantCheckState = true;
3447                         val = Block.Emit (ec);
3448                         ec.CheckState = previous_state;
3449                         ec.ConstantCheckState = previous_state_const;
3450
3451                         return val;
3452                 }
3453         }
3454
3455         public class Unsafe : Statement {
3456                 public readonly Block Block;
3457
3458                 public Unsafe (Block b)
3459                 {
3460                         Block = b;
3461                 }
3462
3463                 public override bool Resolve (EmitContext ec)
3464                 {
3465                         bool previous_state = ec.InUnsafe;
3466                         bool val;
3467                         
3468                         ec.InUnsafe = true;
3469                         val = Block.Resolve (ec);
3470                         ec.InUnsafe = previous_state;
3471
3472                         return val;
3473                 }
3474                 
3475                 public override bool Emit (EmitContext ec)
3476                 {
3477                         bool previous_state = ec.InUnsafe;
3478                         bool val;
3479                         
3480                         ec.InUnsafe = true;
3481                         val = Block.Emit (ec);
3482                         ec.InUnsafe = previous_state;
3483
3484                         return val;
3485                 }
3486         }
3487
3488         // 
3489         // Fixed statement
3490         //
3491         public class Fixed : Statement {
3492                 Expression type;
3493                 ArrayList declarators;
3494                 Statement statement;
3495                 Type expr_type;
3496                 FixedData[] data;
3497
3498                 struct FixedData {
3499                         public bool is_object;
3500                         public VariableInfo vi;
3501                         public Expression expr;
3502                         public Expression converted;
3503                 }                       
3504
3505                 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3506                 {
3507                         this.type = type;
3508                         declarators = decls;
3509                         statement = stmt;
3510                         loc = l;
3511                 }
3512
3513                 public override bool Resolve (EmitContext ec)
3514                 {
3515                         expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3516                         if (expr_type == null)
3517                                 return false;
3518
3519                         data = new FixedData [declarators.Count];
3520
3521                         int i = 0;
3522                         foreach (Pair p in declarators){
3523                                 VariableInfo vi = (VariableInfo) p.First;
3524                                 Expression e = (Expression) p.Second;
3525
3526                                 vi.Number = -1;
3527
3528                                 //
3529                                 // The rules for the possible declarators are pretty wise,
3530                                 // but the production on the grammar is more concise.
3531                                 //
3532                                 // So we have to enforce these rules here.
3533                                 //
3534                                 // We do not resolve before doing the case 1 test,
3535                                 // because the grammar is explicit in that the token &
3536                                 // is present, so we need to test for this particular case.
3537                                 //
3538
3539                                 //
3540                                 // Case 1: & object.
3541                                 //
3542                                 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3543                                         Expression child = ((Unary) e).Expr;
3544
3545                                         vi.MakePinned ();
3546                                         if (child is ParameterReference || child is LocalVariableReference){
3547                                                 Report.Error (
3548                                                         213, loc, 
3549                                                         "No need to use fixed statement for parameters or " +
3550                                                         "local variable declarations (address is already " +
3551                                                         "fixed)");
3552                                                 return false;
3553                                         }
3554                                         
3555                                         e = e.Resolve (ec);
3556                                         if (e == null)
3557                                                 return false;
3558
3559                                         child = ((Unary) e).Expr;
3560                                         
3561                                         if (!TypeManager.VerifyUnManaged (child.Type, loc))
3562                                                 return false;
3563
3564                                         data [i].is_object = true;
3565                                         data [i].expr = e;
3566                                         data [i].converted = null;
3567                                         data [i].vi = vi;
3568                                         i++;
3569
3570                                         continue;
3571                                 }
3572
3573                                 e = e.Resolve (ec);
3574                                 if (e == null)
3575                                         return false;
3576
3577                                 //
3578                                 // Case 2: Array
3579                                 //
3580                                 if (e.Type.IsArray){
3581                                         Type array_type = e.Type.GetElementType ();
3582                                         
3583                                         vi.MakePinned ();
3584                                         //
3585                                         // Provided that array_type is unmanaged,
3586                                         //
3587                                         if (!TypeManager.VerifyUnManaged (array_type, loc))
3588                                                 return false;
3589
3590                                         //
3591                                         // and T* is implicitly convertible to the
3592                                         // pointer type given in the fixed statement.
3593                                         //
3594                                         ArrayPtr array_ptr = new ArrayPtr (e, loc);
3595                                         
3596                                         Expression converted = Expression.ConvertImplicitRequired (
3597                                                 ec, array_ptr, vi.VariableType, loc);
3598                                         if (converted == null)
3599                                                 return false;
3600
3601                                         data [i].is_object = false;
3602                                         data [i].expr = e;
3603                                         data [i].converted = converted;
3604                                         data [i].vi = vi;
3605                                         i++;
3606
3607                                         continue;
3608                                 }
3609
3610                                 //
3611                                 // Case 3: string
3612                                 //
3613                                 if (e.Type == TypeManager.string_type){
3614                                         data [i].is_object = false;
3615                                         data [i].expr = e;
3616                                         data [i].converted = null;
3617                                         data [i].vi = vi;
3618                                         i++;
3619                                 }
3620                         }
3621
3622                         return statement.Resolve (ec);
3623                 }
3624                 
3625                 public override bool Emit (EmitContext ec)
3626                 {
3627                         ILGenerator ig = ec.ig;
3628
3629                         bool is_ret = false;
3630
3631                         for (int i = 0; i < data.Length; i++) {
3632                                 VariableInfo vi = data [i].vi;
3633
3634                                 //
3635                                 // Case 1: & object.
3636                                 //
3637                                 if (data [i].is_object) {
3638                                         //
3639                                         // Store pointer in pinned location
3640                                         //
3641                                         data [i].expr.Emit (ec);
3642                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3643
3644                                         is_ret = statement.Emit (ec);
3645
3646                                         // Clear the pinned variable.
3647                                         ig.Emit (OpCodes.Ldc_I4_0);
3648                                         ig.Emit (OpCodes.Conv_U);
3649                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3650
3651                                         continue;
3652                                 }
3653
3654                                 //
3655                                 // Case 2: Array
3656                                 //
3657                                 if (data [i].expr.Type.IsArray){
3658                                         //
3659                                         // Store pointer in pinned location
3660                                         //
3661                                         data [i].converted.Emit (ec);
3662                                         
3663                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3664
3665                                         is_ret = statement.Emit (ec);
3666                                         
3667                                         // Clear the pinned variable.
3668                                         ig.Emit (OpCodes.Ldc_I4_0);
3669                                         ig.Emit (OpCodes.Conv_U);
3670                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3671
3672                                         continue;
3673                                 }
3674
3675                                 //
3676                                 // Case 3: string
3677                                 //
3678                                 if (data [i].expr.Type == TypeManager.string_type){
3679                                         LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3680                                         TypeManager.MakePinned (pinned_string);
3681                                         
3682                                         data [i].expr.Emit (ec);
3683                                         ig.Emit (OpCodes.Stloc, pinned_string);
3684
3685                                         Expression sptr = new StringPtr (pinned_string, loc);
3686                                         Expression converted = Expression.ConvertImplicitRequired (
3687                                                 ec, sptr, vi.VariableType, loc);
3688                                         
3689                                         if (converted == null)
3690                                                 continue;
3691
3692                                         converted.Emit (ec);
3693                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3694                                         
3695                                         is_ret = statement.Emit (ec);
3696
3697                                         // Clear the pinned variable
3698                                         ig.Emit (OpCodes.Ldnull);
3699                                         ig.Emit (OpCodes.Stloc, pinned_string);
3700                                 }
3701                         }
3702
3703                         return is_ret;
3704                 }
3705         }
3706         
3707         public class Catch {
3708                 public readonly string Name;
3709                 public readonly Block  Block;
3710                 public readonly Location Location;
3711
3712                 Expression type;
3713                 
3714                 public Catch (Expression type, string name, Block block, Location l)
3715                 {
3716                         this.type = type;
3717                         Name = name;
3718                         Block = block;
3719                         Location = l;
3720                 }
3721
3722                 public Type CatchType {
3723                         get {
3724                                 if (type == null)
3725                                         throw new InvalidOperationException ();
3726
3727                                 return type.Type;
3728                         }
3729                 }
3730
3731                 public bool IsGeneral {
3732                         get {
3733                                 return type == null;
3734                         }
3735                 }
3736
3737                 public bool Resolve (EmitContext ec)
3738                 {
3739                         if (type != null) {
3740                                 type = type.DoResolve (ec);
3741                                 if (type == null)
3742                                         return false;
3743
3744                                 Type t = type.Type;
3745                                 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
3746                                         Report.Error (155, Location,
3747                                                       "The type caught or thrown must be derived " +
3748                                                       "from System.Exception");
3749                                         return false;
3750                                 }
3751                         }
3752
3753                         if (!Block.Resolve (ec))
3754                                 return false;
3755
3756                         return true;
3757                 }
3758         }
3759
3760         public class Try : Statement {
3761                 public readonly Block Fini, Block;
3762                 public readonly ArrayList Specific;
3763                 public readonly Catch General;
3764                 
3765                 //
3766                 // specific, general and fini might all be null.
3767                 //
3768                 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3769                 {
3770                         if (specific == null && general == null){
3771                                 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3772                         }
3773                         
3774                         this.Block = block;
3775                         this.Specific = specific;
3776                         this.General = general;
3777                         this.Fini = fini;
3778                         loc = l;
3779                 }
3780
3781                 public override bool Resolve (EmitContext ec)
3782                 {
3783                         bool ok = true;
3784                         
3785                         ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
3786
3787                         Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3788
3789                         bool old_in_try = ec.InTry;
3790                         ec.InTry = true;
3791
3792                         if (!Block.Resolve (ec))
3793                                 ok = false;
3794
3795                         ec.InTry = old_in_try;
3796
3797                         FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3798
3799                         Report.Debug (1, "START OF CATCH BLOCKS", vector);
3800
3801                         foreach (Catch c in Specific){
3802                                 ec.CurrentBranching.CreateSibling ();
3803                                 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3804
3805                                 if (c.Name != null) {
3806                                         VariableInfo vi = c.Block.GetVariableInfo (c.Name);
3807                                         if (vi == null)
3808                                                 throw new Exception ();
3809
3810                                         vi.Number = -1;
3811                                 }
3812
3813                                 bool old_in_catch = ec.InCatch;
3814                                 ec.InCatch = true;
3815
3816                                 if (!c.Resolve (ec))
3817                                         ok = false;
3818
3819                                 ec.InCatch = old_in_catch;
3820
3821                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3822
3823                                 if ((current.Returns == FlowReturns.NEVER) ||
3824                                     (current.Returns == FlowReturns.SOMETIMES)) {
3825                                         vector.AndLocals (current);
3826                                 }
3827                         }
3828
3829                         if (General != null){
3830                                 ec.CurrentBranching.CreateSibling ();
3831                                 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3832
3833                                 bool old_in_catch = ec.InCatch;
3834                                 ec.InCatch = true;
3835
3836                                 if (!General.Resolve (ec))
3837                                         ok = false;
3838
3839                                 ec.InCatch = old_in_catch;
3840
3841                                 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3842
3843                                 if ((current.Returns == FlowReturns.NEVER) ||
3844                                     (current.Returns == FlowReturns.SOMETIMES)) {
3845                                         vector.AndLocals (current);
3846                                 }
3847                         }
3848
3849                         ec.CurrentBranching.CreateSiblingForFinally ();
3850                         Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3851
3852                         if (Fini != null) {
3853                                 bool old_in_finally = ec.InFinally;
3854                                 ec.InFinally = true;
3855
3856                                 if (!Fini.Resolve (ec))
3857                                         ok = false;
3858
3859                                 ec.InFinally = old_in_finally;
3860                         }
3861
3862                         FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3863
3864                         FlowReturns returns = ec.EndFlowBranching ();
3865
3866                         Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3867
3868                         if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3869                                 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3870                         }
3871
3872                         ec.CurrentBranching.CurrentUsageVector.Or (vector);
3873
3874                         Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3875
3876                         return ok;
3877                 }
3878                 
3879                 public override bool Emit (EmitContext ec)
3880                 {
3881                         ILGenerator ig = ec.ig;
3882                         Label end;
3883                         Label finish = ig.DefineLabel ();;
3884                         bool returns;
3885
3886                         ec.TryCatchLevel++;
3887                         end = ig.BeginExceptionBlock ();
3888                         bool old_in_try = ec.InTry;
3889                         ec.InTry = true;
3890                         returns = Block.Emit (ec);
3891                         ec.InTry = old_in_try;
3892
3893                         //
3894                         // System.Reflection.Emit provides this automatically:
3895                         // ig.Emit (OpCodes.Leave, finish);
3896
3897                         bool old_in_catch = ec.InCatch;
3898                         ec.InCatch = true;
3899                         DeclSpace ds = ec.DeclSpace;
3900
3901                         foreach (Catch c in Specific){
3902                                 VariableInfo vi;
3903                                 
3904                                 ig.BeginCatchBlock (c.CatchType);
3905
3906                                 if (c.Name != null){
3907                                         vi = c.Block.GetVariableInfo (c.Name);
3908                                         if (vi == null)
3909                                                 throw new Exception ("Variable does not exist in this block");
3910
3911                                         ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3912                                 } else
3913                                         ig.Emit (OpCodes.Pop);
3914                                 
3915                                 if (!c.Block.Emit (ec))
3916                                         returns = false;
3917                         }
3918
3919                         if (General != null){
3920                                 ig.BeginCatchBlock (TypeManager.object_type);
3921                                 ig.Emit (OpCodes.Pop);
3922                                 if (!General.Block.Emit (ec))
3923                                         returns = false;
3924                         }
3925                         ec.InCatch = old_in_catch;
3926
3927                         ig.MarkLabel (finish);
3928                         if (Fini != null){
3929                                 ig.BeginFinallyBlock ();
3930                                 bool old_in_finally = ec.InFinally;
3931                                 ec.InFinally = true;
3932                                 Fini.Emit (ec);
3933                                 ec.InFinally = old_in_finally;
3934                         }
3935                         
3936                         ig.EndExceptionBlock ();
3937                         ec.TryCatchLevel--;
3938
3939                         if (!returns || ec.InTry || ec.InCatch)
3940                                 return returns;
3941
3942                         // Unfortunately, System.Reflection.Emit automatically emits a leave
3943                         // to the end of the finally block.  This is a problem if `returns'
3944                         // is true since we may jump to a point after the end of the method.
3945                         // As a workaround, emit an explicit ret here.
3946
3947                         if (ec.ReturnType != null)
3948                                 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
3949                         ec.ig.Emit (OpCodes.Ret);
3950
3951                         return true;
3952                 }
3953         }
3954
3955         //
3956         // FIXME: We still do not support the expression variant of the using
3957         // statement.
3958         //
3959         public class Using : Statement {
3960                 object expression_or_block;
3961                 Statement Statement;
3962                 ArrayList var_list;
3963                 Expression expr;
3964                 Type expr_type;
3965                 Expression conv;
3966                 Expression [] converted_vars;
3967                 ExpressionStatement [] assign;
3968                 
3969                 public Using (object expression_or_block, Statement stmt, Location l)
3970                 {
3971                         this.expression_or_block = expression_or_block;
3972                         Statement = stmt;
3973                         loc = l;
3974                 }
3975
3976                 //
3977                 // Resolves for the case of using using a local variable declaration.
3978                 //
3979                 bool ResolveLocalVariableDecls (EmitContext ec)
3980                 {
3981                         bool need_conv = false;
3982                         expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3983                         int i = 0;
3984
3985                         if (expr_type == null)
3986                                 return false;
3987
3988                         //
3989                         // The type must be an IDisposable or an implicit conversion
3990                         // must exist.
3991                         //
3992                         converted_vars = new Expression [var_list.Count];
3993                         assign = new ExpressionStatement [var_list.Count];
3994                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3995                                 foreach (DictionaryEntry e in var_list){
3996                                         Expression var = (Expression) e.Key;
3997
3998                                         var = var.ResolveLValue (ec, new EmptyExpression ());
3999                                         if (var == null)
4000                                                 return false;
4001                                         
4002                                         converted_vars [i] = Expression.ConvertImplicit (
4003                                                 ec, var, TypeManager.idisposable_type, loc);
4004
4005                                         if (converted_vars [i] == null)
4006                                                 return false;
4007                                         i++;
4008                                 }
4009                                 need_conv = true;
4010                         }
4011
4012                         i = 0;
4013                         foreach (DictionaryEntry e in var_list){
4014                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4015                                 Expression new_expr = (Expression) e.Value;
4016                                 Expression a;
4017
4018                                 a = new Assign (var, new_expr, loc);
4019                                 a = a.Resolve (ec);
4020                                 if (a == null)
4021                                         return false;
4022
4023                                 if (!need_conv)
4024                                         converted_vars [i] = var;
4025                                 assign [i] = (ExpressionStatement) a;
4026                                 i++;
4027                         }
4028
4029                         return true;
4030                 }
4031
4032                 bool ResolveExpression (EmitContext ec)
4033                 {
4034                         if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4035                                 conv = Expression.ConvertImplicit (
4036                                         ec, expr, TypeManager.idisposable_type, loc);
4037
4038                                 if (conv == null)
4039                                         return false;
4040                         }
4041
4042                         return true;
4043                 }
4044                 
4045                 //
4046                 // Emits the code for the case of using using a local variable declaration.
4047                 //
4048                 bool EmitLocalVariableDecls (EmitContext ec)
4049                 {
4050                         ILGenerator ig = ec.ig;
4051                         int i = 0;
4052
4053                         bool old_in_try = ec.InTry;
4054                         ec.InTry = true;
4055                         for (i = 0; i < assign.Length; i++) {
4056                                 assign [i].EmitStatement (ec);
4057                                 
4058                                 ig.BeginExceptionBlock ();
4059                         }
4060                         Statement.Emit (ec);
4061                         ec.InTry = old_in_try;
4062
4063                         bool old_in_finally = ec.InFinally;
4064                         ec.InFinally = true;
4065                         var_list.Reverse ();
4066                         foreach (DictionaryEntry e in var_list){
4067                                 LocalVariableReference var = (LocalVariableReference) e.Key;
4068                                 Label skip = ig.DefineLabel ();
4069                                 i--;
4070                                 
4071                                 ig.BeginFinallyBlock ();
4072                                 
4073                                 var.Emit (ec);
4074                                 ig.Emit (OpCodes.Brfalse, skip);
4075                                 converted_vars [i].Emit (ec);
4076                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4077                                 ig.MarkLabel (skip);
4078                                 ig.EndExceptionBlock ();
4079                         }
4080                         ec.InFinally = old_in_finally;
4081
4082                         return false;
4083                 }
4084
4085                 bool EmitExpression (EmitContext ec)
4086                 {
4087                         //
4088                         // Make a copy of the expression and operate on that.
4089                         //
4090                         ILGenerator ig = ec.ig;
4091                         LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4092                         if (conv != null)
4093                                 conv.Emit (ec);
4094                         else
4095                                 expr.Emit (ec);
4096                         ig.Emit (OpCodes.Stloc, local_copy);
4097
4098                         bool old_in_try = ec.InTry;
4099                         ec.InTry = true;
4100                         ig.BeginExceptionBlock ();
4101                         Statement.Emit (ec);
4102                         ec.InTry = old_in_try;
4103                         
4104                         Label skip = ig.DefineLabel ();
4105                         bool old_in_finally = ec.InFinally;
4106                         ig.BeginFinallyBlock ();
4107                         ig.Emit (OpCodes.Ldloc, local_copy);
4108                         ig.Emit (OpCodes.Brfalse, skip);
4109                         ig.Emit (OpCodes.Ldloc, local_copy);
4110                         ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4111                         ig.MarkLabel (skip);
4112                         ec.InFinally = old_in_finally;
4113                         ig.EndExceptionBlock ();
4114
4115                         return false;
4116                 }
4117                 
4118                 public override bool Resolve (EmitContext ec)
4119                 {
4120                         if (expression_or_block is DictionaryEntry){
4121                                 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4122                                 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4123
4124                                 if (!ResolveLocalVariableDecls (ec))
4125                                         return false;
4126
4127                         } else if (expression_or_block is Expression){
4128                                 expr = (Expression) expression_or_block;
4129
4130                                 expr = expr.Resolve (ec);
4131                                 if (expr == null)
4132                                         return false;
4133
4134                                 expr_type = expr.Type;
4135
4136                                 if (!ResolveExpression (ec))
4137                                         return false;
4138                         }                       
4139
4140                         return Statement.Resolve (ec);
4141                 }
4142                 
4143                 public override bool Emit (EmitContext ec)
4144                 {
4145                         if (expression_or_block is DictionaryEntry)
4146                                 return EmitLocalVariableDecls (ec);
4147                         else if (expression_or_block is Expression)
4148                                 return EmitExpression (ec);
4149
4150                         return false;
4151                 }
4152         }
4153
4154         /// <summary>
4155         ///   Implementation of the foreach C# statement
4156         /// </summary>
4157         public class Foreach : Statement {
4158                 Expression type;
4159                 LocalVariableReference variable;
4160                 Expression expr;
4161                 Statement statement;
4162                 ForeachHelperMethods hm;
4163                 Expression empty, conv;
4164                 Type array_type, element_type;
4165                 Type var_type;
4166                 
4167                 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4168                                 Statement stmt, Location l)
4169                 {
4170                         this.type = type;
4171                         this.variable = var;
4172                         this.expr = expr;
4173                         statement = stmt;
4174                         loc = l;
4175                 }
4176                 
4177                 public override bool Resolve (EmitContext ec)
4178                 {
4179                         expr = expr.Resolve (ec);
4180                         if (expr == null)
4181                                 return false;
4182
4183                         var_type = ec.DeclSpace.ResolveType (type, false, loc);
4184                         if (var_type == null)
4185                                 return false;
4186                         
4187                         //
4188                         // We need an instance variable.  Not sure this is the best
4189                         // way of doing this.
4190                         //
4191                         // FIXME: When we implement propertyaccess, will those turn
4192                         // out to return values in ExprClass?  I think they should.
4193                         //
4194                         if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4195                               expr.eclass == ExprClass.PropertyAccess)){
4196                                 error1579 (expr.Type);
4197                                 return false;
4198                         }
4199
4200                         if (expr.Type.IsArray) {
4201                                 array_type = expr.Type;
4202                                 element_type = array_type.GetElementType ();
4203
4204                                 empty = new EmptyExpression (element_type);
4205                         } else {
4206                                 hm = ProbeCollectionType (ec, expr.Type);
4207                                 if (hm == null){
4208                                         error1579 (expr.Type);
4209                                         return false;
4210                                 }
4211
4212                                 array_type = expr.Type;
4213                                 element_type = hm.element_type;
4214
4215                                 empty = new EmptyExpression (hm.element_type);
4216                         }
4217
4218                         //
4219                         // FIXME: maybe we can apply the same trick we do in the
4220                         // array handling to avoid creating empty and conv in some cases.
4221                         //
4222                         // Although it is not as important in this case, as the type
4223                         // will not likely be object (what the enumerator will return).
4224                         //
4225                         conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4226                         if (conv == null)
4227                                 return false;
4228
4229                         if (variable.ResolveLValue (ec, empty) == null)
4230                                 return false;
4231
4232                         if (!statement.Resolve (ec))
4233                                 return false;
4234
4235                         return true;
4236                 }
4237                 
4238                 //
4239                 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4240                 //
4241                 static MethodInfo FetchMethodMoveNext (Type t)
4242                 {
4243                         MemberInfo [] move_next_list;
4244                         
4245                         move_next_list = TypeContainer.FindMembers (
4246                                 t, MemberTypes.Method,
4247                                 BindingFlags.Public | BindingFlags.Instance,
4248                                 Type.FilterName, "MoveNext");
4249                         if (move_next_list == null || move_next_list.Length == 0)
4250                                 return null;
4251
4252                         foreach (MemberInfo m in move_next_list){
4253                                 MethodInfo mi = (MethodInfo) m;
4254                                 Type [] args;
4255                                 
4256                                 args = TypeManager.GetArgumentTypes (mi);
4257                                 if (args != null && args.Length == 0){
4258                                         if (mi.ReturnType == TypeManager.bool_type)
4259                                                 return mi;
4260                                 }
4261                         }
4262                         return null;
4263                 }
4264                 
4265                 //
4266                 // Retrieves a `public T get_Current ()' method from the Type `t'
4267                 //
4268                 static MethodInfo FetchMethodGetCurrent (Type t)
4269                 {
4270                         MemberInfo [] move_next_list;
4271                         
4272                         move_next_list = TypeContainer.FindMembers (
4273                                 t, MemberTypes.Method,
4274                                 BindingFlags.Public | BindingFlags.Instance,
4275                                 Type.FilterName, "get_Current");
4276                         if (move_next_list == null || move_next_list.Length == 0)
4277                                 return null;
4278
4279                         foreach (MemberInfo m in move_next_list){
4280                                 MethodInfo mi = (MethodInfo) m;
4281                                 Type [] args;
4282
4283                                 args = TypeManager.GetArgumentTypes (mi);
4284                                 if (args != null && args.Length == 0)
4285                                         return mi;
4286                         }
4287                         return null;
4288                 }
4289
4290                 // 
4291                 // This struct records the helper methods used by the Foreach construct
4292                 //
4293                 class ForeachHelperMethods {
4294                         public EmitContext ec;
4295                         public MethodInfo get_enumerator;
4296                         public MethodInfo move_next;
4297                         public MethodInfo get_current;
4298                         public Type element_type;
4299                         public Type enumerator_type;
4300                         public bool is_disposable;
4301
4302                         public ForeachHelperMethods (EmitContext ec)
4303                         {
4304                                 this.ec = ec;
4305                                 this.element_type = TypeManager.object_type;
4306                                 this.enumerator_type = TypeManager.ienumerator_type;
4307                                 this.is_disposable = true;
4308                         }
4309                 }
4310                 
4311                 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4312                 {
4313                         if (m == null)
4314                                 return false;
4315                         
4316                         if (!(m is MethodInfo))
4317                                 return false;
4318                         
4319                         if (m.Name != "GetEnumerator")
4320                                 return false;
4321
4322                         MethodInfo mi = (MethodInfo) m;
4323                         Type [] args = TypeManager.GetArgumentTypes (mi);
4324                         if (args != null){
4325                                 if (args.Length != 0)
4326                                         return false;
4327                         }
4328                         ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4329                         EmitContext ec = hm.ec;
4330
4331                         //
4332                         // Check whether GetEnumerator is accessible to us
4333                         //
4334                         MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4335
4336                         Type declaring = mi.DeclaringType;
4337                         if (prot == MethodAttributes.Private){
4338                                 if (declaring != ec.ContainerType)
4339                                         return false;
4340                         } else if (prot == MethodAttributes.FamANDAssem){
4341                                 // If from a different assembly, false
4342                                 if (!(mi is MethodBuilder))
4343                                         return false;
4344                                 //
4345                                 // Are we being invoked from the same class, or from a derived method?
4346                                 //
4347                                 if (ec.ContainerType != declaring){
4348                                         if (!ec.ContainerType.IsSubclassOf (declaring))
4349                                                 return false;
4350                                 }
4351                         } else if (prot == MethodAttributes.FamORAssem){
4352                                 if (!(mi is MethodBuilder ||
4353                                       ec.ContainerType == declaring ||
4354                                       ec.ContainerType.IsSubclassOf (declaring)))
4355                                         return false;
4356                         } if (prot == MethodAttributes.Family){
4357                                 if (!(ec.ContainerType == declaring ||
4358                                       ec.ContainerType.IsSubclassOf (declaring)))
4359                                         return false;
4360                         }
4361
4362                         //
4363                         // Ok, we can access it, now make sure that we can do something
4364                         // with this `GetEnumerator'
4365                         //
4366
4367                         if (mi.ReturnType == TypeManager.ienumerator_type ||
4368                             TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4369                             (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4370                                 hm.move_next = TypeManager.bool_movenext_void;
4371                                 hm.get_current = TypeManager.object_getcurrent_void;
4372                                 return true;
4373                         }
4374
4375                         //
4376                         // Ok, so they dont return an IEnumerable, we will have to
4377                         // find if they support the GetEnumerator pattern.
4378                         //
4379                         Type return_type = mi.ReturnType;
4380
4381                         hm.move_next = FetchMethodMoveNext (return_type);
4382                         if (hm.move_next == null)
4383                                 return false;
4384                         hm.get_current = FetchMethodGetCurrent (return_type);
4385                         if (hm.get_current == null)
4386                                 return false;
4387
4388                         hm.element_type = hm.get_current.ReturnType;
4389                         hm.enumerator_type = return_type;
4390                         hm.is_disposable = TypeManager.ImplementsInterface (
4391                                 hm.enumerator_type, TypeManager.idisposable_type);
4392
4393                         return true;
4394                 }
4395                 
4396                 /// <summary>
4397                 ///   This filter is used to find the GetEnumerator method
4398                 ///   on which IEnumerator operates
4399                 /// </summary>
4400                 static MemberFilter FilterEnumerator;
4401                 
4402                 static Foreach ()
4403                 {
4404                         FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4405                 }
4406
4407                 void error1579 (Type t)
4408                 {
4409                         Report.Error (1579, loc,
4410                                       "foreach statement cannot operate on variables of type `" +
4411                                       t.FullName + "' because that class does not provide a " +
4412                                       " GetEnumerator method or it is inaccessible");
4413                 }
4414
4415                 static bool TryType (Type t, ForeachHelperMethods hm)
4416                 {
4417                         MemberInfo [] mi;
4418                         
4419                         mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4420                                                         BindingFlags.Public | BindingFlags.NonPublic |
4421                                                         BindingFlags.Instance,
4422                                                         FilterEnumerator, hm);
4423
4424                         if (mi == null || mi.Length == 0)
4425                                 return false;
4426
4427                         hm.get_enumerator = (MethodInfo) mi [0];
4428                         return true;    
4429                 }
4430                 
4431                 //
4432                 // Looks for a usable GetEnumerator in the Type, and if found returns
4433                 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4434                 //
4435                 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4436                 {
4437                         ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4438
4439                         if (TryType (t, hm))
4440                                 return hm;
4441
4442                         //
4443                         // Now try to find the method in the interfaces
4444                         //
4445                         while (t != null){
4446                                 Type [] ifaces = t.GetInterfaces ();
4447
4448                                 foreach (Type i in ifaces){
4449                                         if (TryType (i, hm))
4450                                                 return hm;
4451                                 }
4452                                 
4453                                 //
4454                                 // Since TypeBuilder.GetInterfaces only returns the interface
4455                                 // types for this type, we have to keep looping, but once
4456                                 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4457                                 // done, because it returns all the types
4458                                 //
4459                                 if ((t is TypeBuilder))
4460                                         t = t.BaseType;
4461                                 else
4462                                         break;
4463                         } 
4464
4465                         return null;
4466                 }
4467
4468                 //
4469                 // FIXME: possible optimization.
4470                 // We might be able to avoid creating `empty' if the type is the sam
4471                 //
4472                 bool EmitCollectionForeach (EmitContext ec)
4473                 {
4474                         ILGenerator ig = ec.ig;
4475                         LocalBuilder enumerator, disposable;
4476
4477                         enumerator = ig.DeclareLocal (hm.enumerator_type);
4478                         if (hm.is_disposable)
4479                                 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4480                         else
4481                                 disposable = null;
4482                         
4483                         //
4484                         // Instantiate the enumerator
4485                         //
4486                         if (expr.Type.IsValueType){
4487                                 if (expr is IMemoryLocation){
4488                                         IMemoryLocation ml = (IMemoryLocation) expr;
4489
4490                                         ml.AddressOf (ec, AddressOp.Load);
4491                                 } else
4492                                         throw new Exception ("Expr " + expr + " of type " + expr.Type +
4493                                                              " does not implement IMemoryLocation");
4494                                 ig.Emit (OpCodes.Call, hm.get_enumerator);
4495                         } else {
4496                                 expr.Emit (ec);
4497                                 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4498                         }
4499                         ig.Emit (OpCodes.Stloc, enumerator);
4500
4501                         //
4502                         // Protect the code in a try/finalize block, so that
4503                         // if the beast implement IDisposable, we get rid of it
4504                         //
4505                         Label l;
4506                         bool old_in_try = ec.InTry;
4507
4508                         if (hm.is_disposable) {
4509                                 l = ig.BeginExceptionBlock ();
4510                                 ec.InTry = true;
4511                         }
4512                         
4513                         Label end_try = ig.DefineLabel ();
4514                         
4515                         ig.MarkLabel (ec.LoopBegin);
4516                         ig.Emit (OpCodes.Ldloc, enumerator);
4517                         ig.Emit (OpCodes.Callvirt, hm.move_next);
4518                         ig.Emit (OpCodes.Brfalse, end_try);
4519                         ig.Emit (OpCodes.Ldloc, enumerator);
4520                         ig.Emit (OpCodes.Callvirt, hm.get_current);
4521                         variable.EmitAssign (ec, conv);
4522                         statement.Emit (ec);
4523                         ig.Emit (OpCodes.Br, ec.LoopBegin);
4524                         ig.MarkLabel (end_try);
4525                         ec.InTry = old_in_try;
4526                         
4527                         // The runtime provides this for us.
4528                         // ig.Emit (OpCodes.Leave, end);
4529
4530                         //
4531                         // Now the finally block
4532                         //
4533                         if (hm.is_disposable) {
4534                                 Label end_finally = ig.DefineLabel ();
4535                                 bool old_in_finally = ec.InFinally;
4536                                 ec.InFinally = true;
4537                                 ig.BeginFinallyBlock ();
4538                         
4539                                 ig.Emit (OpCodes.Ldloc, enumerator);
4540                                 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4541                                 ig.Emit (OpCodes.Stloc, disposable);
4542                                 ig.Emit (OpCodes.Ldloc, disposable);
4543                                 ig.Emit (OpCodes.Brfalse, end_finally);
4544                                 ig.Emit (OpCodes.Ldloc, disposable);
4545                                 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4546                                 ig.MarkLabel (end_finally);
4547                                 ec.InFinally = old_in_finally;
4548
4549                                 // The runtime generates this anyways.
4550                                 // ig.Emit (OpCodes.Endfinally);
4551
4552                                 ig.EndExceptionBlock ();
4553                         }
4554
4555                         ig.MarkLabel (ec.LoopEnd);
4556                         return false;
4557                 }
4558
4559                 //
4560                 // FIXME: possible optimization.
4561                 // We might be able to avoid creating `empty' if the type is the sam
4562                 //
4563                 bool EmitArrayForeach (EmitContext ec)
4564                 {
4565                         int rank = array_type.GetArrayRank ();
4566                         ILGenerator ig = ec.ig;
4567
4568                         LocalBuilder copy = ig.DeclareLocal (array_type);
4569                         
4570                         //
4571                         // Make our copy of the array
4572                         //
4573                         expr.Emit (ec);
4574                         ig.Emit (OpCodes.Stloc, copy);
4575                         
4576                         if (rank == 1){
4577                                 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4578
4579                                 Label loop, test;
4580                                 
4581                                 ig.Emit (OpCodes.Ldc_I4_0);
4582                                 ig.Emit (OpCodes.Stloc, counter);
4583                                 test = ig.DefineLabel ();
4584                                 ig.Emit (OpCodes.Br, test);
4585
4586                                 loop = ig.DefineLabel ();
4587                                 ig.MarkLabel (loop);
4588
4589                                 ig.Emit (OpCodes.Ldloc, copy);
4590                                 ig.Emit (OpCodes.Ldloc, counter);
4591                                 ArrayAccess.EmitLoadOpcode (ig, var_type);
4592
4593                                 variable.EmitAssign (ec, conv);
4594
4595                                 statement.Emit (ec);
4596
4597                                 ig.MarkLabel (ec.LoopBegin);
4598                                 ig.Emit (OpCodes.Ldloc, counter);
4599                                 ig.Emit (OpCodes.Ldc_I4_1);
4600                                 ig.Emit (OpCodes.Add);
4601                                 ig.Emit (OpCodes.Stloc, counter);
4602
4603                                 ig.MarkLabel (test);
4604                                 ig.Emit (OpCodes.Ldloc, counter);
4605                                 ig.Emit (OpCodes.Ldloc, copy);
4606                                 ig.Emit (OpCodes.Ldlen);
4607                                 ig.Emit (OpCodes.Conv_I4);
4608                                 ig.Emit (OpCodes.Blt, loop);
4609                         } else {
4610                                 LocalBuilder [] dim_len   = new LocalBuilder [rank];
4611                                 LocalBuilder [] dim_count = new LocalBuilder [rank];
4612                                 Label [] loop = new Label [rank];
4613                                 Label [] test = new Label [rank];
4614                                 int dim;
4615                                 
4616                                 for (dim = 0; dim < rank; dim++){
4617                                         dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
4618                                         dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
4619                                         test [dim] = ig.DefineLabel ();
4620                                         loop [dim] = ig.DefineLabel ();
4621                                 }
4622                                         
4623                                 for (dim = 0; dim < rank; dim++){
4624                                         ig.Emit (OpCodes.Ldloc, copy);
4625                                         IntLiteral.EmitInt (ig, dim);
4626                                         ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4627                                         ig.Emit (OpCodes.Stloc, dim_len [dim]);
4628                                 }
4629
4630                                 for (dim = 0; dim < rank; dim++){
4631                                         ig.Emit (OpCodes.Ldc_I4_0);
4632                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
4633                                         ig.Emit (OpCodes.Br, test [dim]);
4634                                         ig.MarkLabel (loop [dim]);
4635                                 }
4636
4637                                 ig.Emit (OpCodes.Ldloc, copy);
4638                                 for (dim = 0; dim < rank; dim++)
4639                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4640
4641                                 //
4642                                 // FIXME: Maybe we can cache the computation of `get'?
4643                                 //
4644                                 Type [] args = new Type [rank];
4645                                 MethodInfo get;
4646
4647                                 for (int i = 0; i < rank; i++)
4648                                         args [i] = TypeManager.int32_type;
4649
4650                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
4651                                 get = mb.GetArrayMethod (
4652                                         array_type, "Get",
4653                                         CallingConventions.HasThis| CallingConventions.Standard,
4654                                         var_type, args);
4655                                 ig.Emit (OpCodes.Call, get);
4656                                 variable.EmitAssign (ec, conv);
4657                                 statement.Emit (ec);
4658                                 ig.MarkLabel (ec.LoopBegin);
4659                                 for (dim = rank - 1; dim >= 0; dim--){
4660                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4661                                         ig.Emit (OpCodes.Ldc_I4_1);
4662                                         ig.Emit (OpCodes.Add);
4663                                         ig.Emit (OpCodes.Stloc, dim_count [dim]);
4664
4665                                         ig.MarkLabel (test [dim]);
4666                                         ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4667                                         ig.Emit (OpCodes.Ldloc, dim_len [dim]);
4668                                         ig.Emit (OpCodes.Blt, loop [dim]);
4669                                 }
4670                         }
4671                         ig.MarkLabel (ec.LoopEnd);
4672                         
4673                         return false;
4674                 }
4675                 
4676                 public override bool Emit (EmitContext ec)
4677                 {
4678                         bool ret_val;
4679                         
4680                         ILGenerator ig = ec.ig;
4681                         
4682                         Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4683                         bool old_inloop = ec.InLoop;
4684                         int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4685                         ec.LoopBegin = ig.DefineLabel ();
4686                         ec.LoopEnd = ig.DefineLabel ();
4687                         ec.InLoop = true;
4688                         ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4689                         
4690                         if (hm != null)
4691                                 ret_val = EmitCollectionForeach (ec);
4692                         else
4693                                 ret_val = EmitArrayForeach (ec);
4694                         
4695                         ec.LoopBegin = old_begin;
4696                         ec.LoopEnd = old_end;
4697                         ec.InLoop = old_inloop;
4698                         ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
4699
4700                         return ret_val;
4701                 }
4702         }
4703 }
4704