2004-08-02 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / flowanalysis.cs
1 //
2 // flowanalyis.cs: The control flow analysis code
3 //
4 // Author:
5 //   Martin Baulig (martin@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 //
9
10 using System;
11 using System.Text;
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
16
17 namespace Mono.CSharp
18 {
19         // <summary>
20         //   A new instance of this class is created every time a new block is resolved
21         //   and if there's branching in the block's control flow.
22         // </summary>
23         public abstract class FlowBranching
24         {
25                 // <summary>
26                 //   The type of a FlowBranching.
27                 // </summary>
28                 public enum BranchingType : 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                                                 if (!new_r.MayReturn && !new_r.MayThrow)
664                                                         new_r.ResetBarrier ();
665                                         }
666                                 } else if (branching.Type == BranchingType.Switch)
667                                         new_r.ResetBreaks ();
668
669                                 //
670                                 // We've now either reached the point after the branching or we will
671                                 // never get there since we always return or always throw an exception.
672                                 //
673                                 // If we can reach the point after the branching, mark all locals and
674                                 // parameters as initialized which have been initialized in all branches
675                                 // we need to look at (see above).
676                                 //
677
678                                 if ((Type == SiblingType.SwitchSection) && !new_r.IsUnreachable) {
679                                         Report.Error (163, Location,
680                                                       "Control cannot fall through from one " +
681                                                       "case label to another");
682                                         return result;
683                                 }
684
685                                 if (locals != null && result.LocalVector != null)
686                                         locals.Or (result.LocalVector);
687
688                                 if (result.ParameterVector != null)
689                                         parameters.Or (result.ParameterVector);
690
691                                 reachability.Or (new_r);
692
693                                 Report.Debug (2, "  MERGING CHILD DONE", this, result,
694                                               new_r, reachability);
695
696                                 IsDirty = true;
697
698                                 return result;
699                         }
700
701                         protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
702                                                      MyBitVector f_params)
703                         {
704                                 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
705                                         MyBitVector temp_params = f_params.Clone ();
706                                         temp_params.Or (vector.Parameters);
707                                 }
708                         }
709
710                         public void MergeFinally (FlowBranching branching, UsageVector f_vector,
711                                                   UsageVector f_origins)
712                         {
713                                 if (parameters != null) {
714                                         if (f_vector != null) {
715                                                 MergeFinally (branching, f_origins, f_vector.Parameters);
716                                                 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
717                                         } else
718                                                 MergeFinally (branching, f_origins, parameters);
719                                 }
720
721                                 if (f_vector != null && f_vector.LocalVector != null)
722                                         MyBitVector.Or (ref locals, f_vector.LocalVector);
723                         }
724
725                         // <summary>
726                         //   Tells control flow analysis that the current code position may be reached with
727                         //   a forward jump from any of the origins listed in `origin_vectors' which is a
728                         //   list of UsageVectors.
729                         //
730                         //   This is used when resolving forward gotos - in the following example, the
731                         //   variable `a' is uninitialized in line 8 becase this line may be reached via
732                         //   the goto in line 4:
733                         //
734                         //      1     int a;
735                         //
736                         //      3     if (something)
737                         //      4        goto World;
738                         //
739                         //      6     a = 5;
740                         //
741                         //      7  World:
742                         //      8     Console.WriteLine (a);
743                         //
744                         // </summary>
745                         public void MergeJumpOrigins (UsageVector o_vectors)
746                         {
747                                 Report.Debug (1, "  MERGING JUMP ORIGINS", this);
748
749                                 reachability = Reachability.Never ();
750
751                                 if (o_vectors == null)
752                                         return;
753
754                                 bool first = true;
755
756                                 for (UsageVector vector = o_vectors; vector != null;
757                                      vector = vector.Next) {
758                                         Report.Debug (1, "    MERGING JUMP ORIGIN", vector);
759
760                                         if (first) {
761                                                 if (locals != null && vector.Locals != null)
762                                                         locals.Or (vector.locals);
763                                                 
764                                                 if (parameters != null)
765                                                         parameters.Or (vector.parameters);
766                                                 first = false;
767                                         } else {
768                                                 if (locals != null && vector.Locals != null)
769                                                         locals.And (vector.locals);
770                                                 if (parameters != null)
771                                                         parameters.And (vector.parameters);
772                                         }
773                                                 
774                                         Reachability.And (ref reachability, vector.Reachability, true);
775                                 }
776
777                                 Report.Debug (1, "  MERGING JUMP ORIGINS DONE", this);
778                         }
779
780                         // <summary>
781                         //   This is used at the beginning of a finally block if there were
782                         //   any return statements in the try block or one of the catch blocks.
783                         // </summary>
784                         public void MergeFinallyOrigins (UsageVector f_origins)
785                         {
786                                 Report.Debug (1, "  MERGING FINALLY ORIGIN", this);
787
788                                 reachability = Reachability.Never ();
789
790                                 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
791                                         Report.Debug (1, "    MERGING FINALLY ORIGIN", vector);
792
793                                         if (parameters != null)
794                                                 parameters.And (vector.parameters);
795
796                                         Reachability.And (ref reachability, vector.Reachability, true);
797                                 }
798
799                                 Report.Debug (1, "  MERGING FINALLY ORIGIN DONE", this);
800                         }
801
802                         public void MergeBreakOrigins (UsageVector o_vectors)
803                         {
804                                 Report.Debug (1, "  MERGING BREAK ORIGINS", this);
805
806                                 if (o_vectors == null)
807                                         return;
808
809                                 bool first = true;
810
811                                 for (UsageVector vector = o_vectors; vector != null;
812                                      vector = vector.Next) {
813                                         Report.Debug (1, "    MERGING BREAK ORIGIN", vector);
814
815                                         if (first) {
816                                                 if (locals != null && vector.Locals != null)
817                                                         locals.Or (vector.locals);
818                                                 
819                                                 if (parameters != null)
820                                                         parameters.Or (vector.parameters);
821                                                 first = false;
822                                         } else {
823                                                 if (locals != null && vector.Locals != null)
824                                                         locals.And (vector.locals);
825                                                 if (parameters != null)
826                                                         parameters.And (vector.parameters);
827                                         }
828                                 }
829
830                                 Report.Debug (1, "  MERGING BREAK ORIGINS DONE", this);
831                         }
832
833                         public void CheckOutParameters (FlowBranching branching)
834                         {
835                                 if (parameters != null)
836                                         branching.CheckOutParameters (parameters, branching.Location);
837                         }
838
839                         // <summary>
840                         //   Performs an `or' operation on the locals and the parameters.
841                         // </summary>
842                         public void Or (UsageVector new_vector)
843                         {
844                                 IsDirty = true;
845                                 locals.Or (new_vector.locals);
846                                 if (parameters != null)
847                                         parameters.Or (new_vector.parameters);
848                         }
849
850                         // <summary>
851                         //   Performs an `and' operation on the locals.
852                         // </summary>
853                         public void AndLocals (UsageVector new_vector)
854                         {
855                                 IsDirty = true;
856                                 locals.And (new_vector.locals);
857                         }
858
859                         public bool HasParameters {
860                                 get {
861                                         return parameters != null;
862                                 }
863                         }
864
865                         public bool HasLocals {
866                                 get {
867                                         return locals != null;
868                                 }
869                         }
870
871                         // <summary>
872                         //   Returns a deep copy of the parameters.
873                         // </summary>
874                         public MyBitVector Parameters {
875                                 get {
876                                         if (parameters != null)
877                                                 return parameters.Clone ();
878                                         else
879                                                 return null;
880                                 }
881                         }
882
883                         // <summary>
884                         //   Returns a deep copy of the locals.
885                         // </summary>
886                         public MyBitVector Locals {
887                                 get {
888                                         if (locals != null)
889                                                 return locals.Clone ();
890                                         else
891                                                 return null;
892                                 }
893                         }
894
895                         public MyBitVector ParameterVector {
896                                 get {
897                                         return parameters;
898                                 }
899                         }
900
901                         public MyBitVector LocalVector {
902                                 get {
903                                         return locals;
904                                 }
905                         }
906
907                         //
908                         // Debugging stuff.
909                         //
910
911                         public override string ToString ()
912                         {
913                                 StringBuilder sb = new StringBuilder ();
914
915                                 sb.Append ("Vector (");
916                                 sb.Append (Type);
917                                 sb.Append (",");
918                                 sb.Append (id);
919                                 sb.Append (",");
920                                 sb.Append (IsDirty);
921                                 sb.Append (",");
922                                 sb.Append (reachability);
923                                 if (parameters != null) {
924                                         sb.Append (" - ");
925                                         sb.Append (parameters);
926                                 }
927                                 sb.Append (" - ");
928                                 sb.Append (locals);
929                                 sb.Append (")");
930
931                                 return sb.ToString ();
932                         }
933                 }
934
935                 // <summary>
936                 //   Creates a new flow branching which is contained in `parent'.
937                 //   You should only pass non-null for the `block' argument if this block
938                 //   introduces any new variables - in this case, we need to create a new
939                 //   usage vector with a different size than our parent's one.
940                 // </summary>
941                 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
942                                          Block block, Location loc)
943                 {
944                         Parent = parent;
945                         Block = block;
946                         Location = loc;
947                         Type = type;
948                         id = ++next_id;
949
950                         UsageVector vector;
951                         if (Block != null) {
952                                 param_map = Block.ParameterMap;
953                                 local_map = Block.LocalMap;
954
955                                 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
956                                 vector = new UsageVector (
957                                         stype, parent_vector, Block, loc,
958                                         param_map.Length, local_map.Length);
959                         } else {
960                                 param_map = Parent.param_map;
961                                 local_map = Parent.local_map;
962                                 vector = new UsageVector (
963                                         stype, Parent.CurrentUsageVector, null, loc);
964                         }
965
966                         AddSibling (vector);
967                 }
968
969                 public abstract UsageVector CurrentUsageVector {
970                         get;
971                 }                               
972
973                 // <summary>
974                 //   Creates a sibling of the current usage vector.
975                 // </summary>
976                 public virtual void CreateSibling (Block block, SiblingType type)
977                 {
978                         UsageVector vector = new UsageVector (
979                                 type, Parent.CurrentUsageVector, block, Location);
980                         AddSibling (vector);
981
982                         Report.Debug (1, "  CREATED SIBLING", CurrentUsageVector);
983                 }
984
985                 public void CreateSibling ()
986                 {
987                         CreateSibling (null, SiblingType.Conditional);
988                 }
989
990                 protected abstract void AddSibling (UsageVector uv);
991
992                 public virtual LabeledStatement LookupLabel (string name, Location loc)
993                 {
994                         if (Parent != null)
995                                 return Parent.LookupLabel (name, loc);
996
997                         Report.Error (
998                                 159, loc,
999                                 "No such label `" + name + "' in this scope");
1000                         return null;
1001                 }
1002
1003                 public abstract void Label (UsageVector origin_vectors);
1004
1005                 // <summary>
1006                 //   Check whether all `out' parameters have been assigned.
1007                 // </summary>
1008                 public void CheckOutParameters (MyBitVector parameters, Location loc)
1009                 {
1010                         for (int i = 0; i < param_map.Count; i++) {
1011                                 VariableInfo var = param_map [i];
1012
1013                                 if (var == null)
1014                                         continue;
1015
1016                                 if (var.IsAssigned (parameters))
1017                                         continue;
1018
1019                                 Report.Error (177, loc, "The out parameter `" +
1020                                               var.Name + "' must be " +
1021                                               "assigned before control leaves the current method.");
1022                         }
1023                 }
1024
1025                 protected UsageVector Merge (UsageVector sibling_list)
1026                 {
1027                         if (sibling_list.Next == null)
1028                                 return sibling_list;
1029
1030                         MyBitVector locals = null;
1031                         MyBitVector parameters = null;
1032
1033                         Reachability reachability = null;
1034
1035                         Report.Debug (2, "  MERGING SIBLINGS", this, Name);
1036
1037                         for (UsageVector child = sibling_list; child != null; child = child.Next) {
1038                                 bool do_break = (Type != BranchingType.Switch) &&
1039                                         (Type != BranchingType.Loop);
1040
1041                                 Report.Debug (2, "    MERGING SIBLING   ", child,
1042                                               child.ParameterVector, child.LocalVector,
1043                                               reachability, child.Reachability, do_break);
1044
1045                                 Reachability.And (ref reachability, child.Reachability, do_break);
1046
1047                                 // A local variable is initialized after a flow branching if it
1048                                 // has been initialized in all its branches which do neither
1049                                 // always return or always throw an exception.
1050                                 //
1051                                 // If a branch may return, but does not always return, then we
1052                                 // can treat it like a never-returning branch here: control will
1053                                 // only reach the code position after the branching if we did not
1054                                 // return here.
1055                                 //
1056                                 // It's important to distinguish between always and sometimes
1057                                 // returning branches here:
1058                                 //
1059                                 //    1   int a;
1060                                 //    2   if (something) {
1061                                 //    3      return;
1062                                 //    4      a = 5;
1063                                 //    5   }
1064                                 //    6   Console.WriteLine (a);
1065                                 //
1066                                 // The if block in lines 3-4 always returns, so we must not look
1067                                 // at the initialization of `a' in line 4 - thus it'll still be
1068                                 // uninitialized in line 6.
1069                                 //
1070                                 // On the other hand, the following is allowed:
1071                                 //
1072                                 //    1   int a;
1073                                 //    2   if (something)
1074                                 //    3      a = 5;
1075                                 //    4   else
1076                                 //    5      return;
1077                                 //    6   Console.WriteLine (a);
1078                                 //
1079                                 // Here, `a' is initialized in line 3 and we must not look at
1080                                 // line 5 since it always returns.
1081                                 // 
1082                                 bool do_break_2 = (child.Type != SiblingType.Block) &&
1083                                         (child.Type != SiblingType.SwitchSection);
1084                                 bool always_throws = (child.Type != SiblingType.Try) &&
1085                                         child.Reachability.AlwaysThrows;
1086                                 bool unreachable = always_throws ||
1087                                         (do_break_2 && child.Reachability.AlwaysBreaks) ||
1088                                         child.Reachability.AlwaysReturns ||
1089                                         child.Reachability.AlwaysHasBarrier;
1090
1091                                 Report.Debug (2, "    MERGING SIBLING #1", reachability,
1092                                               Type, child.Type, child.Reachability.IsUnreachable,
1093                                               do_break_2, always_throws, unreachable);
1094
1095                                 if (!unreachable && (child.LocalVector != null))
1096                                         MyBitVector.And (ref locals, child.LocalVector);
1097
1098                                 // An `out' parameter must be assigned in all branches which do
1099                                 // not always throw an exception.
1100                                 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
1101                                         MyBitVector.And (ref parameters, child.ParameterVector);
1102
1103                                 Report.Debug (2, "    MERGING SIBLING #2", parameters, locals);
1104                         }
1105
1106                         if (reachability == null)
1107                                 reachability = Reachability.Never ();
1108
1109                         Report.Debug (2, "  MERGING SIBLINGS DONE", parameters, locals,
1110                                       reachability, Infinite);
1111
1112                         return new UsageVector (
1113                                 parameters, locals, reachability, null, Location);
1114                 }
1115
1116                 protected abstract UsageVector Merge ();
1117
1118                 // <summary>
1119                 //   Merge a child branching.
1120                 // </summary>
1121                 public UsageVector MergeChild (FlowBranching child)
1122                 {
1123                         return CurrentUsageVector.MergeChild (child);
1124                 }
1125
1126                 // <summary>
1127                 //   Does the toplevel merging.
1128                 // </summary>
1129                 public Reachability MergeTopBlock ()
1130                 {
1131                         if ((Type != BranchingType.Block) || (Block == null))
1132                                 throw new NotSupportedException ();
1133
1134                         UsageVector vector = new UsageVector (
1135                                 SiblingType.Conditional, null, Block, Location,
1136                                 param_map.Length, local_map.Length);
1137
1138                         UsageVector result = vector.MergeChild (this);
1139
1140                         Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1141
1142                         if ((vector.Reachability.Throws != FlowReturns.Always) &&
1143                             (vector.Reachability.Barrier != FlowReturns.Always))
1144                                 CheckOutParameters (vector.Parameters, Location);
1145
1146                         return result.Reachability;
1147                 }
1148
1149                 //
1150                 // Checks whether we're in a `try' block.
1151                 //
1152                 public virtual bool InTryOrCatch (bool is_return)
1153                 {
1154                         if ((Block != null) && Block.IsDestructor)
1155                                 return true;
1156                         else if (!is_return &&
1157                             ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1158                                 return false;
1159                         else if (Parent != null)
1160                                 return Parent.InTryOrCatch (is_return);
1161                         else
1162                                 return false;
1163                 }
1164
1165                 //
1166                 // Checks whether we're in a `catch' block.
1167                 //
1168                 public virtual bool InCatch ()
1169                 {
1170                         if (Parent != null)
1171                                 return Parent.InCatch ();
1172                         else
1173                                 return false;
1174                 }
1175
1176                 //
1177                 // Checks whether we're in a `finally' block.
1178                 //
1179                 public virtual bool InFinally (bool is_return)
1180                 {
1181                         if (!is_return &&
1182                             ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1183                                 return false;
1184                         else if (Parent != null)
1185                                 return Parent.InFinally (is_return);
1186                         else
1187                                 return false;
1188                 }
1189
1190                 public virtual bool InLoop ()
1191                 {
1192                         if (Type == BranchingType.Loop)
1193                                 return true;
1194                         else if (Parent != null)
1195                                 return Parent.InLoop ();
1196                         else
1197                                 return false;
1198                 }
1199
1200                 public virtual bool InSwitch ()
1201                 {
1202                         if (Type == BranchingType.Switch)
1203                                 return true;
1204                         else if (Parent != null)
1205                                 return Parent.InSwitch ();
1206                         else
1207                                 return false;
1208                 }
1209
1210                 public virtual bool BreakCrossesTryCatchBoundary ()
1211                 {
1212                         if ((Type == BranchingType.Loop) || (Type == BranchingType.Switch))
1213                                 return false;
1214                         else if (Parent != null)
1215                                 return Parent.BreakCrossesTryCatchBoundary ();
1216                         else
1217                                 return false;
1218                 }
1219
1220                 public virtual void AddFinallyVector (UsageVector vector)
1221                 {
1222                         if (Parent != null)
1223                                 Parent.AddFinallyVector (vector);
1224                         else if ((Block == null) || !Block.IsDestructor)
1225                                 throw new NotSupportedException ();
1226                 }
1227
1228                 public virtual void AddBreakVector (UsageVector vector)
1229                 {
1230                         if (Parent != null)
1231                                 Parent.AddBreakVector (vector);
1232                         else if ((Block == null) || !Block.IsDestructor)
1233                                 throw new NotSupportedException ();
1234                 }
1235
1236                 public virtual void StealFinallyClauses (ref ArrayList list)
1237                 {
1238                         if (Parent != null)
1239                                 Parent.StealFinallyClauses (ref list);
1240                 }
1241
1242                 public bool IsAssigned (VariableInfo vi)
1243                 {
1244                         return CurrentUsageVector.IsAssigned (vi);
1245                 }
1246
1247                 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1248                 {
1249                         if (CurrentUsageVector.IsAssigned (vi))
1250                                 return true;
1251
1252                         return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1253                 }
1254
1255                 public void SetAssigned (VariableInfo vi)
1256                 {
1257                         CurrentUsageVector.SetAssigned (vi);
1258                 }
1259
1260                 public void SetFieldAssigned (VariableInfo vi, string name)
1261                 {
1262                         CurrentUsageVector.SetFieldAssigned (vi, name);
1263                 }
1264
1265                 public override string ToString ()
1266                 {
1267                         StringBuilder sb = new StringBuilder ();
1268                         sb.Append (GetType ());
1269                         sb.Append (" (");
1270
1271                         sb.Append (id);
1272                         sb.Append (",");
1273                         sb.Append (Type);
1274                         if (Block != null) {
1275                                 sb.Append (" - ");
1276                                 sb.Append (Block.ID);
1277                                 sb.Append (" - ");
1278                                 sb.Append (Block.StartLocation);
1279                         }
1280                         sb.Append (" - ");
1281                         // sb.Append (Siblings.Length);
1282                         // sb.Append (" - ");
1283                         sb.Append (CurrentUsageVector);
1284                         sb.Append (")");
1285                         return sb.ToString ();
1286                 }
1287
1288                 public string Name {
1289                         get {
1290                                 return String.Format ("{0} ({1}:{2}:{3})",
1291                                                       GetType (), id, Type, Location);
1292                         }
1293                 }
1294         }
1295
1296         public class FlowBranchingBlock : FlowBranching
1297         {
1298                 UsageVector sibling_list = null;
1299
1300                 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
1301                                            SiblingType stype, Block block, Location loc)
1302                         : base (parent, type, stype, block, loc)
1303                 { }
1304
1305                 public override UsageVector CurrentUsageVector {
1306                         get { return sibling_list; }
1307                 }
1308
1309                 protected override void AddSibling (UsageVector sibling)
1310                 {
1311                         sibling.Next = sibling_list;
1312                         sibling_list = sibling;
1313                 }
1314
1315                 public override LabeledStatement LookupLabel (string name, Location loc)
1316                 {
1317                         if (Block == null)
1318                                 return base.LookupLabel (name, loc);
1319
1320                         LabeledStatement s = Block.LookupLabel (name);
1321                         if (s != null)
1322                                 return s;
1323
1324                         return base.LookupLabel (name, loc);
1325                 }
1326
1327                 public override void Label (UsageVector origin_vectors)
1328                 {
1329                         if (!CurrentUsageVector.Reachability.IsUnreachable) {
1330                                 UsageVector vector = CurrentUsageVector.Clone ();
1331                                 vector.Next = origin_vectors;
1332                                 origin_vectors = vector;
1333                         }
1334
1335                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1336                 }
1337
1338                 protected override UsageVector Merge ()
1339                 {
1340                         return Merge (sibling_list);
1341                 }
1342         }
1343
1344         public class FlowBranchingLoop : FlowBranchingBlock
1345         {
1346                 UsageVector break_origins;
1347
1348                 public FlowBranchingLoop (FlowBranching parent, Block block, Location loc)
1349                         : base (parent, BranchingType.Loop, SiblingType.Conditional, block, loc)
1350                 { }
1351
1352                 public override void AddBreakVector (UsageVector vector)
1353                 {
1354                         vector = vector.Clone ();
1355                         vector.Next = break_origins;
1356                         break_origins = vector;
1357                 }
1358
1359                 protected override UsageVector Merge ()
1360                 {
1361                         UsageVector vector = base.Merge ();
1362
1363                         vector.MergeBreakOrigins (break_origins);
1364
1365                         return vector;
1366                 }
1367         }
1368
1369         public class FlowBranchingException : FlowBranching
1370         {
1371                 ExceptionStatement stmt;
1372                 UsageVector current_vector;
1373                 UsageVector catch_vectors;
1374                 UsageVector finally_vector;
1375                 UsageVector finally_origins;
1376                 bool emit_finally;
1377                 bool in_try;
1378
1379                 public FlowBranchingException (FlowBranching parent,
1380                                                ExceptionStatement stmt)
1381                         : base (parent, BranchingType.Exception, SiblingType.Try,
1382                                 null, stmt.loc)
1383                 {
1384                         this.stmt = stmt;
1385                         this.emit_finally = true;
1386                 }
1387
1388                 protected override void AddSibling (UsageVector sibling)
1389                 {
1390                         if (sibling.Type == SiblingType.Try) {
1391                                 sibling.Next = catch_vectors;
1392                                 catch_vectors = sibling;
1393                                 in_try = true;
1394                         } else if (sibling.Type == SiblingType.Catch) {
1395                                 sibling.Next = catch_vectors;
1396                                 catch_vectors = sibling;
1397                                 in_try = false;
1398                         } else if (sibling.Type == SiblingType.Finally) {
1399                                 sibling.MergeFinallyOrigins (finally_origins);
1400                                 finally_vector = sibling;
1401                                 in_try = false;
1402                         } else
1403                                 throw new InvalidOperationException ();
1404
1405                         current_vector = sibling;
1406                 }
1407
1408                 public override UsageVector CurrentUsageVector {
1409                         get { return current_vector; }
1410                 }
1411
1412                 public override bool InTryOrCatch (bool is_return)
1413                 {
1414                         return finally_vector == null;
1415                 }
1416
1417                 public override bool InCatch ()
1418                 {
1419                         return !in_try && (finally_vector == null);
1420                 }
1421
1422                 public override bool InFinally (bool is_return)
1423                 {
1424                         return finally_vector != null;
1425                 }
1426
1427                 public override bool BreakCrossesTryCatchBoundary ()
1428                 {
1429                         return true;
1430                 }
1431
1432                 public override void AddFinallyVector (UsageVector vector)
1433                 {
1434                         vector = vector.Clone ();
1435                         vector.Next = finally_origins;
1436                         finally_origins = vector;
1437                 }
1438
1439                 public override void StealFinallyClauses (ref ArrayList list)
1440                 {
1441                         if (list == null)
1442                                 list = new ArrayList ();
1443                         list.Add (stmt);
1444                         emit_finally = false;
1445                         base.StealFinallyClauses (ref list);
1446                 }
1447
1448                 public bool EmitFinally {
1449                         get { return emit_finally; }
1450                 }
1451
1452                 public override LabeledStatement LookupLabel (string name, Location loc)
1453                 {
1454                         if (current_vector.Block == null)
1455                                 return base.LookupLabel (name, loc);
1456
1457                         LabeledStatement s = current_vector.Block.LookupLabel (name);
1458                         if (s != null)
1459                                 return s;
1460
1461                         if (finally_vector != null) {
1462                                 Report.Error (
1463                                         157, loc, "Control can not leave the body " +
1464                                         "of the finally block");
1465                                 return null;
1466                         }
1467
1468                         return base.LookupLabel (name, loc);
1469                 }
1470
1471                 public override void Label (UsageVector origin_vectors)
1472                 {
1473                         CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1474                 }
1475
1476                 protected override UsageVector Merge ()
1477                 {
1478                         UsageVector vector = Merge (catch_vectors);
1479
1480                         vector.MergeFinally (this, finally_vector, finally_origins);
1481
1482                         return vector;
1483                 }
1484         }
1485
1486         // <summary>
1487         //   This is used by the flow analysis code to keep track of the type of local variables
1488         //   and variables.
1489         //
1490         //   The flow code uses a BitVector to keep track of whether a variable has been assigned
1491         //   or not.  This is easy for fundamental types (int, char etc.) or reference types since
1492         //   you can only assign the whole variable as such.
1493         //
1494         //   For structs, we also need to keep track of all its fields.  To do this, we allocate one
1495         //   bit for the struct itself (it's used if you assign/access the whole struct) followed by
1496         //   one bit for each of its fields.
1497         //
1498         //   This class computes this `layout' for each type.
1499         // </summary>
1500         public class TypeInfo
1501         {
1502                 public readonly Type Type;
1503
1504                 // <summary>
1505                 //   Total number of bits a variable of this type consumes in the flow vector.
1506                 // </summary>
1507                 public readonly int TotalLength;
1508
1509                 // <summary>
1510                 //   Number of bits the simple fields of a variable of this type consume
1511                 //   in the flow vector.
1512                 // </summary>
1513                 public readonly int Length;
1514
1515                 // <summary>
1516                 //   This is only used by sub-structs.
1517                 // </summary>
1518                 public readonly int Offset;
1519
1520                 // <summary>
1521                 //   If this is a struct.
1522                 // </summary>
1523                 public readonly bool IsStruct;       
1524
1525                 // <summary>
1526                 //   If this is a struct, all fields which are structs theirselves.
1527                 // </summary>
1528                 public TypeInfo[] SubStructInfo;
1529
1530                 protected readonly StructInfo struct_info;
1531                 private static Hashtable type_hash = new Hashtable ();
1532
1533                 public static TypeInfo GetTypeInfo (Type type)
1534                 {
1535                         TypeInfo info = (TypeInfo) type_hash [type];
1536                         if (info != null)
1537                                 return info;
1538
1539                         info = new TypeInfo (type);
1540                         type_hash.Add (type, info);
1541                         return info;
1542                 }
1543
1544                 public static TypeInfo GetTypeInfo (TypeContainer tc)
1545                 {
1546                         TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1547                         if (info != null)
1548                                 return info;
1549
1550                         info = new TypeInfo (tc);
1551                         type_hash.Add (tc.TypeBuilder, info);
1552                         return info;
1553                 }
1554
1555                 private TypeInfo (Type type)
1556                 {
1557                         this.Type = type;
1558
1559                         struct_info = StructInfo.GetStructInfo (type);
1560                         if (struct_info != null) {
1561                                 Length = struct_info.Length;
1562                                 TotalLength = struct_info.TotalLength;
1563                                 SubStructInfo = struct_info.StructFields;
1564                                 IsStruct = true;
1565                         } else {
1566                                 Length = 0;
1567                                 TotalLength = 1;
1568                                 IsStruct = false;
1569                         }
1570                 }
1571
1572                 private TypeInfo (TypeContainer tc)
1573                 {
1574                         this.Type = tc.TypeBuilder;
1575
1576                         struct_info = StructInfo.GetStructInfo (tc);
1577                         if (struct_info != null) {
1578                                 Length = struct_info.Length;
1579                                 TotalLength = struct_info.TotalLength;
1580                                 SubStructInfo = struct_info.StructFields;
1581                                 IsStruct = true;
1582                         } else {
1583                                 Length = 0;
1584                                 TotalLength = 1;
1585                                 IsStruct = false;
1586                         }
1587                 }
1588
1589                 protected TypeInfo (StructInfo struct_info, int offset)
1590                 {
1591                         this.struct_info = struct_info;
1592                         this.Offset = offset;
1593                         this.Length = struct_info.Length;
1594                         this.TotalLength = struct_info.TotalLength;
1595                         this.SubStructInfo = struct_info.StructFields;
1596                         this.Type = struct_info.Type;
1597                         this.IsStruct = true;
1598                 }
1599
1600                 public int GetFieldIndex (string name)
1601                 {
1602                         if (struct_info == null)
1603                                 return 0;
1604
1605                         return struct_info [name];
1606                 }
1607
1608                 public TypeInfo GetSubStruct (string name)
1609                 {
1610                         if (struct_info == null)
1611                                 return null;
1612
1613                         return struct_info.GetStructField (name);
1614                 }
1615
1616                 // <summary>
1617                 //   A struct's constructor must always assign all fields.
1618                 //   This method checks whether it actually does so.
1619                 // </summary>
1620                 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1621                 {
1622                         if (struct_info == null)
1623                                 return true;
1624
1625                         bool ok = true;
1626                         for (int i = 0; i < struct_info.Count; i++) {
1627                                 FieldInfo field = struct_info.Fields [i];
1628
1629                                 if (!branching.IsFieldAssigned (vi, field.Name)) {
1630                                         Report.Error (171, loc,
1631                                                       "Field `" + TypeManager.CSharpName (Type) +
1632                                                       "." + field.Name + "' must be fully initialized " +
1633                                                       "before control leaves the constructor");
1634                                         ok = false;
1635                                 }
1636                         }
1637
1638                         return ok;
1639                 }
1640
1641                 public override string ToString ()
1642                 {
1643                         return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1644                                               Type, Offset, Length, TotalLength);
1645                 }
1646
1647                 protected class StructInfo {
1648                         public readonly Type Type;
1649                         public readonly FieldInfo[] Fields;
1650                         public readonly TypeInfo[] StructFields;
1651                         public readonly int Count;
1652                         public readonly int CountPublic;
1653                         public readonly int CountNonPublic;
1654                         public readonly int Length;
1655                         public readonly int TotalLength;
1656                         public readonly bool HasStructFields;
1657
1658                         private static Hashtable field_type_hash = new Hashtable ();
1659                         private Hashtable struct_field_hash;
1660                         private Hashtable field_hash;
1661
1662                         protected bool InTransit = false;
1663
1664                         // Private constructor.  To save memory usage, we only need to create one instance
1665                         // of this class per struct type.
1666                         private StructInfo (Type type)
1667                         {
1668                                 this.Type = type;
1669
1670                                 field_type_hash.Add (type, this);
1671
1672                                 if (type is TypeBuilder) {
1673                                         TypeContainer tc = TypeManager.LookupTypeContainer (type);
1674
1675                                         ArrayList fields = tc.Fields;
1676
1677                                         ArrayList public_fields = new ArrayList ();
1678                                         ArrayList non_public_fields = new ArrayList ();
1679
1680                                         if (fields != null) {
1681                                                 foreach (Field field in fields) {
1682                                                         if ((field.ModFlags & Modifiers.STATIC) != 0)
1683                                                                 continue;
1684                                                         if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1685                                                                 public_fields.Add (field.FieldBuilder);
1686                                                         else
1687                                                                 non_public_fields.Add (field.FieldBuilder);
1688                                                 }
1689                                         }
1690
1691                                         CountPublic = public_fields.Count;
1692                                         CountNonPublic = non_public_fields.Count;
1693                                         Count = CountPublic + CountNonPublic;
1694
1695                                         Fields = new FieldInfo [Count];
1696                                         public_fields.CopyTo (Fields, 0);
1697                                         non_public_fields.CopyTo (Fields, CountPublic);
1698                                 } else {
1699                                         FieldInfo[] public_fields = type.GetFields (
1700                                                 BindingFlags.Instance|BindingFlags.Public);
1701                                         FieldInfo[] non_public_fields = type.GetFields (
1702                                                 BindingFlags.Instance|BindingFlags.NonPublic);
1703
1704                                         CountPublic = public_fields.Length;
1705                                         CountNonPublic = non_public_fields.Length;
1706                                         Count = CountPublic + CountNonPublic;
1707
1708                                         Fields = new FieldInfo [Count];
1709                                         public_fields.CopyTo (Fields, 0);
1710                                         non_public_fields.CopyTo (Fields, CountPublic);
1711                                 }
1712
1713                                 struct_field_hash = new Hashtable ();
1714                                 field_hash = new Hashtable ();
1715
1716                                 Length = 0;
1717                                 StructFields = new TypeInfo [Count];
1718                                 StructInfo[] sinfo = new StructInfo [Count];
1719
1720                                 InTransit = true;
1721
1722                                 for (int i = 0; i < Count; i++) {
1723                                         FieldInfo field = (FieldInfo) Fields [i];
1724
1725                                         sinfo [i] = GetStructInfo (field.FieldType);
1726                                         if (sinfo [i] == null)
1727                                                 field_hash.Add (field.Name, ++Length);
1728                                         else if (sinfo [i].InTransit) {
1729                                                 Report.Error (523, String.Format (
1730                                                                       "Struct member '{0}.{1}' of type '{2}' causes " +
1731                                                                       "a cycle in the structure layout",
1732                                                                       type, field.Name, sinfo [i].Type));
1733                                                 sinfo [i] = null;
1734                                                 return;
1735                                         }
1736                                 }
1737
1738                                 InTransit = false;
1739
1740                                 TotalLength = Length + 1;
1741                                 for (int i = 0; i < Count; i++) {
1742                                         FieldInfo field = (FieldInfo) Fields [i];
1743
1744                                         if (sinfo [i] == null)
1745                                                 continue;
1746
1747                                         field_hash.Add (field.Name, TotalLength);
1748
1749                                         HasStructFields = true;
1750                                         StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1751                                         struct_field_hash.Add (field.Name, StructFields [i]);
1752                                         TotalLength += sinfo [i].TotalLength;
1753                                 }
1754                         }
1755
1756                         public int this [string name] {
1757                                 get {
1758                                         if (field_hash.Contains (name))
1759                                                 return (int) field_hash [name];
1760                                         else
1761                                                 return 0;
1762                                 }
1763                         }
1764
1765                         public TypeInfo GetStructField (string name)
1766                         {
1767                                 return (TypeInfo) struct_field_hash [name];
1768                         }
1769
1770                         public static StructInfo GetStructInfo (Type type)
1771                         {
1772                                 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1773                                     TypeManager.IsBuiltinType (type))
1774                                         return null;
1775
1776                                 StructInfo info = (StructInfo) field_type_hash [type];
1777                                 if (info != null)
1778                                         return info;
1779
1780                                 return new StructInfo (type);
1781                         }
1782
1783                         public static StructInfo GetStructInfo (TypeContainer tc)
1784                         {
1785                                 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1786                                 if (info != null)
1787                                         return info;
1788
1789                                 return new StructInfo (tc.TypeBuilder);
1790                         }
1791                 }
1792         }
1793
1794         // <summary>
1795         //   This is used by the flow analysis code to store information about a single local variable
1796         //   or parameter.  Depending on the variable's type, we need to allocate one or more elements
1797         //   in the BitVector - if it's a fundamental or reference type, we just need to know whether
1798         //   it has been assigned or not, but for structs, we need this information for each of its fields.
1799         // </summary>
1800         public class VariableInfo {
1801                 public readonly string Name;
1802                 public readonly TypeInfo TypeInfo;
1803
1804                 // <summary>
1805                 //   The bit offset of this variable in the flow vector.
1806                 // </summary>
1807                 public readonly int Offset;
1808
1809                 // <summary>
1810                 //   The number of bits this variable needs in the flow vector.
1811                 //   The first bit always specifies whether the variable as such has been assigned while
1812                 //   the remaining bits contain this information for each of a struct's fields.
1813                 // </summary>
1814                 public readonly int Length;
1815
1816                 // <summary>
1817                 //   If this is a parameter of local variable.
1818                 // </summary>
1819                 public readonly bool IsParameter;
1820
1821                 public readonly LocalInfo LocalInfo;
1822                 public readonly int ParameterIndex;
1823
1824                 readonly VariableInfo Parent;
1825                 VariableInfo[] sub_info;
1826
1827                 protected VariableInfo (string name, Type type, int offset)
1828                 {
1829                         this.Name = name;
1830                         this.Offset = offset;
1831                         this.TypeInfo = TypeInfo.GetTypeInfo (type);
1832
1833                         Length = TypeInfo.TotalLength;
1834
1835                         Initialize ();
1836                 }
1837
1838                 protected VariableInfo (VariableInfo parent, TypeInfo type)
1839                 {
1840                         this.Name = parent.Name;
1841                         this.TypeInfo = type;
1842                         this.Offset = parent.Offset + type.Offset;
1843                         this.Parent = parent;
1844                         this.Length = type.TotalLength;
1845
1846                         this.IsParameter = parent.IsParameter;
1847                         this.LocalInfo = parent.LocalInfo;
1848                         this.ParameterIndex = parent.ParameterIndex;
1849
1850                         Initialize ();
1851                 }
1852
1853                 protected void Initialize ()
1854                 {
1855                         TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1856                         if (sub_fields != null) {
1857                                 sub_info = new VariableInfo [sub_fields.Length];
1858                                 for (int i = 0; i < sub_fields.Length; i++) {
1859                                         if (sub_fields [i] != null)
1860                                                 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1861                                 }
1862                         } else
1863                                 sub_info = new VariableInfo [0];
1864                 }
1865
1866                 public VariableInfo (LocalInfo local_info, int offset)
1867                         : this (local_info.Name, local_info.VariableType, offset)
1868                 {
1869                         this.LocalInfo = local_info;
1870                         this.IsParameter = false;
1871                 }
1872
1873                 public VariableInfo (string name, Type type, int param_idx, int offset)
1874                         : this (name, type, offset)
1875                 {
1876                         this.ParameterIndex = param_idx;
1877                         this.IsParameter = true;
1878                 }
1879
1880                 public bool IsAssigned (EmitContext ec)
1881                 {
1882                         return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1883                 }
1884
1885                 public bool IsAssigned (EmitContext ec, Location loc)
1886                 {
1887                         if (IsAssigned (ec))
1888                                 return true;
1889
1890                         Report.Error (165, loc,
1891                                       "Use of unassigned local variable `" + Name + "'");
1892                         ec.CurrentBranching.SetAssigned (this);
1893                         return false;
1894                 }
1895
1896                 public bool IsAssigned (MyBitVector vector)
1897                 {
1898                         if (vector [Offset])
1899                                 return true;
1900
1901                         for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1902                                 if (vector [parent.Offset])
1903                                         return true;
1904
1905                         // Return unless this is a struct.
1906                         if (!TypeInfo.IsStruct)
1907                                 return false;
1908
1909                         // Ok, so each field must be assigned.
1910                         for (int i = 0; i < TypeInfo.Length; i++) {
1911                                 if (!vector [Offset + i + 1])
1912                                         return false;
1913                         }
1914
1915                         // Ok, now check all fields which are structs.
1916                         for (int i = 0; i < sub_info.Length; i++) {
1917                                 VariableInfo sinfo = sub_info [i];
1918                                 if (sinfo == null)
1919                                         continue;
1920
1921                                 if (!sinfo.IsAssigned (vector))
1922                                         return false;
1923                         }
1924
1925                         vector [Offset] = true;
1926                         return true;
1927                 }
1928
1929                 public void SetAssigned (EmitContext ec)
1930                 {
1931                         if (ec.DoFlowAnalysis)
1932                                 ec.CurrentBranching.SetAssigned (this);
1933                 }
1934
1935                 public void SetAssigned (MyBitVector vector)
1936                 {
1937                         vector [Offset] = true;
1938                 }
1939
1940                 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1941                 {
1942                         if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1943                                 return true;
1944
1945                         Report.Error (170, loc,
1946                                       "Use of possibly unassigned field `" + name + "'");
1947                         ec.CurrentBranching.SetFieldAssigned (this, name);
1948                         return false;
1949                 }
1950
1951                 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1952                 {
1953                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1954
1955                         if (field_idx == 0)
1956                                 return true;
1957
1958                         return vector [Offset + field_idx];
1959                 }
1960
1961                 public void SetFieldAssigned (EmitContext ec, string name)
1962                 {
1963                         if (ec.DoFlowAnalysis)
1964                                 ec.CurrentBranching.SetFieldAssigned (this, name);
1965                 }
1966
1967                 public void SetFieldAssigned (MyBitVector vector, string field_name)
1968                 {
1969                         int field_idx = TypeInfo.GetFieldIndex (field_name);
1970
1971                         if (field_idx == 0)
1972                                 return;
1973
1974                         vector [Offset + field_idx] = true;
1975                 }
1976
1977                 public VariableInfo GetSubStruct (string name)
1978                 {
1979                         TypeInfo type = TypeInfo.GetSubStruct (name);
1980
1981                         if (type == null)
1982                                 return null;
1983
1984                         return new VariableInfo (this, type);
1985                 }
1986
1987                 public override string ToString ()
1988                 {
1989                         return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1990                                               Name, TypeInfo, Offset, Length, IsParameter);
1991                 }
1992         }
1993
1994         // <summary>
1995         //   This is used by the flow code to hold the `layout' of the flow vector for
1996         //   all locals and all parameters (ie. we create one instance of this class for the
1997         //   locals and another one for the params).
1998         // </summary>
1999         public class VariableMap {
2000                 // <summary>
2001                 //   The number of variables in the map.
2002                 // </summary>
2003                 public readonly int Count;
2004
2005                 // <summary>
2006                 //   Total length of the flow vector for this map.
2007                 // <summary>
2008                 public readonly int Length;
2009
2010                 VariableInfo[] map;
2011
2012                 public VariableMap (InternalParameters ip)
2013                 {
2014                         Count = ip != null ? ip.Count : 0;
2015                         
2016                         // Dont bother allocating anything!
2017                         if (Count == 0)
2018                                 return;
2019                         
2020                         Length = 0;
2021
2022                         for (int i = 0; i < Count; i++) {
2023                                 Parameter.Modifier mod = ip.ParameterModifier (i);
2024
2025                                 if ((mod & Parameter.Modifier.OUT) == 0)
2026                                         continue;
2027                                 
2028                                 // Dont allocate till we find an out var.
2029                                 if (map == null)
2030                                         map = new VariableInfo [Count];
2031
2032                                 map [i] = new VariableInfo (ip.ParameterName (i),
2033                                         TypeManager.GetElementType (ip.ParameterType (i)), i, Length);
2034                                 
2035                                 Length += map [i].Length;
2036                         }
2037                 }
2038
2039                 public VariableMap (LocalInfo[] locals)
2040                         : this (null, locals)
2041                 { }
2042
2043                 public VariableMap (VariableMap parent, LocalInfo[] locals)
2044                 {
2045                         int offset = 0, start = 0;
2046                         if (parent != null && parent.map != null) {
2047                                 offset = parent.Length;
2048                                 start = parent.Count;
2049                         }
2050
2051                         Count = locals.Length + start;
2052                         
2053                         if (Count == 0)
2054                                 return;
2055                         
2056                         map = new VariableInfo [Count];
2057                         Length = offset;
2058
2059                         if (parent != null && parent.map != null) {
2060                                 parent.map.CopyTo (map, 0);
2061                         }
2062
2063                         for (int i = start; i < Count; i++) {
2064                                 LocalInfo li = locals [i-start];
2065
2066                                 if (li.VariableType == null)
2067                                         continue;
2068
2069                                 map [i] = li.VariableInfo = new VariableInfo (li, Length);
2070                                 Length += map [i].Length;
2071                         }
2072                 }
2073
2074                 // <summary>
2075                 //   Returns the VariableInfo for variable @index or null if we don't need to
2076                 //   compute assignment info for this variable.
2077                 // </summary>
2078                 public VariableInfo this [int index] {
2079                         get {
2080                                 if (map == null)
2081                                         return null;
2082                                 
2083                                 return map [index];
2084                         }
2085                 }
2086
2087                 public override string ToString ()
2088                 {
2089                         return String.Format ("VariableMap ({0}:{1})", Count, Length);
2090                 }
2091         }
2092
2093         // <summary>
2094         //   This is a special bit vector which can inherit from another bit vector doing a
2095         //   copy-on-write strategy.  The inherited vector may have a smaller size than the
2096         //   current one.
2097         // </summary>
2098         public class MyBitVector {
2099                 public readonly int Count;
2100                 public readonly MyBitVector InheritsFrom;
2101
2102                 bool is_dirty;
2103                 BitArray vector;
2104
2105                 public MyBitVector (int Count)
2106                         : this (null, Count)
2107                 { }
2108
2109                 public MyBitVector (MyBitVector InheritsFrom, int Count)
2110                 {
2111                         this.InheritsFrom = InheritsFrom;
2112                         this.Count = Count;
2113                 }
2114
2115                 // <summary>
2116                 //   Checks whether this bit vector has been modified.  After setting this to true,
2117                 //   we won't use the inherited vector anymore, but our own copy of it.
2118                 // </summary>
2119                 public bool IsDirty {
2120                         get {
2121                                 return is_dirty;
2122                         }
2123
2124                         set {
2125                                 if (!is_dirty)
2126                                         initialize_vector ();
2127                         }
2128                 }
2129
2130                 // <summary>
2131                 //   Get/set bit `index' in the bit vector.
2132                 // </summary>
2133                 public bool this [int index]
2134                 {
2135                         get {
2136                                 if (index > Count)
2137                                         throw new ArgumentOutOfRangeException ();
2138
2139                                 // We're doing a "copy-on-write" strategy here; as long
2140                                 // as nobody writes to the array, we can use our parent's
2141                                 // copy instead of duplicating the vector.
2142
2143                                 if (vector != null)
2144                                         return vector [index];
2145                                 else if (InheritsFrom != null) {
2146                                         BitArray inherited = InheritsFrom.Vector;
2147
2148                                         if (index < inherited.Count)
2149                                                 return inherited [index];
2150                                         else
2151                                                 return false;
2152                                 } else
2153                                         return false;
2154                         }
2155
2156                         set {
2157                                 if (index > Count)
2158                                         throw new ArgumentOutOfRangeException ();
2159
2160                                 // Only copy the vector if we're actually modifying it.
2161
2162                                 if (this [index] != value) {
2163                                         initialize_vector ();
2164
2165                                         vector [index] = value;
2166                                 }
2167                         }
2168                 }
2169
2170                 // <summary>
2171                 //   If you explicitly convert the MyBitVector to a BitArray, you will get a deep
2172                 //   copy of the bit vector.
2173                 // </summary>
2174                 public static explicit operator BitArray (MyBitVector vector)
2175                 {
2176                         vector.initialize_vector ();
2177                         return vector.Vector;
2178                 }
2179
2180                 // <summary>
2181                 //   Performs an `or' operation on the bit vector.  The `new_vector' may have a
2182                 //   different size than the current one.
2183                 // </summary>
2184                 public void Or (MyBitVector new_vector)
2185                 {
2186                         BitArray new_array = new_vector.Vector;
2187
2188                         initialize_vector ();
2189
2190                         int upper;
2191                         if (vector.Count < new_array.Count)
2192                                 upper = vector.Count;
2193                         else
2194                                 upper = new_array.Count;
2195
2196                         for (int i = 0; i < upper; i++)
2197                                 vector [i] = vector [i] | new_array [i];
2198                 }
2199
2200                 // <summary>
2201                 //   Perfonrms an `and' operation on the bit vector.  The `new_vector' may have
2202                 //   a different size than the current one.
2203                 // </summary>
2204                 public void And (MyBitVector new_vector)
2205                 {
2206                         BitArray new_array = new_vector.Vector;
2207
2208                         initialize_vector ();
2209
2210                         int lower, upper;
2211                         if (vector.Count < new_array.Count)
2212                                 lower = upper = vector.Count;
2213                         else {
2214                                 lower = new_array.Count;
2215                                 upper = vector.Count;
2216                         }
2217
2218                         for (int i = 0; i < lower; i++)
2219                                 vector [i] = vector [i] & new_array [i];
2220
2221                         for (int i = lower; i < upper; i++)
2222                                 vector [i] = false;
2223                 }
2224
2225                 public static void And (ref MyBitVector target, MyBitVector vector)
2226                 {
2227                         if (target != null)
2228                                 target.And (vector);
2229                         else
2230                                 target = vector.Clone ();
2231                 }
2232
2233                 public static void Or (ref MyBitVector target, MyBitVector vector)
2234                 {
2235                         if (target != null)
2236                                 target.Or (vector);
2237                         else
2238                                 target = vector.Clone ();
2239                 }
2240
2241                 // <summary>
2242                 //   This does a deep copy of the bit vector.
2243                 // </summary>
2244                 public MyBitVector Clone ()
2245                 {
2246                         MyBitVector retval = new MyBitVector (Count);
2247
2248                         retval.Vector = Vector;
2249
2250                         return retval;
2251                 }
2252
2253                 BitArray Vector {
2254                         get {
2255                                 if (vector != null)
2256                                         return vector;
2257                                 else if (!is_dirty && (InheritsFrom != null))
2258                                         return InheritsFrom.Vector;
2259
2260                                 initialize_vector ();
2261
2262                                 return vector;
2263                         }
2264
2265                         set {
2266                                 initialize_vector ();
2267
2268                                 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
2269                                         vector [i] = value [i];
2270                         }
2271                 }
2272
2273                 void initialize_vector ()
2274                 {
2275                         if (vector != null)
2276                                 return;
2277                         
2278                         vector = new BitArray (Count, false);
2279                         if (InheritsFrom != null)
2280                                 Vector = InheritsFrom.Vector;
2281
2282                         is_dirty = true;
2283                 }
2284
2285                 public override string ToString ()
2286                 {
2287                         StringBuilder sb = new StringBuilder ("{");
2288
2289                         BitArray vector = Vector;
2290                         if (!IsDirty)
2291                                 sb.Append ("=");
2292                         for (int i = 0; i < vector.Count; i++) {
2293                                 sb.Append (vector [i] ? "1" : "0");
2294                         }
2295                         
2296                         sb.Append ("}");
2297                         return sb.ToString ();
2298                 }
2299         }
2300 }