2003-12-20 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / flowanalysis.cs
1 //
2 // flowanalyis.cs: The control flow analysis code
3 //
4 // Author:
5 //   Martin Baulig (martin@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 //
9
10 using System;
11 using System.Text;
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp
18 {
19         // <summary>
20         //   A new instance of this class is created every time a new block is resolved
21         //   and if there's branching in the block's control flow.
22         // </summary>
23         public abstract class FlowBranching
24         {
25                 // <summary>
26                 //   The type of a FlowBranching.
27                 // </summary>
28                 public enum BranchingType {
29                         // Normal (conditional or toplevel) block.
30                         Block,
31
32                         // Conditional.
33                         Conditional,
34
35                         // A loop block.
36                         LoopBlock,
37
38                         // Try/Catch block.
39                         Exception,
40
41                         // Switch block.
42                         Switch,
43
44                         // Switch section.
45                         SwitchSection
46                 }
47
48                 // <summary>
49                 //   The type of one sibling of a branching.
50                 // </summary>
51                 public enum SiblingType {
52                         Block,
53                         Conditional,
54                         SwitchSection,
55                         Try,
56                         Catch,
57                         Finally
58                 }
59
60                 // <summary>
61                 //   This is used in the control flow analysis code to specify whether the
62                 //   current code block may return to its enclosing block before reaching
63                 //   its end.
64                 // </summary>
65                 public enum FlowReturns {
66                         Undefined = 0,
67
68                         // It can never return.
69                         Never,
70
71                         // This means that the block contains a conditional return statement
72                         // somewhere.
73                         Sometimes,
74
75                         // The code always returns, ie. there's an unconditional return / break
76                         // statement in it.
77                         Always
78                 }
79
80                 public sealed class Reachability
81                 {
82                         FlowReturns returns, breaks, throws, barrier, reachable;
83
84                         public FlowReturns Returns {
85                                 get { return returns; }
86                         }
87                         public FlowReturns Breaks {
88                                 get { return breaks; }
89                         }
90                         public FlowReturns Throws {
91                                 get { return throws; }
92                         }
93                         public FlowReturns Barrier {
94                                 get { return barrier; }
95                         }
96                         public FlowReturns Reachable {
97                                 get { return reachable; }
98                         }
99
100                         public Reachability (FlowReturns returns, FlowReturns breaks,
101                                              FlowReturns throws, FlowReturns barrier)
102                         {
103                                 this.returns = returns;
104                                 this.breaks = breaks;
105                                 this.throws = throws;
106                                 this.barrier = barrier;
107
108                                 update ();
109                         }
110
111                         public Reachability Clone ()
112                         {
113                                 Reachability cloned = new Reachability (returns, breaks, throws, barrier);
114                                 cloned.reachable = reachable;
115                                 return cloned;
116                         }
117
118                         public static void And (ref Reachability a, Reachability b, bool do_break)
119                         {
120                                 if (a == null) {
121                                         a = b.Clone ();
122                                         return;
123                                 }
124
125                                 //
126                                 // `break' does not "break" in a Switch or a LoopBlock
127                                 //
128                                 bool a_breaks = do_break && a.AlwaysBreaks;
129                                 bool b_breaks = do_break && b.AlwaysBreaks;
130
131                                 bool a_has_barrier, b_has_barrier;
132                                 if (do_break) {
133                                         //
134                                         // This is the normal case: the code following a barrier
135                                         // cannot be reached.
136                                         //
137                                         a_has_barrier = a.AlwaysHasBarrier;
138                                         b_has_barrier = b.AlwaysHasBarrier;
139                                 } else {
140                                         //
141                                         // Special case for Switch and LoopBlocks: we can reach the
142                                         // code after the barrier via the `break'.
143                                         //
144                                         a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
145                                         b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
146                                 }
147
148                                 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
149                                 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
150
151                                 //
152                                 // Do all code paths always return ?
153                                 //
154                                 if (a.AlwaysReturns) {
155                                         if (b.AlwaysReturns || b_unreachable)
156                                                 a.returns = FlowReturns.Always;
157                                         else
158                                                 a.returns = FlowReturns.Sometimes;
159                                 } else if (b.AlwaysReturns) {
160                                         if (a.AlwaysReturns || a_unreachable)
161                                                 a.returns = FlowReturns.Always;
162                                         else
163                                                 a.returns = FlowReturns.Sometimes;
164                                 } else if (!a.MayReturn) {
165                                         if (b.MayReturn)
166                                                 a.returns = FlowReturns.Sometimes;
167                                         else
168                                                 a.returns = FlowReturns.Never;
169                                 } else if (!b.MayReturn) {
170                                         if (a.MayReturn)
171                                                 a.returns = FlowReturns.Sometimes;
172                                         else
173                                                 a.returns = FlowReturns.Never;
174                                 }
175
176                                 a.breaks = AndFlowReturns (a.breaks, b.breaks);
177                                 a.throws = AndFlowReturns (a.throws, b.throws);
178                                 a.barrier = AndFlowReturns (a.barrier, b.barrier);
179
180                                 a.reachable = AndFlowReturns (a.reachable, b.reachable);
181                         }
182
183                         public static Reachability Never ()
184                         {
185                                 return new Reachability (
186                                         FlowReturns.Never, FlowReturns.Never,
187                                         FlowReturns.Never, FlowReturns.Never);
188                         }
189
190                         void update ()
191                         {
192                                 if ((returns == FlowReturns.Always) || (breaks == FlowReturns.Always) ||
193                                     (throws == FlowReturns.Always) || (barrier == FlowReturns.Always))
194                                         reachable = FlowReturns.Never;
195                                 else if ((returns == FlowReturns.Never) && (breaks == FlowReturns.Never) &&
196                                          (throws == FlowReturns.Never) && (barrier == FlowReturns.Never))
197                                         reachable = FlowReturns.Always;
198                                 else
199                                         reachable = FlowReturns.Sometimes;
200                         }
201
202                         public bool AlwaysBreaks {
203                                 get { return breaks == FlowReturns.Always; }
204                         }
205
206                         public bool MayBreak {
207                                 get { return breaks != FlowReturns.Never; }
208                         }
209
210                         public bool AlwaysReturns {
211                                 get { return returns == FlowReturns.Always; }
212                         }
213
214                         public bool MayReturn {
215                                 get { return returns != FlowReturns.Never; }
216                         }
217
218                         public bool AlwaysThrows {
219                                 get { return throws == FlowReturns.Always; }
220                         }
221
222                         public bool MayThrow {
223                                 get { return throws != FlowReturns.Never; }
224                         }
225
226                         public bool AlwaysHasBarrier {
227                                 get { return barrier == FlowReturns.Always; }
228                         }
229
230                         public bool MayHaveBarrier {
231                                 get { return barrier != FlowReturns.Never; }
232                         }
233
234                         public bool IsUnreachable {
235                                 get { return reachable == FlowReturns.Never; }
236                         }
237
238                         public void SetReturns ()
239                         {
240                                 returns = FlowReturns.Always;
241                                 update ();
242                         }
243
244                         public void SetReturnsSometimes ()
245                         {
246                                 returns = FlowReturns.Sometimes;
247                                 update ();
248                         }
249
250                         public void SetBreaks ()
251                         {
252                                 breaks = FlowReturns.Always;
253                                 update ();
254                         }
255
256                         public void ResetBreaks ()
257                         {
258                                 breaks = FlowReturns.Never;
259                                 update ();
260                         }
261
262                         public void SetThrows ()
263                         {
264                                 throws = FlowReturns.Always;
265                                 update ();
266                         }
267
268                         public void SetBarrier ()
269                         {
270                                 barrier = FlowReturns.Always;
271                                 update ();
272                         }
273
274                         static string ShortName (FlowReturns returns)
275                         {
276                                 switch (returns) {
277                                 case FlowReturns.Never:
278                                         return "N";
279                                 case FlowReturns.Sometimes:
280                                         return "S";
281                                 default:
282                                         return "A";
283                                 }
284                         }
285
286                         public override string ToString ()
287                         {
288                                 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
289                                                       ShortName (returns), ShortName (breaks),
290                                                       ShortName (throws), ShortName (barrier),
291                                                       ShortName (reachable));
292                         }
293                 }
294
295                 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
296                 {
297                         switch (type) {
298                         case BranchingType.Exception:
299                                 return new FlowBranchingException (parent, type, block, loc);
300
301                         case BranchingType.Switch:
302                                 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
303
304                         case BranchingType.SwitchSection:
305                                 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
306
307                         case BranchingType.Block:
308                                 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
309
310                         default:
311                                 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
312                         }
313                 }
314
315                 // <summary>
316                 //   The type of this flow branching.
317                 // </summary>
318                 public readonly BranchingType Type;
319
320                 // <summary>
321                 //   The block this branching is contained in.  This may be null if it's not
322                 //   a top-level block and it doesn't declare any local variables.
323                 // </summary>
324                 public readonly Block Block;
325
326                 // <summary>
327                 //   The parent of this branching or null if this is the top-block.
328                 // </summary>
329                 public readonly FlowBranching Parent;
330
331                 // <summary>
332                 //   Start-Location of this flow branching.
333                 // </summary>
334                 public readonly Location Location;
335
336                 // <summary>
337                 //   If this is an infinite loop.
338                 // </summary>
339                 public bool Infinite;
340
341                 //
342                 // Private
343                 //
344                 VariableMap param_map, local_map;
345
346                 static int next_id = 0;
347                 int id;
348
349                 // <summary>
350                 //   Performs an `And' operation on the FlowReturns status
351                 //   (for instance, a block only returns Always if all its siblings
352                 //   always return).
353                 // </summary>
354                 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
355                 {
356                         if (a == FlowReturns.Undefined)
357                                 return b;
358
359                         switch (a) {
360                         case FlowReturns.Never:
361                                 if (b == FlowReturns.Never)
362                                         return FlowReturns.Never;
363                                 else
364                                         return FlowReturns.Sometimes;
365
366                         case FlowReturns.Sometimes:
367                                 return FlowReturns.Sometimes;
368
369                         case FlowReturns.Always:
370                                 if (b == FlowReturns.Always)
371                                         return FlowReturns.Always;
372                                 else
373                                         return FlowReturns.Sometimes;
374
375                         default:
376                                 throw new ArgumentException ();
377                         }
378                 }
379
380                 // <summary>
381                 //   The vector contains a BitArray with information about which local variables
382                 //   and parameters are already initialized at the current code position.
383                 // </summary>
384                 public class UsageVector {
385                         // <summary>
386                         //   The type of this branching.
387                         // </summary>
388                         public readonly SiblingType Type;
389
390                         // <summary>
391                         //   Start location of this branching.
392                         // </summary>
393                         public readonly Location Location;
394
395                         // <summary>
396                         //   If this is true, then the usage vector has been modified and must be
397                         //   merged when we're done with this branching.
398                         // </summary>
399                         public bool IsDirty;
400
401                         // <summary>
402                         //   The number of parameters in this block.
403                         // </summary>
404                         public readonly int CountParameters;
405
406                         // <summary>
407                         //   The number of locals in this block.
408                         // </summary>
409                         public readonly int CountLocals;
410
411                         // <summary>
412                         //   If not null, then we inherit our state from this vector and do a
413                         //   copy-on-write.  If null, then we're the first sibling in a top-level
414                         //   block and inherit from the empty vector.
415                         // </summary>
416                         public readonly UsageVector InheritsFrom;
417
418                         // <summary>
419                         //   This is used to construct a list of UsageVector's.
420                         // </summary>
421                         public UsageVector Next;
422
423                         //
424                         // Private.
425                         //
426                         MyBitVector locals, parameters;
427                         Reachability reachability;
428                         bool is_finally;
429
430                         static int next_id = 0;
431                         int id;
432
433                         //
434                         // Normally, you should not use any of these constructors.
435                         //
436                         public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
437                         {
438                                 this.Type = type;
439                                 this.Location = loc;
440                                 this.InheritsFrom = parent;
441                                 this.CountParameters = num_params;
442                                 this.CountLocals = num_locals;
443
444                                 if (parent != null) {
445                                         locals = new MyBitVector (parent.locals, CountLocals);
446                                         if (num_params > 0)
447                                                 parameters = new MyBitVector (parent.parameters, num_params);
448
449                                         reachability = parent.Reachability.Clone ();
450                                 } else {
451                                         locals = new MyBitVector (null, CountLocals);
452                                         if (num_params > 0)
453                                                 parameters = new MyBitVector (null, num_params);
454
455                                         reachability = Reachability.Never ();
456                                 }
457
458                                 id = ++next_id;
459                         }
460
461                         public UsageVector (SiblingType type, UsageVector parent, Location loc)
462                                 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
463                         { }
464
465                         public UsageVector (MyBitVector parameters, MyBitVector locals,
466                                             Reachability reachability, Location loc)
467                         {
468                                 this.Type = SiblingType.Block;
469                                 this.Location = loc;
470
471                                 this.reachability = reachability;
472                                 this.parameters = parameters;
473                                 this.locals = locals;
474
475                                 id = ++next_id;
476                         }
477
478                         // <summary>
479                         //   This does a deep copy of the usage vector.
480                         // </summary>
481                         public UsageVector Clone ()
482                         {
483                                 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
484
485                                 retval.locals = locals.Clone ();
486                                 if (parameters != null)
487                                         retval.parameters = parameters.Clone ();
488                                 retval.reachability = reachability.Clone ();
489
490                                 return retval;
491                         }
492
493                         public bool IsAssigned (VariableInfo var)
494                         {
495                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
496                                         return true;
497
498                                 return var.IsAssigned (var.IsParameter ? parameters : locals);
499                         }
500
501                         public void SetAssigned (VariableInfo var)
502                         {
503                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
504                                         return;
505
506                                 IsDirty = true;
507                                 var.SetAssigned (var.IsParameter ? parameters : locals);
508                         }
509
510                         public bool IsFieldAssigned (VariableInfo var, string name)
511                         {
512                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
513                                         return true;
514
515                                 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
516                         }
517
518                         public void SetFieldAssigned (VariableInfo var, string name)
519                         {
520                                 if (!var.IsParameter && Reachability.AlwaysBreaks)
521                                         return;
522
523                                 IsDirty = true;
524                                 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
525                         }
526
527                         public Reachability Reachability {
528                                 get {
529                                         return reachability;
530                                 }
531                         }
532
533                         public void Return ()
534                         {
535                                 if (!reachability.IsUnreachable) {
536                                         IsDirty = true;
537                                         reachability.SetReturns ();
538                                 }
539                         }
540
541                         public void Break ()
542                         {
543                                 if (!reachability.IsUnreachable) {
544                                         IsDirty = true;
545                                         reachability.SetBreaks ();
546                                 }
547                         }
548
549                         public void Throw ()
550                         {
551                                 if (!reachability.IsUnreachable) {
552                                         IsDirty = true;
553                                         reachability.SetThrows ();
554                                 }
555                         }
556
557                         public void Goto ()
558                         {
559                                 if (!reachability.IsUnreachable) {
560                                         IsDirty = true;
561                                         reachability.SetBarrier ();
562                                 }
563                         }
564
565                         // <summary>
566                         //   Merges a child branching.
567                         // </summary>
568                         public UsageVector MergeChild (FlowBranching branching)
569                         {
570                                 UsageVector result = branching.Merge ();
571
572                                 Report.Debug (2, "  MERGING CHILD", this, IsDirty,
573                                               result.ParameterVector, result.LocalVector,
574                                               result.Reachability, Type);
575
576                                 reachability = result.Reachability;
577
578                                 if (branching.Type == BranchingType.LoopBlock) {
579                                         bool may_leave_loop = reachability.MayBreak;
580                                         reachability.ResetBreaks ();
581
582                                         if (branching.Infinite && !may_leave_loop) {
583                                                 if (reachability.Returns == FlowReturns.Sometimes) {
584                                                         // If we're an infinite loop and do not break,
585                                                         // the code after the loop can never be reached.
586                                                         // However, if we may return from the loop,
587                                                         // then we do always return (or stay in the
588                                                         // loop forever).
589                                                         reachability.SetReturns ();
590                                                 }
591
592                                                 reachability.SetBarrier ();
593                                         } else {
594                                                 if (reachability.Returns == FlowReturns.Always) {
595                                                         // We're either finite or we may leave the loop.
596                                                         reachability.SetReturnsSometimes ();
597                                                 }
598                                         }
599                                 } else if (branching.Type == BranchingType.Switch)
600                                         reachability.ResetBreaks ();
601
602                                 //
603                                 // We've now either reached the point after the branching or we will
604                                 // never get there since we always return or always throw an exception.
605                                 //
606                                 // If we can reach the point after the branching, mark all locals and
607                                 // parameters as initialized which have been initialized in all branches
608                                 // we need to look at (see above).
609                                 //
610
611                                 if ((Type == SiblingType.SwitchSection) && !reachability.IsUnreachable) {
612                                         Report.Error (163, Location,
613                                                       "Control cannot fall through from one " +
614                                                       "case label to another");
615                                         return result;
616                                 }
617
618                                 if (result.LocalVector != null)
619                                         locals.Or (result.LocalVector);
620
621                                 if (result.ParameterVector != null)
622                                         parameters.Or (result.ParameterVector);
623
624                                 Report.Debug (2, "  MERGING CHILD DONE", this, result);
625
626                                 IsDirty = true;
627
628                                 return result;
629                         }
630
631                         protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
632                                                      MyBitVector f_params)
633                         {
634                                 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
635                                         MyBitVector temp_params = f_params.Clone ();
636                                         temp_params.Or (vector.Parameters);
637                                 }
638                         }
639
640                         public void MergeFinally (FlowBranching branching, UsageVector f_vector,
641                                                   UsageVector f_origins)
642                         {
643                                 if (parameters != null) {
644                                         if (f_vector != null) {
645                                                 MergeFinally (branching, f_origins, f_vector.Parameters);
646                                                 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
647                                         } else
648                                                 MergeFinally (branching, f_origins, parameters);
649                                 }
650
651                                 if (f_vector != null)
652                                         MyBitVector.Or (ref locals, f_vector.LocalVector);
653                         }
654
655                         // <summary>
656                         //   Tells control flow analysis that the current code position may be reached with
657                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
658                         //   list of UsageVectors.
659                         //
660                         //   This is used when resolving forward gotos - in the following example, the
661                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
662                         //   the goto in line 4:
663                         //
664                         //      1     int a;
665                         //
666                         //      3     if (something)
667                         //      4        goto World;
668                         //
669                         //      6     a = 5;
670                         //
671                         //      7  World:
672                         //      8     Console.WriteLine (a);
673                         //
674                         // </summary>
675                         public void MergeJumpOrigins (ICollection origin_vectors)
676                         {
677                                 Report.Debug (1, "  MERGING JUMP ORIGINS", this);
678
679                                 reachability = Reachability.Never ();
680
681                                 if (origin_vectors == null)
682                                         return;
683
684                                 bool first = true;
685
686                                 foreach (UsageVector vector in origin_vectors) {
687                                         Report.Debug (1, "    MERGING JUMP ORIGIN", vector);
688
689                                         if (first) {
690                                                 locals.Or (vector.locals);
691                                                 if (parameters != null)
692                                                         parameters.Or (vector.parameters);
693                                                 first = false;
694                                         } else {
695                                                 locals.And (vector.locals);
696                                                 if (parameters != null)
697                                                         parameters.And (vector.parameters);
698                                         }
699                                                 
700                                         Reachability.And (ref reachability, vector.Reachability, true);
701                                 }
702
703                                 Report.Debug (1, "  MERGING JUMP ORIGINS DONE", this);
704                         }
705
706                         // <summary>
707                         //   This is used at the beginning of a finally block if there were
708                         //   any return statements in the try block or one of the catch blocks.
709                         // </summary>
710                         public void MergeFinallyOrigins (UsageVector f_origins)
711                         {
712                                 Report.Debug (1, "  MERGING FINALLY ORIGIN", this);
713
714                                 reachability = Reachability.Never ();
715
716                                 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
717                                         Report.Debug (1, "    MERGING FINALLY ORIGIN", vector);
718
719                                         if (parameters != null)
720                                                 parameters.And (vector.parameters);
721
722                                         Reachability.And (ref reachability, vector.Reachability, true);
723                                 }
724
725                                 is_finally = true;
726
727                                 Report.Debug (1, "  MERGING FINALLY ORIGIN DONE", this);
728                         }
729
730                         public void CheckOutParameters (FlowBranching branching)
731                         {
732                                 if (parameters != null)
733                                         branching.CheckOutParameters (parameters, branching.Location);
734                         }
735
736                         // <summary>
737                         //   Performs an `or' operation on the locals and the parameters.
738                         // </summary>
739                         public void Or (UsageVector new_vector)
740                         {
741                                 IsDirty = true;
742                                 locals.Or (new_vector.locals);
743                                 if (parameters != null)
744                                         parameters.Or (new_vector.parameters);
745                         }
746
747                         // <summary>
748                         //   Performs an `and' operation on the locals.
749                         // </summary>
750                         public void AndLocals (UsageVector new_vector)
751                         {
752                                 IsDirty = true;
753                                 locals.And (new_vector.locals);
754                         }
755
756                         public bool HasParameters {
757                                 get {
758                                         return parameters != null;
759                                 }
760                         }
761
762                         public bool HasLocals {
763                                 get {
764                                         return locals != null;
765                                 }
766                         }
767
768                         // <summary>
769                         //   Returns a deep copy of the parameters.
770                         // </summary>
771                         public MyBitVector Parameters {
772                                 get {
773                                         if (parameters != null)
774                                                 return parameters.Clone ();
775                                         else
776                                                 return null;
777                                 }
778                         }
779
780                         // <summary>
781                         //   Returns a deep copy of the locals.
782                         // </summary>
783                         public MyBitVector Locals {
784                                 get {
785                                         return locals.Clone ();
786                                 }
787                         }
788
789                         public MyBitVector ParameterVector {
790                                 get {
791                                         return parameters;
792                                 }
793                         }
794
795                         public MyBitVector LocalVector {
796                                 get {
797                                         return locals;
798                                 }
799                         }
800
801                         //
802                         // Debugging stuff.
803                         //
804
805                         public override string ToString ()
806                         {
807                                 StringBuilder sb = new StringBuilder ();
808
809                                 sb.Append ("Vector (");
810                                 sb.Append (id);
811                                 sb.Append (",");
812                                 sb.Append (IsDirty);
813                                 sb.Append (",");
814                                 sb.Append (reachability);
815                                 if (parameters != null) {
816                                         sb.Append (" - ");
817                                         sb.Append (parameters);
818                                 }
819                                 sb.Append (" - ");
820                                 sb.Append (locals);
821                                 sb.Append (")");
822
823                                 return sb.ToString ();
824                         }
825                 }
826
827                 // <summary>
828                 //   Creates a new flow branching which is contained in `parent'.
829                 //   You should only pass non-null for the `block' argument if this block
830                 //   introduces any new variables - in this case, we need to create a new
831                 //   usage vector with a different size than our parent's one.
832                 // </summary>
833                 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
834                                          Block block, Location loc)
835                 {
836                         Parent = parent;
837                         Block = block;
838                         Location = loc;
839                         Type = type;
840                         id = ++next_id;
841
842                         UsageVector vector;
843                         if (Block != null) {
844                                 param_map = Block.ParameterMap;
845                                 local_map = Block.LocalMap;
846
847                                 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
848                                 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
849                         } else {
850                                 param_map = Parent.param_map;
851                                 local_map = Parent.local_map;
852                                 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
853                         }
854
855                         AddSibling (vector);
856                 }
857
858                 public abstract UsageVector CurrentUsageVector {
859                         get;
860                 }                               
861
862                 // <summary>
863                 //   Creates a sibling of the current usage vector.
864                 // </summary>
865                 public virtual void CreateSibling (SiblingType type)
866                 {
867                         AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
868
869                         Report.Debug (1, "  CREATED SIBLING", CurrentUsageVector);
870                 }
871
872                 protected abstract void AddSibling (UsageVector uv);
873
874                 public abstract void Label (ArrayList origin_vectors);
875
876                 // <summary>
877                 //   Check whether all `out' parameters have been assigned.
878                 // </summary>
879                 public void CheckOutParameters (MyBitVector parameters, Location loc)
880                 {
881                         for (int i = 0; i < param_map.Count; i++) {
882                                 VariableInfo var = param_map [i];
883
884                                 if (var == null)
885                                         continue;
886
887                                 if (var.IsAssigned (parameters))
888                                         continue;
889
890                                 Report.Error (177, loc, "The out parameter `" +
891                                               param_map.VariableNames [i] + "' must be " +
892                                               "assigned before control leave the current method.");
893                         }
894                 }
895
896                 protected UsageVector Merge (UsageVector sibling_list)
897                 {
898                         if (sibling_list.Next == null)
899                                 return sibling_list;
900
901                         MyBitVector locals = null;
902                         MyBitVector parameters = null;
903
904                         Reachability reachability = null;
905
906                         Report.Debug (2, "  MERGING SIBLINGS", this, Name);
907
908                         for (UsageVector child = sibling_list; child != null; child = child.Next) {
909                                 bool do_break = (Type != BranchingType.Switch) &&
910                                         (Type != BranchingType.LoopBlock);
911
912                                 Report.Debug (2, "    MERGING SIBLING   ", child,
913                                               child.Parameters, child.Locals,
914                                               reachability, child.Reachability, do_break);
915
916                                 Reachability.And (ref reachability, child.Reachability, do_break);
917
918                                 // A local variable is initialized after a flow branching if it
919                                 // has been initialized in all its branches which do neither
920                                 // always return or always throw an exception.
921                                 //
922                                 // If a branch may return, but does not always return, then we
923                                 // can treat it like a never-returning branch here: control will
924                                 // only reach the code position after the branching if we did not
925                                 // return here.
926                                 //
927                                 // It's important to distinguish between always and sometimes
928                                 // returning branches here:
929                                 //
930                                 //    1   int a;
931                                 //    2   if (something) {
932                                 //    3      return;
933                                 //    4      a = 5;
934                                 //    5   }
935                                 //    6   Console.WriteLine (a);
936                                 //
937                                 // The if block in lines 3-4 always returns, so we must not look
938                                 // at the initialization of `a' in line 4 - thus it'll still be
939                                 // uninitialized in line 6.
940                                 //
941                                 // On the other hand, the following is allowed:
942                                 //
943                                 //    1   int a;
944                                 //    2   if (something)
945                                 //    3      a = 5;
946                                 //    4   else
947                                 //    5      return;
948                                 //    6   Console.WriteLine (a);
949                                 //
950                                 // Here, `a' is initialized in line 3 and we must not look at
951                                 // line 5 since it always returns.
952                                 // 
953                                 bool do_break_2 = (child.Type != SiblingType.Block) &&
954                                         (child.Type != SiblingType.SwitchSection);
955                                 bool unreachable = (do_break_2 && child.Reachability.AlwaysBreaks) ||
956                                         child.Reachability.AlwaysThrows ||
957                                         child.Reachability.AlwaysReturns ||
958                                         child.Reachability.AlwaysHasBarrier;
959
960                                 Report.Debug (2, "    MERGING SIBLING #1", reachability,
961                                               Type, child.Type, child.Reachability.IsUnreachable,
962                                               do_break_2, unreachable);
963
964                                 if (!unreachable)
965                                         MyBitVector.And (ref locals, child.LocalVector);
966
967                                 // An `out' parameter must be assigned in all branches which do
968                                 // not always throw an exception.
969                                 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
970                                         MyBitVector.And (ref parameters, child.ParameterVector);
971
972                                 Report.Debug (2, "    MERGING SIBLING #2", parameters, locals);
973                         }
974
975                         if (reachability == null)
976                                 reachability = Reachability.Never ();
977
978                         Report.Debug (2, "  MERGING SIBLINGS DONE", parameters, locals,
979                                       reachability, Infinite);
980
981                         return new UsageVector (parameters, locals, reachability, Location);
982                 }
983
984                 protected abstract UsageVector Merge ();
985
986                 // <summary>
987                 //   Merge a child branching.
988                 // </summary>
989                 public UsageVector MergeChild (FlowBranching child)
990                 {
991                         return CurrentUsageVector.MergeChild (child);
992                 }
993
994                 // <summary>
995                 //   Does the toplevel merging.
996                 // </summary>
997                 public Reachability MergeTopBlock ()
998                 {
999                         if ((Type != BranchingType.Block) || (Block == null))
1000                                 throw new NotSupportedException ();
1001
1002                         UsageVector vector = new UsageVector (
1003                                 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1004
1005                         UsageVector result = vector.MergeChild (this);
1006
1007                         Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1008
1009                         if (vector.Reachability.Throws != FlowReturns.Always)
1010                                 CheckOutParameters (vector.Parameters, Location);
1011
1012                         return result.Reachability;
1013                 }
1014
1015                 public virtual bool InTryBlock ()
1016                 {
1017                         if (Parent != null)
1018                                 return Parent.InTryBlock ();
1019                         else
1020                                 return false;
1021                 }
1022
1023                 public virtual void AddFinallyVector (UsageVector vector)
1024                 {
1025                         if (Parent != null)
1026                                 Parent.AddFinallyVector (vector);
1027                         else
1028                                 throw new NotSupportedException ();
1029                 }
1030
1031                 public bool IsAssigned (VariableInfo vi)
1032                 {
1033                         return CurrentUsageVector.IsAssigned (vi);
1034                 }
1035
1036                 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1037                 {
1038                         if (CurrentUsageVector.IsAssigned (vi))
1039                                 return true;
1040
1041                         return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1042                 }
1043
1044                 public void SetAssigned (VariableInfo vi)
1045                 {
1046                         CurrentUsageVector.SetAssigned (vi);
1047                 }
1048
1049                 public void SetFieldAssigned (VariableInfo vi, string name)
1050                 {
1051                         CurrentUsageVector.SetFieldAssigned (vi, name);
1052                 }
1053
1054                 public override string ToString ()
1055                 {
1056                         StringBuilder sb = new StringBuilder ();
1057                         sb.Append (GetType ());
1058                         sb.Append (" (");
1059
1060                         sb.Append (id);
1061                         sb.Append (",");
1062                         sb.Append (Type);
1063                         if (Block != null) {
1064                                 sb.Append (" - ");
1065                                 sb.Append (Block.ID);
1066                                 sb.Append (" - ");
1067                                 sb.Append (Block.StartLocation);
1068                         }
1069                         sb.Append (" - ");
1070                         // sb.Append (Siblings.Length);
1071                         // sb.Append (" - ");
1072                         sb.Append (CurrentUsageVector);
1073                         sb.Append (")");
1074                         return sb.ToString ();
1075                 }
1076
1077                 public string Name {
1078                         get {
1079                                 return String.Format ("{0} ({1}:{2}:{3})",
1080                                                       GetType (), id, Type, Location);
1081                         }
1082                 }
1083         }
1084
1085         public class FlowBranchingBlock : FlowBranching
1086         {
1087                 UsageVector sibling_list = null;
1088
1089                 public FlowBranchingBlock (FlowBranching parent, BranchingType type, SiblingType stype,
1090                                            Block block, Location loc)
1091                         : base (parent, type, stype, block, loc)
1092                 { }
1093
1094                 public override UsageVector CurrentUsageVector {
1095                         get { return sibling_list; }
1096                 }
1097
1098                 protected override void AddSibling (UsageVector sibling)
1099                 {
1100                         sibling.Next = sibling_list;
1101                         sibling_list = sibling;
1102                 }
1103
1104                 public override void Label (ArrayList origin_vectors)
1105                 {
1106                         if (!CurrentUsageVector.Reachability.IsUnreachable) {
1107                                 if (origin_vectors == null)
1108                                         origin_vectors = new ArrayList (1);
1109                                 origin_vectors.Add (CurrentUsageVector.Clone ());
1110                         }
1111
1112                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1113                 }
1114
1115                 protected override UsageVector Merge ()
1116                 {
1117                         return Merge (sibling_list);
1118                 }
1119         }
1120
1121         public class FlowBranchingException : FlowBranching
1122         {
1123                 UsageVector current_vector;
1124                 UsageVector try_vector;
1125                 UsageVector catch_vectors;
1126                 UsageVector finally_vector;
1127                 UsageVector finally_origins;
1128
1129                 public FlowBranchingException (FlowBranching parent, BranchingType type, Block block, Location loc)
1130                         : base (parent, type, SiblingType.Try, block, loc)
1131                 { }
1132
1133                 protected override void AddSibling (UsageVector sibling)
1134                 {
1135                         if (sibling.Type == SiblingType.Try) {
1136                                 try_vector = sibling;
1137                                 sibling.Next = catch_vectors;
1138                                 catch_vectors = sibling;
1139                         } else if (sibling.Type == SiblingType.Catch) {
1140                                 sibling.Next = catch_vectors;
1141                                 catch_vectors = sibling;
1142                         } else if (sibling.Type == SiblingType.Finally) {
1143                                 sibling.MergeFinallyOrigins (finally_origins);
1144                                 finally_vector = sibling;
1145                         } else
1146                                 throw new InvalidOperationException ();
1147
1148                         current_vector = sibling;
1149                 }
1150
1151                 public override UsageVector CurrentUsageVector {
1152                         get { return current_vector; }
1153                 }
1154
1155                 public override bool InTryBlock ()
1156                 {
1157                         return true;
1158                 }
1159
1160                 public override void AddFinallyVector (UsageVector vector)
1161                 {
1162                         vector = vector.Clone ();
1163                         vector.Next = finally_origins;
1164                         finally_origins = vector;
1165                 }
1166
1167                 public override void Label (ArrayList origin_vectors)
1168                 {
1169                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1170                 }
1171
1172                 protected override UsageVector Merge ()
1173                 {
1174                         UsageVector vector = Merge (catch_vectors);
1175
1176                         vector.MergeFinally (this, finally_vector, finally_origins);
1177
1178                         return vector;
1179                 }
1180         }
1181
1182         // <summary>
1183         //   This is used by the flow analysis code to keep track of the type of local variables
1184         //   and variables.
1185         //
1186         //   The flow code uses a BitVector to keep track of whether a variable has been assigned
1187         //   or not.  This is easy for fundamental types (int, char etc.) or reference types since
1188         //   you can only assign the whole variable as such.
1189         //
1190         //   For structs, we also need to keep track of all its fields.  To do this, we allocate one
1191         //   bit for the struct itself (it's used if you assign/access the whole struct) followed by
1192         //   one bit for each of its fields.
1193         //
1194         //   This class computes this `layout' for each type.
1195         // </summary>
1196         public class TypeInfo
1197         {
1198                 public readonly Type Type;
1199
1200                 // <summary>
1201                 //   Total number of bits a variable of this type consumes in the flow vector.
1202                 // </summary>
1203                 public readonly int TotalLength;
1204
1205                 // <summary>
1206                 //   Number of bits the simple fields of a variable of this type consume
1207                 //   in the flow vector.
1208                 // </summary>
1209                 public readonly int Length;
1210
1211                 // <summary>
1212                 //   This is only used by sub-structs.
1213                 // </summary>
1214                 public readonly int Offset;
1215
1216                 // <summary>
1217                 //   If this is a struct.
1218                 // </summary>
1219                 public readonly bool IsStruct;       
1220
1221                 // <summary>
1222                 //   If this is a struct, all fields which are structs theirselves.
1223                 // </summary>
1224                 public TypeInfo[] SubStructInfo;
1225
1226                 protected readonly StructInfo struct_info;
1227                 private static Hashtable type_hash = new Hashtable ();
1228
1229                 public static TypeInfo GetTypeInfo (Type type)
1230                 {
1231                         TypeInfo info = (TypeInfo) type_hash [type];
1232                         if (info != null)
1233                                 return info;
1234
1235                         info = new TypeInfo (type);
1236                         type_hash.Add (type, info);
1237                         return info;
1238                 }
1239
1240                 public static TypeInfo GetTypeInfo (TypeContainer tc)
1241                 {
1242                         TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1243                         if (info != null)
1244                                 return info;
1245
1246                         info = new TypeInfo (tc);
1247                         type_hash.Add (tc.TypeBuilder, info);
1248                         return info;
1249                 }
1250
1251                 private TypeInfo (Type type)
1252                 {
1253                         this.Type = type;
1254
1255                         struct_info = StructInfo.GetStructInfo (type);
1256                         if (struct_info != null) {
1257                                 Length = struct_info.Length;
1258                                 TotalLength = struct_info.TotalLength;
1259                                 SubStructInfo = struct_info.StructFields;
1260                                 IsStruct = true;
1261                         } else {
1262                                 Length = 0;
1263                                 TotalLength = 1;
1264                                 IsStruct = false;
1265                         }
1266                 }
1267
1268                 private TypeInfo (TypeContainer tc)
1269                 {
1270                         this.Type = tc.TypeBuilder;
1271
1272                         struct_info = StructInfo.GetStructInfo (tc);
1273                         if (struct_info != null) {
1274                                 Length = struct_info.Length;
1275                                 TotalLength = struct_info.TotalLength;
1276                                 SubStructInfo = struct_info.StructFields;
1277                                 IsStruct = true;
1278                         } else {
1279                                 Length = 0;
1280                                 TotalLength = 1;
1281                                 IsStruct = false;
1282                         }
1283                 }
1284
1285                 protected TypeInfo (StructInfo struct_info, int offset)
1286                 {
1287                         this.struct_info = struct_info;
1288                         this.Offset = offset;
1289                         this.Length = struct_info.Length;
1290                         this.TotalLength = struct_info.TotalLength;
1291                         this.SubStructInfo = struct_info.StructFields;
1292                         this.Type = struct_info.Type;
1293                         this.IsStruct = true;
1294                 }
1295
1296                 public int GetFieldIndex (string name)
1297                 {
1298                         if (struct_info == null)
1299                                 return 0;
1300
1301                         return struct_info [name];
1302                 }
1303
1304                 public TypeInfo GetSubStruct (string name)
1305                 {
1306                         if (struct_info == null)
1307                                 return null;
1308
1309                         return struct_info.GetStructField (name);
1310                 }
1311
1312                 // <summary>
1313                 //   A struct's constructor must always assign all fields.
1314                 //   This method checks whether it actually does so.
1315                 // </summary>
1316                 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1317                 {
1318                         if (struct_info == null)
1319                                 return true;
1320
1321                         bool ok = true;
1322                         for (int i = 0; i < struct_info.Count; i++) {
1323                                 FieldInfo field = struct_info.Fields [i];
1324
1325                                 if (!branching.IsFieldAssigned (vi, field.Name)) {
1326                                         Report.Error (171, loc,
1327                                                       "Field `" + TypeManager.CSharpName (Type) +
1328                                                       "." + field.Name + "' must be fully initialized " +
1329                                                       "before control leaves the constructor");
1330                                         ok = false;
1331                                 }
1332                         }
1333
1334                         return ok;
1335                 }
1336
1337                 public override string ToString ()
1338                 {
1339                         return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1340                                               Type, Offset, Length, TotalLength);
1341                 }
1342
1343                 protected class StructInfo {
1344                         public readonly Type Type;
1345                         public readonly FieldInfo[] Fields;
1346                         public readonly TypeInfo[] StructFields;
1347                         public readonly int Count;
1348                         public readonly int CountPublic;
1349                         public readonly int CountNonPublic;
1350                         public readonly int Length;
1351                         public readonly int TotalLength;
1352                         public readonly bool HasStructFields;
1353
1354                         private static Hashtable field_type_hash = new Hashtable ();
1355                         private Hashtable struct_field_hash;
1356                         private Hashtable field_hash;
1357
1358                         protected bool InTransit = false;
1359
1360                         // Private constructor.  To save memory usage, we only need to create one instance
1361                         // of this class per struct type.
1362                         private StructInfo (Type type)
1363                         {
1364                                 this.Type = type;
1365
1366                                 field_type_hash.Add (type, this);
1367
1368                                 if (type is TypeBuilder) {
1369                                         TypeContainer tc = TypeManager.LookupTypeContainer (type);
1370
1371                                         ArrayList fields = tc.Fields;
1372
1373                                         ArrayList public_fields = new ArrayList ();
1374                                         ArrayList non_public_fields = new ArrayList ();
1375
1376                                         if (fields != null) {
1377                                                 foreach (Field field in fields) {
1378                                                         if ((field.ModFlags & Modifiers.STATIC) != 0)
1379                                                                 continue;
1380                                                         if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1381                                                                 public_fields.Add (field.FieldBuilder);
1382                                                         else
1383                                                                 non_public_fields.Add (field.FieldBuilder);
1384                                                 }
1385                                         }
1386
1387                                         CountPublic = public_fields.Count;
1388                                         CountNonPublic = non_public_fields.Count;
1389                                         Count = CountPublic + CountNonPublic;
1390
1391                                         Fields = new FieldInfo [Count];
1392                                         public_fields.CopyTo (Fields, 0);
1393                                         non_public_fields.CopyTo (Fields, CountPublic);
1394                                 } else {
1395                                         FieldInfo[] public_fields = type.GetFields (
1396                                                 BindingFlags.Instance|BindingFlags.Public);
1397                                         FieldInfo[] non_public_fields = type.GetFields (
1398                                                 BindingFlags.Instance|BindingFlags.NonPublic);
1399
1400                                         CountPublic = public_fields.Length;
1401                                         CountNonPublic = non_public_fields.Length;
1402                                         Count = CountPublic + CountNonPublic;
1403
1404                                         Fields = new FieldInfo [Count];
1405                                         public_fields.CopyTo (Fields, 0);
1406                                         non_public_fields.CopyTo (Fields, CountPublic);
1407                                 }
1408
1409                                 struct_field_hash = new Hashtable ();
1410                                 field_hash = new Hashtable ();
1411
1412                                 Length = 0;
1413                                 StructFields = new TypeInfo [Count];
1414                                 StructInfo[] sinfo = new StructInfo [Count];
1415
1416                                 InTransit = true;
1417
1418                                 for (int i = 0; i < Count; i++) {
1419                                         FieldInfo field = (FieldInfo) Fields [i];
1420
1421                                         sinfo [i] = GetStructInfo (field.FieldType);
1422                                         if (sinfo [i] == null)
1423                                                 field_hash.Add (field.Name, ++Length);
1424                                         else if (sinfo [i].InTransit) {
1425                                                 Report.Error (523, String.Format (
1426                                                                       "Struct member '{0}.{1}' of type '{2}' causes " +
1427                                                                       "a cycle in the structure layout",
1428                                                                       type, field.Name, sinfo [i].Type));
1429                                                 sinfo [i] = null;
1430                                                 return;
1431                                         }
1432                                 }
1433
1434                                 InTransit = false;
1435
1436                                 TotalLength = Length + 1;
1437                                 for (int i = 0; i < Count; i++) {
1438                                         FieldInfo field = (FieldInfo) Fields [i];
1439
1440                                         if (sinfo [i] == null)
1441                                                 continue;
1442
1443                                         field_hash.Add (field.Name, TotalLength);
1444
1445                                         HasStructFields = true;
1446                                         StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1447                                         struct_field_hash.Add (field.Name, StructFields [i]);
1448                                         TotalLength += sinfo [i].TotalLength;
1449                                 }
1450                         }
1451
1452                         public int this [string name] {
1453                                 get {
1454                                         if (field_hash.Contains (name))
1455                                                 return (int) field_hash [name];
1456                                         else
1457                                                 return 0;
1458                                 }
1459                         }
1460
1461                         public TypeInfo GetStructField (string name)
1462                         {
1463                                 return (TypeInfo) struct_field_hash [name];
1464                         }
1465
1466                         public static StructInfo GetStructInfo (Type type)
1467                         {
1468                                 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1469                                     TypeManager.IsBuiltinType (type))
1470                                         return null;
1471
1472                                 StructInfo info = (StructInfo) field_type_hash [type];
1473                                 if (info != null)
1474                                         return info;
1475
1476                                 return new StructInfo (type);
1477                         }
1478
1479                         public static StructInfo GetStructInfo (TypeContainer tc)
1480                         {
1481                                 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1482                                 if (info != null)
1483                                         return info;
1484
1485                                 return new StructInfo (tc.TypeBuilder);
1486                         }
1487                 }
1488         }
1489
1490         // <summary>
1491         //   This is used by the flow analysis code to store information about a single local variable
1492         //   or parameter.  Depending on the variable's type, we need to allocate one or more elements
1493         //   in the BitVector - if it's a fundamental or reference type, we just need to know whether
1494         //   it has been assigned or not, but for structs, we need this information for each of its fields.
1495         // </summary>
1496         public class VariableInfo {
1497                 public readonly string Name;
1498                 public readonly TypeInfo TypeInfo;
1499
1500                 // <summary>
1501                 //   The bit offset of this variable in the flow vector.
1502                 // </summary>
1503                 public readonly int Offset;
1504
1505                 // <summary>
1506                 //   The number of bits this variable needs in the flow vector.
1507                 //   The first bit always specifies whether the variable as such has been assigned while
1508                 //   the remaining bits contain this information for each of a struct's fields.
1509                 // </summary>
1510                 public readonly int Length;
1511
1512                 // <summary>
1513                 //   If this is a parameter of local variable.
1514                 // </summary>
1515                 public readonly bool IsParameter;
1516
1517                 public readonly LocalInfo LocalInfo;
1518                 public readonly int ParameterIndex;
1519
1520                 readonly VariableInfo Parent;
1521                 VariableInfo[] sub_info;
1522
1523                 protected VariableInfo (string name, Type type, int offset)
1524                 {
1525                         this.Name = name;
1526                         this.Offset = offset;
1527                         this.TypeInfo = TypeInfo.GetTypeInfo (type);
1528
1529                         Length = TypeInfo.TotalLength;
1530
1531                         Initialize ();
1532                 }
1533
1534                 protected VariableInfo (VariableInfo parent, TypeInfo type)
1535                 {
1536                         this.Name = parent.Name;
1537                         this.TypeInfo = type;
1538                         this.Offset = parent.Offset + type.Offset;
1539                         this.Parent = parent;
1540                         this.Length = type.TotalLength;
1541
1542                         this.IsParameter = parent.IsParameter;
1543                         this.LocalInfo = parent.LocalInfo;
1544                         this.ParameterIndex = parent.ParameterIndex;
1545
1546                         Initialize ();
1547                 }
1548
1549                 protected void Initialize ()
1550                 {
1551                         TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1552                         if (sub_fields != null) {
1553                                 sub_info = new VariableInfo [sub_fields.Length];
1554                                 for (int i = 0; i < sub_fields.Length; i++) {
1555                                         if (sub_fields [i] != null)
1556                                                 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1557                                 }
1558                         } else
1559                                 sub_info = new VariableInfo [0];
1560                 }
1561
1562                 public VariableInfo (LocalInfo local_info, int offset)
1563                         : this (local_info.Name, local_info.VariableType, offset)
1564                 {
1565                         this.LocalInfo = local_info;
1566                         this.IsParameter = false;
1567                 }
1568
1569                 public VariableInfo (string name, Type type, int param_idx, int offset)
1570                         : this (name, type, offset)
1571                 {
1572                         this.ParameterIndex = param_idx;
1573                         this.IsParameter = true;
1574                 }
1575
1576                 public bool IsAssigned (EmitContext ec)
1577                 {
1578                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1579                 }
1580
1581                 public bool IsAssigned (EmitContext ec, Location loc)
1582                 {
1583                         if (IsAssigned (ec))
1584                                 return true;
1585
1586                         Report.Error (165, loc,
1587                                       "Use of unassigned local variable `" + Name + "'");
1588                         ec.CurrentBranching.SetAssigned (this);
1589                         return false;
1590                 }
1591
1592                 public bool IsAssigned (MyBitVector vector)
1593                 {
1594                         if (vector [Offset])
1595                                 return true;
1596
1597                         for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1598                                 if (vector [parent.Offset])
1599                                         return true;
1600
1601                         // Return unless this is a struct.
1602                         if (!TypeInfo.IsStruct)
1603                                 return false;
1604
1605                         // Ok, so each field must be assigned.
1606                         for (int i = 0; i < TypeInfo.Length; i++) {
1607                                 if (!vector [Offset + i + 1])
1608                                         return false;
1609                         }
1610
1611                         // Ok, now check all fields which are structs.
1612                         for (int i = 0; i < sub_info.Length; i++) {
1613                                 VariableInfo sinfo = sub_info [i];
1614                                 if (sinfo == null)
1615                                         continue;
1616
1617                                 if (!sinfo.IsAssigned (vector))
1618                                         return false;
1619                         }
1620
1621                         vector [Offset] = true;
1622                         return true;
1623                 }
1624
1625                 public void SetAssigned (EmitContext ec)
1626                 {
1627                         if (ec.DoFlowAnalysis)
1628                                 ec.CurrentBranching.SetAssigned (this);
1629                 }
1630
1631                 public void SetAssigned (MyBitVector vector)
1632                 {
1633                         vector [Offset] = true;
1634                 }
1635
1636                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1637                 {
1638                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1639                                 return true;
1640
1641                         Report.Error (170, loc,
1642                                       "Use of possibly unassigned field `" + name + "'");
1643                         ec.CurrentBranching.SetFieldAssigned (this, name);
1644                         return false;
1645                 }
1646
1647                 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1648                 {
1649                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1650
1651                         if (field_idx == 0)
1652                                 return true;
1653
1654                         return vector [Offset + field_idx];
1655                 }
1656
1657                 public void SetFieldAssigned (EmitContext ec, string name)
1658                 {
1659                         if (ec.DoFlowAnalysis)
1660                                 ec.CurrentBranching.SetFieldAssigned (this, name);
1661                 }
1662
1663                 public void SetFieldAssigned (MyBitVector vector, string field_name)
1664                 {
1665                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1666
1667                         if (field_idx == 0)
1668                                 return;
1669
1670                         vector [Offset + field_idx] = true;
1671                 }
1672
1673                 public VariableInfo GetSubStruct (string name)
1674                 {
1675                         TypeInfo type = TypeInfo.GetSubStruct (name);
1676
1677                         if (type == null)
1678                                 return null;
1679
1680                         return new VariableInfo (this, type);
1681                 }
1682
1683                 public override string ToString ()
1684                 {
1685                         return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1686                                               Name, TypeInfo, Offset, Length, IsParameter);
1687                 }
1688         }
1689
1690         // <summary>
1691         //   This is used by the flow code to hold the `layout' of the flow vector for
1692         //   all locals and all parameters (ie. we create one instance of this class for the
1693         //   locals and another one for the params).
1694         // </summary>
1695         public class VariableMap {
1696                 // <summary>
1697                 //   The number of variables in the map.
1698                 // </summary>
1699                 public readonly int Count;
1700
1701                 // <summary>
1702                 //   Total length of the flow vector for this map.
1703                 // <summary>
1704                 public readonly int Length;
1705
1706                 // <summary>
1707                 //   Type and name of all the variables.
1708                 //   Note that this is null for variables for which we do not need to compute
1709                 //   assignment info.
1710                 // </summary>
1711                 public readonly Type[] VariableTypes;
1712                 public readonly string[] VariableNames;
1713
1714                 VariableInfo[] map;
1715
1716                 public VariableMap (InternalParameters ip)
1717                 {
1718                         Count = ip != null ? ip.Count : 0;
1719                         map = new VariableInfo [Count];
1720                         VariableNames = new string [Count];
1721                         VariableTypes = new Type [Count];
1722                         Length = 0;
1723
1724                         for (int i = 0; i < Count; i++) {
1725                                 Parameter.Modifier mod = ip.ParameterModifier (i);
1726
1727                                 if ((mod & Parameter.Modifier.OUT) == 0)
1728                                         continue;
1729
1730                                 VariableNames [i] = ip.ParameterName (i);
1731                                 VariableTypes [i] = TypeManager.GetElementType (ip.ParameterType (i));
1732
1733                                 map [i] = new VariableInfo (VariableNames [i], VariableTypes [i], i, Length);
1734                                 Length += map [i].Length;
1735                         }
1736                 }
1737
1738                 public VariableMap (LocalInfo[] locals)
1739                         : this (null, locals)
1740                 { }
1741
1742                 public VariableMap (VariableMap parent, LocalInfo[] locals)
1743                 {
1744                         int offset = 0, start = 0;
1745                         if (parent != null) {
1746                                 offset = parent.Length;
1747                                 start = parent.Count;
1748                         }
1749
1750                         Count = locals.Length + start;
1751                         map = new VariableInfo [Count];
1752                         VariableNames = new string [Count];
1753                         VariableTypes = new Type [Count];
1754                         Length = offset;
1755
1756                         if (parent != null) {
1757                                 parent.map.CopyTo (map, 0);
1758                                 parent.VariableNames.CopyTo (VariableNames, 0);
1759                                 parent.VariableTypes.CopyTo (VariableTypes, 0);
1760                         }
1761
1762                         for (int i = start; i < Count; i++) {
1763                                 LocalInfo li = locals [i-start];
1764
1765                                 if (li.VariableType == null)
1766                                         continue;
1767
1768                                 VariableNames [i] = li.Name;
1769                                 VariableTypes [i] = li.VariableType;
1770
1771                                 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1772                                 Length += map [i].Length;
1773                         }
1774                 }
1775
1776                 // <summary>
1777                 //   Returns the VariableInfo for variable @index or null if we don't need to
1778                 //   compute assignment info for this variable.
1779                 // </summary>
1780                 public VariableInfo this [int index] {
1781                         get {
1782                                 return map [index];
1783                         }
1784                 }
1785
1786                 public override string ToString ()
1787                 {
1788                         return String.Format ("VariableMap ({0}:{1})", Count, Length);
1789                 }
1790         }
1791
1792         // <summary>
1793         //   This is a special bit vector which can inherit from another bit vector doing a
1794         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
1795         //   current one.
1796         // </summary>
1797         public class MyBitVector {
1798                 public readonly int Count;
1799                 public readonly MyBitVector InheritsFrom;
1800
1801                 bool is_dirty;
1802                 BitArray vector;
1803
1804                 public MyBitVector (int Count)
1805                         : this (null, Count)
1806                 { }
1807
1808                 public MyBitVector (MyBitVector InheritsFrom, int Count)
1809                 {
1810                         this.InheritsFrom = InheritsFrom;
1811                         this.Count = Count;
1812                 }
1813
1814                 // <summary>
1815                 //   Checks whether this bit vector has been modified.  After setting this to true,
1816                 //   we won't use the inherited vector anymore, but our own copy of it.
1817                 // </summary>
1818                 public bool IsDirty {
1819                         get {
1820                                 return is_dirty;
1821                         }
1822
1823                         set {
1824                                 if (!is_dirty)
1825                                         initialize_vector ();
1826                         }
1827                 }
1828
1829                 // <summary>
1830                 //   Get/set bit `index' in the bit vector.
1831                 // </summary>
1832                 public bool this [int index]
1833                 {
1834                         get {
1835                                 if (index > Count)
1836                                         throw new ArgumentOutOfRangeException ();
1837
1838                                 // We're doing a "copy-on-write" strategy here; as long
1839                                 // as nobody writes to the array, we can use our parent's
1840                                 // copy instead of duplicating the vector.
1841
1842                                 if (vector != null)
1843                                         return vector [index];
1844                                 else if (InheritsFrom != null) {
1845                                         BitArray inherited = InheritsFrom.Vector;
1846
1847                                         if (index < inherited.Count)
1848                                                 return inherited [index];
1849                                         else
1850                                                 return false;
1851                                 } else
1852                                         return false;
1853                         }
1854
1855                         set {
1856                                 if (index > Count)
1857                                         throw new ArgumentOutOfRangeException ();
1858
1859                                 // Only copy the vector if we're actually modifying it.
1860
1861                                 if (this [index] != value) {
1862                                         initialize_vector ();
1863
1864                                         vector [index] = value;
1865                                 }
1866                         }
1867                 }
1868
1869                 // <summary>
1870                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1871                 //   copy of the bit vector.
1872                 // </summary>
1873                 public static explicit operator BitArray (MyBitVector vector)
1874                 {
1875                         vector.initialize_vector ();
1876                         return vector.Vector;
1877                 }
1878
1879                 // <summary>
1880                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
1881                 //   different size than the current one.
1882                 // </summary>
1883                 public void Or (MyBitVector new_vector)
1884                 {
1885                         BitArray new_array = new_vector.Vector;
1886
1887                         initialize_vector ();
1888
1889                         int upper;
1890                         if (vector.Count < new_array.Count)
1891                                 upper = vector.Count;
1892                         else
1893                                 upper = new_array.Count;
1894
1895                         for (int i = 0; i < upper; i++)
1896                                 vector [i] = vector [i] | new_array [i];
1897                 }
1898
1899                 // <summary>
1900                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
1901                 //   a different size than the current one.
1902                 // </summary>
1903                 public void And (MyBitVector new_vector)
1904                 {
1905                         BitArray new_array = new_vector.Vector;
1906
1907                         initialize_vector ();
1908
1909                         int lower, upper;
1910                         if (vector.Count < new_array.Count)
1911                                 lower = upper = vector.Count;
1912                         else {
1913                                 lower = new_array.Count;
1914                                 upper = vector.Count;
1915                         }
1916
1917                         for (int i = 0; i < lower; i++)
1918                                 vector [i] = vector [i] & new_array [i];
1919
1920                         for (int i = lower; i < upper; i++)
1921                                 vector [i] = false;
1922                 }
1923
1924                 public static void And (ref MyBitVector target, MyBitVector vector)
1925                 {
1926                         if (target != null)
1927                                 target.And (vector);
1928                         else
1929                                 target = vector.Clone ();
1930                 }
1931
1932                 public static void Or (ref MyBitVector target, MyBitVector vector)
1933                 {
1934                         if (target != null)
1935                                 target.Or (vector);
1936                         else
1937                                 target = vector.Clone ();
1938                 }
1939
1940                 // <summary>
1941                 //   This does a deep copy of the bit vector.
1942                 // </summary>
1943                 public MyBitVector Clone ()
1944                 {
1945                         MyBitVector retval = new MyBitVector (Count);
1946
1947                         retval.Vector = Vector;
1948
1949                         return retval;
1950                 }
1951
1952                 BitArray Vector {
1953                         get {
1954                                 if (vector != null)
1955                                         return vector;
1956                                 else if (!is_dirty && (InheritsFrom != null))
1957                                         return InheritsFrom.Vector;
1958
1959                                 initialize_vector ();
1960
1961                                 return vector;
1962                         }
1963
1964                         set {
1965                                 initialize_vector ();
1966
1967                                 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1968                                         vector [i] = value [i];
1969                         }
1970                 }
1971
1972                 void initialize_vector ()
1973                 {
1974                         if (vector != null)
1975                                 return;
1976
1977                         vector = new BitArray (Count, false);
1978                         if (InheritsFrom != null)
1979                                 Vector = InheritsFrom.Vector;
1980
1981                         is_dirty = true;
1982                 }
1983
1984                 public override string ToString ()
1985                 {
1986                         StringBuilder sb = new StringBuilder ("{");
1987
1988                         BitArray vector = Vector;
1989                         if (!IsDirty)
1990                                 sb.Append ("=");
1991                         for (int i = 0; i < vector.Count; i++) {
1992                                 sb.Append (vector [i] ? "1" : "0");
1993                         }
1994                         
1995                         sb.Append ("}");
1996                         return sb.ToString ();
1997                 }
1998         }
1999 }