2 // flowanalyis.cs: The control flow analysis code
5 // Martin Baulig (martin@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
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.
23 public abstract class FlowBranching
26 // The type of a FlowBranching.
28 public enum BranchingType {
29 // Normal (conditional or toplevel) block.
49 // The type of one sibling of a branching.
51 public enum SiblingType {
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
65 public enum FlowReturns {
68 // It can never return.
71 // This means that the block contains a conditional return statement
75 // The code always returns, ie. there's an unconditional return / break
80 public sealed class Reachability
82 FlowReturns returns, breaks, throws, barrier, reachable;
84 public FlowReturns Returns {
85 get { return returns; }
87 public FlowReturns Breaks {
88 get { return breaks; }
90 public FlowReturns Throws {
91 get { return throws; }
93 public FlowReturns Barrier {
94 get { return barrier; }
96 public FlowReturns Reachable {
97 get { return reachable; }
100 public Reachability (FlowReturns returns, FlowReturns breaks,
101 FlowReturns throws, FlowReturns barrier)
103 this.returns = returns;
104 this.breaks = breaks;
105 this.throws = throws;
106 this.barrier = barrier;
111 public Reachability Clone ()
113 Reachability cloned = new Reachability (returns, breaks, throws, barrier);
114 cloned.reachable = reachable;
118 public static void And (ref Reachability a, Reachability b, bool do_break)
126 // `break' does not "break" in a Switch or a LoopBlock
128 bool a_breaks = do_break && a.AlwaysBreaks;
129 bool b_breaks = do_break && b.AlwaysBreaks;
131 bool a_has_barrier, b_has_barrier;
134 // This is the normal case: the code following a barrier
135 // cannot be reached.
137 a_has_barrier = a.AlwaysHasBarrier;
138 b_has_barrier = b.AlwaysHasBarrier;
141 // Special case for Switch and LoopBlocks: we can reach the
142 // code after the barrier via the `break'.
144 a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
145 b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
148 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
149 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
152 // Do all code paths always return ?
154 if (a.AlwaysReturns) {
155 if (b.AlwaysReturns || b_unreachable)
156 a.returns = FlowReturns.Always;
158 a.returns = FlowReturns.Sometimes;
159 } else if (b.AlwaysReturns) {
160 if (a.AlwaysReturns || a_unreachable)
161 a.returns = FlowReturns.Always;
163 a.returns = FlowReturns.Sometimes;
164 } else if (!a.MayReturn) {
166 a.returns = FlowReturns.Sometimes;
168 a.returns = FlowReturns.Never;
169 } else if (!b.MayReturn) {
171 a.returns = FlowReturns.Sometimes;
173 a.returns = FlowReturns.Never;
176 a.breaks = AndFlowReturns (a.breaks, b.breaks);
177 a.throws = AndFlowReturns (a.throws, b.throws);
178 a.barrier = AndFlowReturns (a.barrier, b.barrier);
180 a.reachable = AndFlowReturns (a.reachable, b.reachable);
183 public static Reachability Never ()
185 return new Reachability (
186 FlowReturns.Never, FlowReturns.Never,
187 FlowReturns.Never, FlowReturns.Never);
192 if ((returns == FlowReturns.Always) || (breaks == FlowReturns.Always) ||
193 (throws == FlowReturns.Always) || (barrier == FlowReturns.Always))
194 reachable = FlowReturns.Never;
195 else if ((returns == FlowReturns.Never) && (breaks == FlowReturns.Never) &&
196 (throws == FlowReturns.Never) && (barrier == FlowReturns.Never))
197 reachable = FlowReturns.Always;
199 reachable = FlowReturns.Sometimes;
202 public bool AlwaysBreaks {
203 get { return breaks == FlowReturns.Always; }
206 public bool MayBreak {
207 get { return breaks != FlowReturns.Never; }
210 public bool AlwaysReturns {
211 get { return returns == FlowReturns.Always; }
214 public bool MayReturn {
215 get { return returns != FlowReturns.Never; }
218 public bool AlwaysThrows {
219 get { return throws == FlowReturns.Always; }
222 public bool MayThrow {
223 get { return throws != FlowReturns.Never; }
226 public bool AlwaysHasBarrier {
227 get { return barrier == FlowReturns.Always; }
230 public bool MayHaveBarrier {
231 get { return barrier != FlowReturns.Never; }
234 public bool IsUnreachable {
235 get { return reachable == FlowReturns.Never; }
238 public void SetReturns ()
240 returns = FlowReturns.Always;
244 public void SetReturnsSometimes ()
246 returns = FlowReturns.Sometimes;
250 public void SetBreaks ()
252 breaks = FlowReturns.Always;
256 public void ResetBreaks ()
258 breaks = FlowReturns.Never;
262 public void SetThrows ()
264 throws = FlowReturns.Always;
268 public void SetBarrier ()
270 barrier = FlowReturns.Always;
274 static string ShortName (FlowReturns returns)
277 case FlowReturns.Never:
279 case FlowReturns.Sometimes:
286 public override string ToString ()
288 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
289 ShortName (returns), ShortName (breaks),
290 ShortName (throws), ShortName (barrier),
291 ShortName (reachable));
295 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
298 case BranchingType.Exception:
299 return new FlowBranchingException (parent, type, block, loc);
301 case BranchingType.Switch:
302 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
304 case BranchingType.SwitchSection:
305 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
307 case BranchingType.Block:
308 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
311 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
316 // The type of this flow branching.
318 public readonly BranchingType Type;
321 // The block this branching is contained in. This may be null if it's not
322 // a top-level block and it doesn't declare any local variables.
324 public readonly Block Block;
327 // The parent of this branching or null if this is the top-block.
329 public readonly FlowBranching Parent;
332 // Start-Location of this flow branching.
334 public readonly Location Location;
337 // If this is an infinite loop.
339 public bool Infinite;
344 VariableMap param_map, local_map;
346 static int next_id = 0;
350 // Performs an `And' operation on the FlowReturns status
351 // (for instance, a block only returns Always if all its siblings
354 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
356 if (a == FlowReturns.Undefined)
360 case FlowReturns.Never:
361 if (b == FlowReturns.Never)
362 return FlowReturns.Never;
364 return FlowReturns.Sometimes;
366 case FlowReturns.Sometimes:
367 return FlowReturns.Sometimes;
369 case FlowReturns.Always:
370 if (b == FlowReturns.Always)
371 return FlowReturns.Always;
373 return FlowReturns.Sometimes;
376 throw new ArgumentException ();
381 // The vector contains a BitArray with information about which local variables
382 // and parameters are already initialized at the current code position.
384 public class UsageVector {
386 // The type of this branching.
388 public readonly SiblingType Type;
391 // Start location of this branching.
393 public readonly Location Location;
396 // If this is true, then the usage vector has been modified and must be
397 // merged when we're done with this branching.
402 // The number of parameters in this block.
404 public readonly int CountParameters;
407 // The number of locals in this block.
409 public readonly int CountLocals;
412 // If not null, then we inherit our state from this vector and do a
413 // copy-on-write. If null, then we're the first sibling in a top-level
414 // block and inherit from the empty vector.
416 public readonly UsageVector InheritsFrom;
419 // This is used to construct a list of UsageVector's.
421 public UsageVector Next;
426 MyBitVector locals, parameters;
427 Reachability reachability;
430 static int next_id = 0;
434 // Normally, you should not use any of these constructors.
436 public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
440 this.InheritsFrom = parent;
441 this.CountParameters = num_params;
442 this.CountLocals = num_locals;
444 if (parent != null) {
445 locals = new MyBitVector (parent.locals, CountLocals);
447 parameters = new MyBitVector (parent.parameters, num_params);
449 reachability = parent.Reachability.Clone ();
451 locals = new MyBitVector (null, CountLocals);
453 parameters = new MyBitVector (null, num_params);
455 reachability = Reachability.Never ();
461 public UsageVector (SiblingType type, UsageVector parent, Location loc)
462 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
465 public UsageVector (MyBitVector parameters, MyBitVector locals,
466 Reachability reachability, Location loc)
468 this.Type = SiblingType.Block;
471 this.reachability = reachability;
472 this.parameters = parameters;
473 this.locals = locals;
479 // This does a deep copy of the usage vector.
481 public UsageVector Clone ()
483 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
485 retval.locals = locals.Clone ();
486 if (parameters != null)
487 retval.parameters = parameters.Clone ();
488 retval.reachability = reachability.Clone ();
493 public bool IsAssigned (VariableInfo var)
495 if (!var.IsParameter && Reachability.AlwaysBreaks)
498 return var.IsAssigned (var.IsParameter ? parameters : locals);
501 public void SetAssigned (VariableInfo var)
503 if (!var.IsParameter && Reachability.AlwaysBreaks)
507 var.SetAssigned (var.IsParameter ? parameters : locals);
510 public bool IsFieldAssigned (VariableInfo var, string name)
512 if (!var.IsParameter && Reachability.AlwaysBreaks)
515 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
518 public void SetFieldAssigned (VariableInfo var, string name)
520 if (!var.IsParameter && Reachability.AlwaysBreaks)
524 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
527 public Reachability Reachability {
533 public void Return ()
535 if (!reachability.IsUnreachable) {
537 reachability.SetReturns ();
543 if (!reachability.IsUnreachable) {
545 reachability.SetBreaks ();
551 if (!reachability.IsUnreachable) {
553 reachability.SetThrows ();
559 if (!reachability.IsUnreachable) {
561 reachability.SetBarrier ();
566 // Merges a child branching.
568 public UsageVector MergeChild (FlowBranching branching)
570 UsageVector result = branching.Merge ();
572 Report.Debug (2, " MERGING CHILD", this, IsDirty,
573 result.ParameterVector, result.LocalVector,
574 result.Reachability, Type);
576 reachability = result.Reachability;
578 if (branching.Type == BranchingType.LoopBlock) {
579 bool may_leave_loop = reachability.MayBreak;
580 reachability.ResetBreaks ();
582 if (branching.Infinite && !may_leave_loop) {
583 if (reachability.Returns == FlowReturns.Sometimes) {
584 // If we're an infinite loop and do not break,
585 // the code after the loop can never be reached.
586 // However, if we may return from the loop,
587 // then we do always return (or stay in the
589 reachability.SetReturns ();
592 reachability.SetBarrier ();
594 if (reachability.Returns == FlowReturns.Always) {
595 // We're either finite or we may leave the loop.
596 reachability.SetReturnsSometimes ();
599 } else if (branching.Type == BranchingType.Switch)
600 reachability.ResetBreaks ();
603 // We've now either reached the point after the branching or we will
604 // never get there since we always return or always throw an exception.
606 // If we can reach the point after the branching, mark all locals and
607 // parameters as initialized which have been initialized in all branches
608 // we need to look at (see above).
611 if ((Type == SiblingType.SwitchSection) && !reachability.IsUnreachable) {
612 Report.Error (163, Location,
613 "Control cannot fall through from one " +
614 "case label to another");
618 if (result.LocalVector != null)
619 locals.Or (result.LocalVector);
621 if (result.ParameterVector != null)
622 parameters.Or (result.ParameterVector);
624 Report.Debug (2, " MERGING CHILD DONE", this);
631 protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
632 MyBitVector f_params)
634 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
635 MyBitVector temp_params = f_params.Clone ();
636 temp_params.Or (vector.Parameters);
638 branching.CheckOutParameters (temp_params, branching.Location);
642 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
643 UsageVector f_origins)
645 if (parameters != null) {
646 if (f_vector != null) {
647 MergeFinally (branching, f_origins, f_vector.Parameters);
648 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
650 MergeFinally (branching, f_origins, parameters);
653 if (f_vector != null)
654 MyBitVector.Or (ref locals, f_vector.LocalVector);
658 // Tells control flow analysis that the current code position may be reached with
659 // a forward jump from any of the origins listed in `origin_vectors' which is a
660 // list of UsageVectors.
662 // This is used when resolving forward gotos - in the following example, the
663 // variable `a' is uninitialized in line 8 becase this line may be reached via
664 // the goto in line 4:
674 // 8 Console.WriteLine (a);
677 public void MergeJumpOrigins (ICollection origin_vectors)
679 Report.Debug (1, " MERGING JUMP ORIGIN", this);
681 reachability = Reachability.Never ();
683 if (origin_vectors == null)
686 foreach (UsageVector vector in origin_vectors) {
687 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
689 locals.And (vector.locals);
690 if (parameters != null)
691 parameters.And (vector.parameters);
693 Reachability.And (ref reachability, vector.Reachability, true);
696 Report.Debug (1, " MERGING JUMP ORIGIN DONE", this);
700 // This is used at the beginning of a finally block if there were
701 // any return statements in the try block or one of the catch blocks.
703 public void MergeFinallyOrigins (ICollection finally_vectors)
705 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
708 RealBreaks = FlowReturns.Never;
711 foreach (UsageVector vector in finally_vectors) {
712 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
714 if (parameters != null)
715 parameters.And (vector.parameters);
718 RealBreaks = AndFlowReturns (Breaks, vector.Breaks);
724 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
727 public void CheckOutParameters (FlowBranching branching)
729 if (parameters != null)
730 branching.CheckOutParameters (parameters, branching.Location);
734 // Performs an `or' operation on the locals and the parameters.
736 public void Or (UsageVector new_vector)
739 locals.Or (new_vector.locals);
740 if (parameters != null)
741 parameters.Or (new_vector.parameters);
745 // Performs an `and' operation on the locals.
747 public void AndLocals (UsageVector new_vector)
750 locals.And (new_vector.locals);
753 public bool HasParameters {
755 return parameters != null;
759 public bool HasLocals {
761 return locals != null;
766 // Returns a deep copy of the parameters.
768 public MyBitVector Parameters {
770 if (parameters != null)
771 return parameters.Clone ();
778 // Returns a deep copy of the locals.
780 public MyBitVector Locals {
782 return locals.Clone ();
786 public MyBitVector ParameterVector {
792 public MyBitVector LocalVector {
802 public override string ToString ()
804 StringBuilder sb = new StringBuilder ();
806 sb.Append ("Vector (");
811 sb.Append (reachability);
812 if (parameters != null) {
814 sb.Append (parameters);
820 return sb.ToString ();
825 // Creates a new flow branching which is contained in `parent'.
826 // You should only pass non-null for the `block' argument if this block
827 // introduces any new variables - in this case, we need to create a new
828 // usage vector with a different size than our parent's one.
830 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
831 Block block, Location loc)
841 param_map = Block.ParameterMap;
842 local_map = Block.LocalMap;
844 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
845 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
847 param_map = Parent.param_map;
848 local_map = Parent.local_map;
849 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
855 public abstract UsageVector CurrentUsageVector {
860 // Creates a sibling of the current usage vector.
862 public virtual void CreateSibling (SiblingType type)
864 AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
866 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
869 protected abstract void AddSibling (UsageVector uv);
871 public abstract void Label (ArrayList origin_vectors);
874 // Check whether all `out' parameters have been assigned.
876 public void CheckOutParameters (MyBitVector parameters, Location loc)
878 for (int i = 0; i < param_map.Count; i++) {
879 VariableInfo var = param_map [i];
884 if (var.IsAssigned (parameters))
887 Report.Error (177, loc, "The out parameter `" +
888 param_map.VariableNames [i] + "' must be " +
889 "assigned before control leave the current method.");
893 protected UsageVector Merge (UsageVector sibling_list)
895 if (sibling_list.Next == null)
898 MyBitVector locals = null;
899 MyBitVector parameters = null;
901 Reachability reachability = null;
903 Report.Debug (2, " MERGING SIBLINGS", this, Name);
905 for (UsageVector child = sibling_list; child != null; child = child.Next) {
906 bool do_break = (Type != BranchingType.Switch) &&
907 (Type != BranchingType.LoopBlock);
909 Report.Debug (2, " MERGING SIBLING ", child,
910 child.Locals, child.Parameters,
911 reachability, child.Reachability, do_break);
913 Reachability.And (ref reachability, child.Reachability, do_break);
915 // A local variable is initialized after a flow branching if it
916 // has been initialized in all its branches which do neither
917 // always return or always throw an exception.
919 // If a branch may return, but does not always return, then we
920 // can treat it like a never-returning branch here: control will
921 // only reach the code position after the branching if we did not
924 // It's important to distinguish between always and sometimes
925 // returning branches here:
928 // 2 if (something) {
932 // 6 Console.WriteLine (a);
934 // The if block in lines 3-4 always returns, so we must not look
935 // at the initialization of `a' in line 4 - thus it'll still be
936 // uninitialized in line 6.
938 // On the other hand, the following is allowed:
945 // 6 Console.WriteLine (a);
947 // Here, `a' is initialized in line 3 and we must not look at
948 // line 5 since it always returns.
950 bool do_break_2 = (child.Type != SiblingType.Block) &&
951 (child.Type != SiblingType.SwitchSection);
952 bool unreachable = (do_break_2 && child.Reachability.AlwaysBreaks) ||
953 child.Reachability.AlwaysThrows ||
954 child.Reachability.AlwaysReturns ||
955 child.Reachability.AlwaysHasBarrier;
957 Report.Debug (2, " MERGING SIBLING #1", reachability,
958 Type, child.Type, child.Reachability.IsUnreachable,
959 do_break_2, unreachable);
962 MyBitVector.And (ref locals, child.LocalVector);
964 // An `out' parameter must be assigned in all branches which do
965 // not always throw an exception.
966 if ((child.Type != SiblingType.Catch) &&
967 (child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
968 MyBitVector.And (ref parameters, child.ParameterVector);
971 if (reachability == null)
972 reachability = Reachability.Never ();
974 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
975 reachability, Infinite);
977 return new UsageVector (parameters, locals, reachability, Location);
980 protected abstract UsageVector Merge ();
983 // Merge a child branching.
985 public Reachability MergeChild (FlowBranching child)
987 UsageVector result = CurrentUsageVector.MergeChild (child);
989 return result.Reachability;
993 // Does the toplevel merging.
995 public Reachability MergeTopBlock ()
997 if ((Type != BranchingType.Block) || (Block == null))
998 throw new NotSupportedException ();
1000 UsageVector vector = new UsageVector (
1001 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1003 UsageVector result = vector.MergeChild (this);
1005 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1007 if (vector.Reachability.Throws != FlowReturns.Always)
1008 CheckOutParameters (vector.Parameters, Location);
1010 return result.Reachability;
1013 public virtual bool InTryBlock ()
1016 return Parent.InTryBlock ();
1021 public virtual void AddFinallyVector (UsageVector vector)
1024 Parent.AddFinallyVector (vector);
1026 throw new NotSupportedException ();
1029 public bool IsAssigned (VariableInfo vi)
1031 return CurrentUsageVector.IsAssigned (vi);
1034 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1036 if (CurrentUsageVector.IsAssigned (vi))
1039 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1042 public void SetAssigned (VariableInfo vi)
1044 CurrentUsageVector.SetAssigned (vi);
1047 public void SetFieldAssigned (VariableInfo vi, string name)
1049 CurrentUsageVector.SetFieldAssigned (vi, name);
1052 public override string ToString ()
1054 StringBuilder sb = new StringBuilder ();
1055 sb.Append (GetType ());
1061 if (Block != null) {
1063 sb.Append (Block.ID);
1065 sb.Append (Block.StartLocation);
1068 // sb.Append (Siblings.Length);
1069 // sb.Append (" - ");
1070 sb.Append (CurrentUsageVector);
1072 return sb.ToString ();
1075 public string Name {
1077 return String.Format ("{0} ({1}:{2}:{3})",
1078 GetType (), id, Type, Location);
1083 public class FlowBranchingBlock : FlowBranching
1085 UsageVector sibling_list = null;
1087 public FlowBranchingBlock (FlowBranching parent, BranchingType type, SiblingType stype,
1088 Block block, Location loc)
1089 : base (parent, type, stype, block, loc)
1092 public override UsageVector CurrentUsageVector {
1093 get { return sibling_list; }
1096 protected override void AddSibling (UsageVector sibling)
1098 sibling.Next = sibling_list;
1099 sibling_list = sibling;
1102 public override void Label (ArrayList origin_vectors)
1104 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1107 protected override UsageVector Merge ()
1109 return Merge (sibling_list);
1113 public class FlowBranchingException : FlowBranching
1115 UsageVector current_vector;
1116 UsageVector try_vector;
1117 UsageVector catch_vectors;
1118 UsageVector finally_vector;
1119 UsageVector finally_origins;
1121 public FlowBranchingException (FlowBranching parent, BranchingType type, Block block, Location loc)
1122 : base (parent, type, SiblingType.Try, block, loc)
1125 protected override void AddSibling (UsageVector sibling)
1127 if (sibling.Type == SiblingType.Try) {
1128 try_vector = sibling;
1129 sibling.Next = catch_vectors;
1130 catch_vectors = sibling;
1131 } else if (sibling.Type == SiblingType.Catch) {
1132 sibling.Next = catch_vectors;
1133 catch_vectors = sibling;
1134 } else if (sibling.Type == SiblingType.Finally) {
1135 // sibling.MergeFinallyOrigins (finally_vectors);
1136 finally_vector = sibling;
1138 throw new InvalidOperationException ();
1140 current_vector = sibling;
1143 public override UsageVector CurrentUsageVector {
1144 get { return current_vector; }
1147 public override bool InTryBlock ()
1152 public override void AddFinallyVector (UsageVector vector)
1154 vector = vector.Clone ();
1155 vector.Next = finally_origins;
1156 finally_origins = vector;
1159 public override void Label (ArrayList origin_vectors)
1161 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1164 protected override UsageVector Merge ()
1166 UsageVector vector = Merge (catch_vectors);
1168 vector.MergeFinally (this, finally_vector, finally_origins);
1175 // This is used by the flow analysis code to keep track of the type of local variables
1178 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1179 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1180 // you can only assign the whole variable as such.
1182 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1183 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1184 // one bit for each of its fields.
1186 // This class computes this `layout' for each type.
1188 public class TypeInfo
1190 public readonly Type Type;
1193 // Total number of bits a variable of this type consumes in the flow vector.
1195 public readonly int TotalLength;
1198 // Number of bits the simple fields of a variable of this type consume
1199 // in the flow vector.
1201 public readonly int Length;
1204 // This is only used by sub-structs.
1206 public readonly int Offset;
1209 // If this is a struct.
1211 public readonly bool IsStruct;
1214 // If this is a struct, all fields which are structs theirselves.
1216 public TypeInfo[] SubStructInfo;
1218 protected readonly StructInfo struct_info;
1219 private static Hashtable type_hash = new Hashtable ();
1221 public static TypeInfo GetTypeInfo (Type type)
1223 TypeInfo info = (TypeInfo) type_hash [type];
1227 info = new TypeInfo (type);
1228 type_hash.Add (type, info);
1232 public static TypeInfo GetTypeInfo (TypeContainer tc)
1234 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1238 info = new TypeInfo (tc);
1239 type_hash.Add (tc.TypeBuilder, info);
1243 private TypeInfo (Type type)
1247 struct_info = StructInfo.GetStructInfo (type);
1248 if (struct_info != null) {
1249 Length = struct_info.Length;
1250 TotalLength = struct_info.TotalLength;
1251 SubStructInfo = struct_info.StructFields;
1260 private TypeInfo (TypeContainer tc)
1262 this.Type = tc.TypeBuilder;
1264 struct_info = StructInfo.GetStructInfo (tc);
1265 if (struct_info != null) {
1266 Length = struct_info.Length;
1267 TotalLength = struct_info.TotalLength;
1268 SubStructInfo = struct_info.StructFields;
1277 protected TypeInfo (StructInfo struct_info, int offset)
1279 this.struct_info = struct_info;
1280 this.Offset = offset;
1281 this.Length = struct_info.Length;
1282 this.TotalLength = struct_info.TotalLength;
1283 this.SubStructInfo = struct_info.StructFields;
1284 this.Type = struct_info.Type;
1285 this.IsStruct = true;
1288 public int GetFieldIndex (string name)
1290 if (struct_info == null)
1293 return struct_info [name];
1296 public TypeInfo GetSubStruct (string name)
1298 if (struct_info == null)
1301 return struct_info.GetStructField (name);
1305 // A struct's constructor must always assign all fields.
1306 // This method checks whether it actually does so.
1308 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1310 if (struct_info == null)
1314 for (int i = 0; i < struct_info.Count; i++) {
1315 FieldInfo field = struct_info.Fields [i];
1317 if (!branching.IsFieldAssigned (vi, field.Name)) {
1318 Report.Error (171, loc,
1319 "Field `" + TypeManager.CSharpName (Type) +
1320 "." + field.Name + "' must be fully initialized " +
1321 "before control leaves the constructor");
1329 public override string ToString ()
1331 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1332 Type, Offset, Length, TotalLength);
1335 protected class StructInfo {
1336 public readonly Type Type;
1337 public readonly FieldInfo[] Fields;
1338 public readonly TypeInfo[] StructFields;
1339 public readonly int Count;
1340 public readonly int CountPublic;
1341 public readonly int CountNonPublic;
1342 public readonly int Length;
1343 public readonly int TotalLength;
1344 public readonly bool HasStructFields;
1346 private static Hashtable field_type_hash = new Hashtable ();
1347 private Hashtable struct_field_hash;
1348 private Hashtable field_hash;
1350 protected bool InTransit = false;
1352 // Private constructor. To save memory usage, we only need to create one instance
1353 // of this class per struct type.
1354 private StructInfo (Type type)
1358 field_type_hash.Add (type, this);
1360 if (type is TypeBuilder) {
1361 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1363 ArrayList fields = tc.Fields;
1365 ArrayList public_fields = new ArrayList ();
1366 ArrayList non_public_fields = new ArrayList ();
1368 if (fields != null) {
1369 foreach (Field field in fields) {
1370 if ((field.ModFlags & Modifiers.STATIC) != 0)
1372 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1373 public_fields.Add (field.FieldBuilder);
1375 non_public_fields.Add (field.FieldBuilder);
1379 CountPublic = public_fields.Count;
1380 CountNonPublic = non_public_fields.Count;
1381 Count = CountPublic + CountNonPublic;
1383 Fields = new FieldInfo [Count];
1384 public_fields.CopyTo (Fields, 0);
1385 non_public_fields.CopyTo (Fields, CountPublic);
1387 FieldInfo[] public_fields = type.GetFields (
1388 BindingFlags.Instance|BindingFlags.Public);
1389 FieldInfo[] non_public_fields = type.GetFields (
1390 BindingFlags.Instance|BindingFlags.NonPublic);
1392 CountPublic = public_fields.Length;
1393 CountNonPublic = non_public_fields.Length;
1394 Count = CountPublic + CountNonPublic;
1396 Fields = new FieldInfo [Count];
1397 public_fields.CopyTo (Fields, 0);
1398 non_public_fields.CopyTo (Fields, CountPublic);
1401 struct_field_hash = new Hashtable ();
1402 field_hash = new Hashtable ();
1405 StructFields = new TypeInfo [Count];
1406 StructInfo[] sinfo = new StructInfo [Count];
1410 for (int i = 0; i < Count; i++) {
1411 FieldInfo field = (FieldInfo) Fields [i];
1413 sinfo [i] = GetStructInfo (field.FieldType);
1414 if (sinfo [i] == null)
1415 field_hash.Add (field.Name, ++Length);
1416 else if (sinfo [i].InTransit) {
1417 Report.Error (523, String.Format (
1418 "Struct member '{0}.{1}' of type '{2}' causes " +
1419 "a cycle in the structure layout",
1420 type, field.Name, sinfo [i].Type));
1428 TotalLength = Length + 1;
1429 for (int i = 0; i < Count; i++) {
1430 FieldInfo field = (FieldInfo) Fields [i];
1432 if (sinfo [i] == null)
1435 field_hash.Add (field.Name, TotalLength);
1437 HasStructFields = true;
1438 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1439 struct_field_hash.Add (field.Name, StructFields [i]);
1440 TotalLength += sinfo [i].TotalLength;
1444 public int this [string name] {
1446 if (field_hash.Contains (name))
1447 return (int) field_hash [name];
1453 public TypeInfo GetStructField (string name)
1455 return (TypeInfo) struct_field_hash [name];
1458 public static StructInfo GetStructInfo (Type type)
1460 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1461 TypeManager.IsBuiltinType (type))
1464 StructInfo info = (StructInfo) field_type_hash [type];
1468 return new StructInfo (type);
1471 public static StructInfo GetStructInfo (TypeContainer tc)
1473 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1477 return new StructInfo (tc.TypeBuilder);
1483 // This is used by the flow analysis code to store information about a single local variable
1484 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1485 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1486 // it has been assigned or not, but for structs, we need this information for each of its fields.
1488 public class VariableInfo {
1489 public readonly string Name;
1490 public readonly TypeInfo TypeInfo;
1493 // The bit offset of this variable in the flow vector.
1495 public readonly int Offset;
1498 // The number of bits this variable needs in the flow vector.
1499 // The first bit always specifies whether the variable as such has been assigned while
1500 // the remaining bits contain this information for each of a struct's fields.
1502 public readonly int Length;
1505 // If this is a parameter of local variable.
1507 public readonly bool IsParameter;
1509 public readonly LocalInfo LocalInfo;
1510 public readonly int ParameterIndex;
1512 readonly VariableInfo Parent;
1513 VariableInfo[] sub_info;
1515 protected VariableInfo (string name, Type type, int offset)
1518 this.Offset = offset;
1519 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1521 Length = TypeInfo.TotalLength;
1526 protected VariableInfo (VariableInfo parent, TypeInfo type)
1528 this.Name = parent.Name;
1529 this.TypeInfo = type;
1530 this.Offset = parent.Offset + type.Offset;
1531 this.Parent = parent;
1532 this.Length = type.TotalLength;
1534 this.IsParameter = parent.IsParameter;
1535 this.LocalInfo = parent.LocalInfo;
1536 this.ParameterIndex = parent.ParameterIndex;
1541 protected void Initialize ()
1543 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1544 if (sub_fields != null) {
1545 sub_info = new VariableInfo [sub_fields.Length];
1546 for (int i = 0; i < sub_fields.Length; i++) {
1547 if (sub_fields [i] != null)
1548 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1551 sub_info = new VariableInfo [0];
1554 public VariableInfo (LocalInfo local_info, int offset)
1555 : this (local_info.Name, local_info.VariableType, offset)
1557 this.LocalInfo = local_info;
1558 this.IsParameter = false;
1561 public VariableInfo (string name, Type type, int param_idx, int offset)
1562 : this (name, type, offset)
1564 this.ParameterIndex = param_idx;
1565 this.IsParameter = true;
1568 public bool IsAssigned (EmitContext ec)
1570 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1573 public bool IsAssigned (EmitContext ec, Location loc)
1575 if (IsAssigned (ec))
1578 Report.Error (165, loc,
1579 "Use of unassigned local variable `" + Name + "'");
1580 ec.CurrentBranching.SetAssigned (this);
1584 public bool IsAssigned (MyBitVector vector)
1586 if (vector [Offset])
1589 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1590 if (vector [parent.Offset])
1593 // Return unless this is a struct.
1594 if (!TypeInfo.IsStruct)
1597 // Ok, so each field must be assigned.
1598 for (int i = 0; i < TypeInfo.Length; i++) {
1599 if (!vector [Offset + i + 1])
1603 // Ok, now check all fields which are structs.
1604 for (int i = 0; i < sub_info.Length; i++) {
1605 VariableInfo sinfo = sub_info [i];
1609 if (!sinfo.IsAssigned (vector))
1613 vector [Offset] = true;
1617 public void SetAssigned (EmitContext ec)
1619 if (ec.DoFlowAnalysis)
1620 ec.CurrentBranching.SetAssigned (this);
1623 public void SetAssigned (MyBitVector vector)
1625 vector [Offset] = true;
1628 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1630 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1633 Report.Error (170, loc,
1634 "Use of possibly unassigned field `" + name + "'");
1635 ec.CurrentBranching.SetFieldAssigned (this, name);
1639 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1641 int field_idx = TypeInfo.GetFieldIndex (field_name);
1646 return vector [Offset + field_idx];
1649 public void SetFieldAssigned (EmitContext ec, string name)
1651 if (ec.DoFlowAnalysis)
1652 ec.CurrentBranching.SetFieldAssigned (this, name);
1655 public void SetFieldAssigned (MyBitVector vector, string field_name)
1657 int field_idx = TypeInfo.GetFieldIndex (field_name);
1662 vector [Offset + field_idx] = true;
1665 public VariableInfo GetSubStruct (string name)
1667 TypeInfo type = TypeInfo.GetSubStruct (name);
1672 return new VariableInfo (this, type);
1675 public override string ToString ()
1677 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1678 Name, TypeInfo, Offset, Length, IsParameter);
1683 // This is used by the flow code to hold the `layout' of the flow vector for
1684 // all locals and all parameters (ie. we create one instance of this class for the
1685 // locals and another one for the params).
1687 public class VariableMap {
1689 // The number of variables in the map.
1691 public readonly int Count;
1694 // Total length of the flow vector for this map.
1696 public readonly int Length;
1699 // Type and name of all the variables.
1700 // Note that this is null for variables for which we do not need to compute
1703 public readonly Type[] VariableTypes;
1704 public readonly string[] VariableNames;
1708 public VariableMap (InternalParameters ip)
1710 Count = ip != null ? ip.Count : 0;
1711 map = new VariableInfo [Count];
1712 VariableNames = new string [Count];
1713 VariableTypes = new Type [Count];
1716 for (int i = 0; i < Count; i++) {
1717 Parameter.Modifier mod = ip.ParameterModifier (i);
1719 if ((mod & Parameter.Modifier.OUT) == 0)
1722 VariableNames [i] = ip.ParameterName (i);
1723 VariableTypes [i] = TypeManager.GetElementType (ip.ParameterType (i));
1725 map [i] = new VariableInfo (VariableNames [i], VariableTypes [i], i, Length);
1726 Length += map [i].Length;
1730 public VariableMap (LocalInfo[] locals)
1731 : this (null, locals)
1734 public VariableMap (VariableMap parent, LocalInfo[] locals)
1736 int offset = 0, start = 0;
1737 if (parent != null) {
1738 offset = parent.Length;
1739 start = parent.Count;
1742 Count = locals.Length + start;
1743 map = new VariableInfo [Count];
1744 VariableNames = new string [Count];
1745 VariableTypes = new Type [Count];
1748 if (parent != null) {
1749 parent.map.CopyTo (map, 0);
1750 parent.VariableNames.CopyTo (VariableNames, 0);
1751 parent.VariableTypes.CopyTo (VariableTypes, 0);
1754 for (int i = start; i < Count; i++) {
1755 LocalInfo li = locals [i-start];
1757 if (li.VariableType == null)
1760 VariableNames [i] = li.Name;
1761 VariableTypes [i] = li.VariableType;
1763 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1764 Length += map [i].Length;
1769 // Returns the VariableInfo for variable @index or null if we don't need to
1770 // compute assignment info for this variable.
1772 public VariableInfo this [int index] {
1778 public override string ToString ()
1780 return String.Format ("VariableMap ({0}:{1})", Count, Length);
1785 // This is a special bit vector which can inherit from another bit vector doing a
1786 // copy-on-write strategy. The inherited vector may have a smaller size than the
1789 public class MyBitVector {
1790 public readonly int Count;
1791 public readonly MyBitVector InheritsFrom;
1796 public MyBitVector (int Count)
1797 : this (null, Count)
1800 public MyBitVector (MyBitVector InheritsFrom, int Count)
1802 this.InheritsFrom = InheritsFrom;
1807 // Checks whether this bit vector has been modified. After setting this to true,
1808 // we won't use the inherited vector anymore, but our own copy of it.
1810 public bool IsDirty {
1817 initialize_vector ();
1822 // Get/set bit `index' in the bit vector.
1824 public bool this [int index]
1828 throw new ArgumentOutOfRangeException ();
1830 // We're doing a "copy-on-write" strategy here; as long
1831 // as nobody writes to the array, we can use our parent's
1832 // copy instead of duplicating the vector.
1835 return vector [index];
1836 else if (InheritsFrom != null) {
1837 BitArray inherited = InheritsFrom.Vector;
1839 if (index < inherited.Count)
1840 return inherited [index];
1849 throw new ArgumentOutOfRangeException ();
1851 // Only copy the vector if we're actually modifying it.
1853 if (this [index] != value) {
1854 initialize_vector ();
1856 vector [index] = value;
1862 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1863 // copy of the bit vector.
1865 public static explicit operator BitArray (MyBitVector vector)
1867 vector.initialize_vector ();
1868 return vector.Vector;
1872 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1873 // different size than the current one.
1875 public void Or (MyBitVector new_vector)
1877 BitArray new_array = new_vector.Vector;
1879 initialize_vector ();
1882 if (vector.Count < new_array.Count)
1883 upper = vector.Count;
1885 upper = new_array.Count;
1887 for (int i = 0; i < upper; i++)
1888 vector [i] = vector [i] | new_array [i];
1892 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1893 // a different size than the current one.
1895 public void And (MyBitVector new_vector)
1897 BitArray new_array = new_vector.Vector;
1899 initialize_vector ();
1902 if (vector.Count < new_array.Count)
1903 lower = upper = vector.Count;
1905 lower = new_array.Count;
1906 upper = vector.Count;
1909 for (int i = 0; i < lower; i++)
1910 vector [i] = vector [i] & new_array [i];
1912 for (int i = lower; i < upper; i++)
1916 public static void And (ref MyBitVector target, MyBitVector vector)
1919 target.And (vector);
1921 target = vector.Clone ();
1924 public static void Or (ref MyBitVector target, MyBitVector vector)
1929 target = vector.Clone ();
1933 // This does a deep copy of the bit vector.
1935 public MyBitVector Clone ()
1937 MyBitVector retval = new MyBitVector (Count);
1939 retval.Vector = Vector;
1948 else if (!is_dirty && (InheritsFrom != null))
1949 return InheritsFrom.Vector;
1951 initialize_vector ();
1957 initialize_vector ();
1959 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1960 vector [i] = value [i];
1964 void initialize_vector ()
1969 vector = new BitArray (Count, false);
1970 if (InheritsFrom != null)
1971 Vector = InheritsFrom.Vector;
1976 public override string ToString ()
1978 StringBuilder sb = new StringBuilder ("{");
1980 BitArray vector = Vector;
1983 for (int i = 0; i < vector.Count; i++) {
1984 sb.Append (vector [i] ? "1" : "0");
1988 return sb.ToString ();