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