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 : byte {
29 // Normal (conditional or toplevel) block.
49 // The type of one sibling of a branching.
51 public enum SiblingType : byte {
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 : byte {
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;
429 static int next_id = 0;
433 // Normally, you should not use any of these constructors.
435 public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
439 this.InheritsFrom = parent;
440 this.CountParameters = num_params;
441 this.CountLocals = num_locals;
443 if (parent != null) {
445 locals = new MyBitVector (parent.locals, CountLocals);
448 parameters = new MyBitVector (parent.parameters, num_params);
450 reachability = parent.Reachability.Clone ();
453 locals = new MyBitVector (null, CountLocals);
456 parameters = new MyBitVector (null, num_params);
458 reachability = Reachability.Never ();
464 public UsageVector (SiblingType type, UsageVector parent, Location loc)
465 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
468 public UsageVector (MyBitVector parameters, MyBitVector locals,
469 Reachability reachability, Location loc)
471 this.Type = SiblingType.Block;
474 this.reachability = reachability;
475 this.parameters = parameters;
476 this.locals = locals;
482 // This does a deep copy of the usage vector.
484 public UsageVector Clone ()
486 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
488 if (retval.locals != null)
489 retval.locals = locals.Clone ();
491 if (parameters != null)
492 retval.parameters = parameters.Clone ();
494 retval.reachability = reachability.Clone ();
499 public bool IsAssigned (VariableInfo var)
501 if (!var.IsParameter && Reachability.AlwaysBreaks)
504 return var.IsAssigned (var.IsParameter ? parameters : locals);
507 public void SetAssigned (VariableInfo var)
509 if (!var.IsParameter && Reachability.AlwaysBreaks)
513 var.SetAssigned (var.IsParameter ? parameters : locals);
516 public bool IsFieldAssigned (VariableInfo var, string name)
518 if (!var.IsParameter && Reachability.AlwaysBreaks)
521 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
524 public void SetFieldAssigned (VariableInfo var, string name)
526 if (!var.IsParameter && Reachability.AlwaysBreaks)
530 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
533 public Reachability Reachability {
539 public void Return ()
541 if (!reachability.IsUnreachable) {
543 reachability.SetReturns ();
549 if (!reachability.IsUnreachable) {
551 reachability.SetBreaks ();
557 if (!reachability.IsUnreachable) {
559 reachability.SetThrows ();
565 if (!reachability.IsUnreachable) {
567 reachability.SetBarrier ();
572 // Merges a child branching.
574 public UsageVector MergeChild (FlowBranching branching)
576 UsageVector result = branching.Merge ();
578 Report.Debug (2, " MERGING CHILD", this, IsDirty,
579 result.ParameterVector, result.LocalVector,
580 result.Reachability, Type);
582 reachability = result.Reachability;
584 if (branching.Type == BranchingType.LoopBlock) {
585 bool may_leave_loop = reachability.MayBreak;
586 reachability.ResetBreaks ();
588 if (branching.Infinite && !may_leave_loop) {
589 if (reachability.Returns == FlowReturns.Sometimes) {
590 // If we're an infinite loop and do not break,
591 // the code after the loop can never be reached.
592 // However, if we may return from the loop,
593 // then we do always return (or stay in the
595 reachability.SetReturns ();
598 reachability.SetBarrier ();
600 if (reachability.Returns == FlowReturns.Always) {
601 // We're either finite or we may leave the loop.
602 reachability.SetReturnsSometimes ();
605 } else if (branching.Type == BranchingType.Switch)
606 reachability.ResetBreaks ();
609 // We've now either reached the point after the branching or we will
610 // never get there since we always return or always throw an exception.
612 // If we can reach the point after the branching, mark all locals and
613 // parameters as initialized which have been initialized in all branches
614 // we need to look at (see above).
617 if ((Type == SiblingType.SwitchSection) && !reachability.IsUnreachable) {
618 Report.Error (163, Location,
619 "Control cannot fall through from one " +
620 "case label to another");
624 if (locals != null && result.LocalVector != null)
625 locals.Or (result.LocalVector);
627 if (result.ParameterVector != null)
628 parameters.Or (result.ParameterVector);
630 Report.Debug (2, " MERGING CHILD DONE", this, result);
637 protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
638 MyBitVector f_params)
640 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
641 MyBitVector temp_params = f_params.Clone ();
642 temp_params.Or (vector.Parameters);
646 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
647 UsageVector f_origins)
649 if (parameters != null) {
650 if (f_vector != null) {
651 MergeFinally (branching, f_origins, f_vector.Parameters);
652 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
654 MergeFinally (branching, f_origins, parameters);
657 if (f_vector != null && f_vector.LocalVector != null)
658 MyBitVector.Or (ref locals, f_vector.LocalVector);
662 // Tells control flow analysis that the current code position may be reached with
663 // a forward jump from any of the origins listed in `origin_vectors' which is a
664 // list of UsageVectors.
666 // This is used when resolving forward gotos - in the following example, the
667 // variable `a' is uninitialized in line 8 becase this line may be reached via
668 // the goto in line 4:
678 // 8 Console.WriteLine (a);
681 public void MergeJumpOrigins (ICollection origin_vectors)
683 Report.Debug (1, " MERGING JUMP ORIGINS", this);
685 reachability = Reachability.Never ();
687 if (origin_vectors == null)
692 foreach (UsageVector vector in origin_vectors) {
693 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
696 if (locals != null && vector.Locals != null)
697 locals.Or (vector.locals);
699 if (parameters != null)
700 parameters.Or (vector.parameters);
703 if (locals != null && vector.Locals != null)
704 locals.And (vector.locals);
705 if (parameters != null)
706 parameters.And (vector.parameters);
709 Reachability.And (ref reachability, vector.Reachability, true);
712 Report.Debug (1, " MERGING JUMP ORIGINS DONE", this);
716 // This is used at the beginning of a finally block if there were
717 // any return statements in the try block or one of the catch blocks.
719 public void MergeFinallyOrigins (UsageVector f_origins)
721 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
723 reachability = Reachability.Never ();
725 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
726 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
728 if (parameters != null)
729 parameters.And (vector.parameters);
731 Reachability.And (ref reachability, vector.Reachability, true);
734 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
737 public void CheckOutParameters (FlowBranching branching)
739 if (parameters != null)
740 branching.CheckOutParameters (parameters, branching.Location);
744 // Performs an `or' operation on the locals and the parameters.
746 public void Or (UsageVector new_vector)
749 locals.Or (new_vector.locals);
750 if (parameters != null)
751 parameters.Or (new_vector.parameters);
755 // Performs an `and' operation on the locals.
757 public void AndLocals (UsageVector new_vector)
760 locals.And (new_vector.locals);
763 public bool HasParameters {
765 return parameters != null;
769 public bool HasLocals {
771 return locals != null;
776 // Returns a deep copy of the parameters.
778 public MyBitVector Parameters {
780 if (parameters != null)
781 return parameters.Clone ();
788 // Returns a deep copy of the locals.
790 public MyBitVector Locals {
793 return locals.Clone ();
799 public MyBitVector ParameterVector {
805 public MyBitVector LocalVector {
815 public override string ToString ()
817 StringBuilder sb = new StringBuilder ();
819 sb.Append ("Vector (");
824 sb.Append (reachability);
825 if (parameters != null) {
827 sb.Append (parameters);
833 return sb.ToString ();
838 // Creates a new flow branching which is contained in `parent'.
839 // You should only pass non-null for the `block' argument if this block
840 // introduces any new variables - in this case, we need to create a new
841 // usage vector with a different size than our parent's one.
843 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
844 Block block, Location loc)
854 param_map = Block.ParameterMap;
855 local_map = Block.LocalMap;
857 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
858 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
862 param_map = Parent.param_map;
863 local_map = Parent.local_map;
864 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
870 public abstract UsageVector CurrentUsageVector {
875 // Creates a sibling of the current usage vector.
877 public virtual void CreateSibling (SiblingType type)
879 AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
881 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
884 protected abstract void AddSibling (UsageVector uv);
886 public abstract void Label (ArrayList origin_vectors);
889 // Check whether all `out' parameters have been assigned.
891 public void CheckOutParameters (MyBitVector parameters, Location loc)
893 for (int i = 0; i < param_map.Count; i++) {
894 VariableInfo var = param_map [i];
899 if (var.IsAssigned (parameters))
902 Report.Error (177, loc, "The out parameter `" +
903 var.Name + "' must be " +
904 "assigned before control leave the current method.");
908 protected UsageVector Merge (UsageVector sibling_list)
910 if (sibling_list.Next == null)
913 MyBitVector locals = null;
914 MyBitVector parameters = null;
916 Reachability reachability = null;
918 Report.Debug (2, " MERGING SIBLINGS", this, Name);
920 for (UsageVector child = sibling_list; child != null; child = child.Next) {
921 bool do_break = (Type != BranchingType.Switch) &&
922 (Type != BranchingType.LoopBlock);
924 Report.Debug (2, " MERGING SIBLING ", child,
925 child.ParameterVector, child.LocalVector,
926 reachability, child.Reachability, do_break);
928 Reachability.And (ref reachability, child.Reachability, do_break);
930 // A local variable is initialized after a flow branching if it
931 // has been initialized in all its branches which do neither
932 // always return or always throw an exception.
934 // If a branch may return, but does not always return, then we
935 // can treat it like a never-returning branch here: control will
936 // only reach the code position after the branching if we did not
939 // It's important to distinguish between always and sometimes
940 // returning branches here:
943 // 2 if (something) {
947 // 6 Console.WriteLine (a);
949 // The if block in lines 3-4 always returns, so we must not look
950 // at the initialization of `a' in line 4 - thus it'll still be
951 // uninitialized in line 6.
953 // On the other hand, the following is allowed:
960 // 6 Console.WriteLine (a);
962 // Here, `a' is initialized in line 3 and we must not look at
963 // line 5 since it always returns.
965 bool do_break_2 = (child.Type != SiblingType.Block) &&
966 (child.Type != SiblingType.SwitchSection);
967 bool unreachable = (do_break_2 && child.Reachability.AlwaysBreaks) ||
968 child.Reachability.AlwaysThrows ||
969 child.Reachability.AlwaysReturns ||
970 child.Reachability.AlwaysHasBarrier;
972 Report.Debug (2, " MERGING SIBLING #1", reachability,
973 Type, child.Type, child.Reachability.IsUnreachable,
974 do_break_2, unreachable);
976 if (!unreachable && (child.LocalVector != null))
977 MyBitVector.And (ref locals, child.LocalVector);
979 // An `out' parameter must be assigned in all branches which do
980 // not always throw an exception.
981 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
982 MyBitVector.And (ref parameters, child.ParameterVector);
984 Report.Debug (2, " MERGING SIBLING #2", parameters, locals);
987 if (reachability == null)
988 reachability = Reachability.Never ();
990 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
991 reachability, Infinite);
993 return new UsageVector (parameters, locals, reachability, Location);
996 protected abstract UsageVector Merge ();
999 // Merge a child branching.
1001 public UsageVector MergeChild (FlowBranching child)
1003 return CurrentUsageVector.MergeChild (child);
1007 // Does the toplevel merging.
1009 public Reachability MergeTopBlock ()
1011 if ((Type != BranchingType.Block) || (Block == null))
1012 throw new NotSupportedException ();
1014 UsageVector vector = new UsageVector (
1015 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1017 UsageVector result = vector.MergeChild (this);
1019 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1021 if (vector.Reachability.Throws != FlowReturns.Always)
1022 CheckOutParameters (vector.Parameters, Location);
1024 return result.Reachability;
1027 public virtual bool InTryBlock ()
1030 return Parent.InTryBlock ();
1035 public virtual void AddFinallyVector (UsageVector vector)
1038 Parent.AddFinallyVector (vector);
1040 throw new NotSupportedException ();
1043 public bool IsAssigned (VariableInfo vi)
1045 return CurrentUsageVector.IsAssigned (vi);
1048 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1050 if (CurrentUsageVector.IsAssigned (vi))
1053 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1056 public void SetAssigned (VariableInfo vi)
1058 CurrentUsageVector.SetAssigned (vi);
1061 public void SetFieldAssigned (VariableInfo vi, string name)
1063 CurrentUsageVector.SetFieldAssigned (vi, name);
1066 public override string ToString ()
1068 StringBuilder sb = new StringBuilder ();
1069 sb.Append (GetType ());
1075 if (Block != null) {
1077 sb.Append (Block.ID);
1079 sb.Append (Block.StartLocation);
1082 // sb.Append (Siblings.Length);
1083 // sb.Append (" - ");
1084 sb.Append (CurrentUsageVector);
1086 return sb.ToString ();
1089 public string Name {
1091 return String.Format ("{0} ({1}:{2}:{3})",
1092 GetType (), id, Type, Location);
1097 public class FlowBranchingBlock : FlowBranching
1099 UsageVector sibling_list = null;
1101 public FlowBranchingBlock (FlowBranching parent, BranchingType type, SiblingType stype,
1102 Block block, Location loc)
1103 : base (parent, type, stype, block, loc)
1106 public override UsageVector CurrentUsageVector {
1107 get { return sibling_list; }
1110 protected override void AddSibling (UsageVector sibling)
1112 sibling.Next = sibling_list;
1113 sibling_list = sibling;
1116 public override void Label (ArrayList origin_vectors)
1118 if (!CurrentUsageVector.Reachability.IsUnreachable) {
1119 if (origin_vectors == null)
1120 origin_vectors = new ArrayList (1);
1121 origin_vectors.Add (CurrentUsageVector.Clone ());
1124 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1127 protected override UsageVector Merge ()
1129 return Merge (sibling_list);
1133 public class FlowBranchingException : FlowBranching
1135 UsageVector current_vector;
1136 UsageVector catch_vectors;
1137 UsageVector finally_vector;
1138 UsageVector finally_origins;
1140 public FlowBranchingException (FlowBranching parent, BranchingType type, Block block, Location loc)
1141 : base (parent, type, SiblingType.Try, block, loc)
1144 protected override void AddSibling (UsageVector sibling)
1146 if (sibling.Type == SiblingType.Try) {
1147 sibling.Next = catch_vectors;
1148 catch_vectors = sibling;
1149 } else if (sibling.Type == SiblingType.Catch) {
1150 sibling.Next = catch_vectors;
1151 catch_vectors = sibling;
1152 } else if (sibling.Type == SiblingType.Finally) {
1153 sibling.MergeFinallyOrigins (finally_origins);
1154 finally_vector = sibling;
1156 throw new InvalidOperationException ();
1158 current_vector = sibling;
1161 public override UsageVector CurrentUsageVector {
1162 get { return current_vector; }
1165 public override bool InTryBlock ()
1170 public override void AddFinallyVector (UsageVector vector)
1172 vector = vector.Clone ();
1173 vector.Next = finally_origins;
1174 finally_origins = vector;
1177 public override void Label (ArrayList origin_vectors)
1179 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1182 protected override UsageVector Merge ()
1184 UsageVector vector = Merge (catch_vectors);
1186 vector.MergeFinally (this, finally_vector, finally_origins);
1193 // This is used by the flow analysis code to keep track of the type of local variables
1196 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1197 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1198 // you can only assign the whole variable as such.
1200 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1201 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1202 // one bit for each of its fields.
1204 // This class computes this `layout' for each type.
1206 public class TypeInfo
1208 public readonly Type Type;
1211 // Total number of bits a variable of this type consumes in the flow vector.
1213 public readonly int TotalLength;
1216 // Number of bits the simple fields of a variable of this type consume
1217 // in the flow vector.
1219 public readonly int Length;
1222 // This is only used by sub-structs.
1224 public readonly int Offset;
1227 // If this is a struct.
1229 public readonly bool IsStruct;
1232 // If this is a struct, all fields which are structs theirselves.
1234 public TypeInfo[] SubStructInfo;
1236 protected readonly StructInfo struct_info;
1237 private static Hashtable type_hash = new Hashtable ();
1239 public static TypeInfo GetTypeInfo (Type type)
1241 TypeInfo info = (TypeInfo) type_hash [type];
1245 info = new TypeInfo (type);
1246 type_hash.Add (type, info);
1250 public static TypeInfo GetTypeInfo (TypeContainer tc)
1252 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1256 info = new TypeInfo (tc);
1257 type_hash.Add (tc.TypeBuilder, info);
1261 private TypeInfo (Type type)
1265 struct_info = StructInfo.GetStructInfo (type);
1266 if (struct_info != null) {
1267 Length = struct_info.Length;
1268 TotalLength = struct_info.TotalLength;
1269 SubStructInfo = struct_info.StructFields;
1278 private TypeInfo (TypeContainer tc)
1280 this.Type = tc.TypeBuilder;
1282 struct_info = StructInfo.GetStructInfo (tc);
1283 if (struct_info != null) {
1284 Length = struct_info.Length;
1285 TotalLength = struct_info.TotalLength;
1286 SubStructInfo = struct_info.StructFields;
1295 protected TypeInfo (StructInfo struct_info, int offset)
1297 this.struct_info = struct_info;
1298 this.Offset = offset;
1299 this.Length = struct_info.Length;
1300 this.TotalLength = struct_info.TotalLength;
1301 this.SubStructInfo = struct_info.StructFields;
1302 this.Type = struct_info.Type;
1303 this.IsStruct = true;
1306 public int GetFieldIndex (string name)
1308 if (struct_info == null)
1311 return struct_info [name];
1314 public TypeInfo GetSubStruct (string name)
1316 if (struct_info == null)
1319 return struct_info.GetStructField (name);
1323 // A struct's constructor must always assign all fields.
1324 // This method checks whether it actually does so.
1326 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1328 if (struct_info == null)
1332 for (int i = 0; i < struct_info.Count; i++) {
1333 FieldInfo field = struct_info.Fields [i];
1335 if (!branching.IsFieldAssigned (vi, field.Name)) {
1336 Report.Error (171, loc,
1337 "Field `" + TypeManager.CSharpName (Type) +
1338 "." + field.Name + "' must be fully initialized " +
1339 "before control leaves the constructor");
1347 public override string ToString ()
1349 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1350 Type, Offset, Length, TotalLength);
1353 protected class StructInfo {
1354 public readonly Type Type;
1355 public readonly FieldInfo[] Fields;
1356 public readonly TypeInfo[] StructFields;
1357 public readonly int Count;
1358 public readonly int CountPublic;
1359 public readonly int CountNonPublic;
1360 public readonly int Length;
1361 public readonly int TotalLength;
1362 public readonly bool HasStructFields;
1364 private static Hashtable field_type_hash = new Hashtable ();
1365 private Hashtable struct_field_hash;
1366 private Hashtable field_hash;
1368 protected bool InTransit = false;
1370 // Private constructor. To save memory usage, we only need to create one instance
1371 // of this class per struct type.
1372 private StructInfo (Type type)
1376 field_type_hash.Add (type, this);
1378 if (type is TypeBuilder) {
1379 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1381 ArrayList fields = tc.Fields;
1383 ArrayList public_fields = new ArrayList ();
1384 ArrayList non_public_fields = new ArrayList ();
1386 if (fields != null) {
1387 foreach (Field field in fields) {
1388 if ((field.ModFlags & Modifiers.STATIC) != 0)
1390 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1391 public_fields.Add (field.FieldBuilder);
1393 non_public_fields.Add (field.FieldBuilder);
1397 CountPublic = public_fields.Count;
1398 CountNonPublic = non_public_fields.Count;
1399 Count = CountPublic + CountNonPublic;
1401 Fields = new FieldInfo [Count];
1402 public_fields.CopyTo (Fields, 0);
1403 non_public_fields.CopyTo (Fields, CountPublic);
1405 FieldInfo[] public_fields = type.GetFields (
1406 BindingFlags.Instance|BindingFlags.Public);
1407 FieldInfo[] non_public_fields = type.GetFields (
1408 BindingFlags.Instance|BindingFlags.NonPublic);
1410 CountPublic = public_fields.Length;
1411 CountNonPublic = non_public_fields.Length;
1412 Count = CountPublic + CountNonPublic;
1414 Fields = new FieldInfo [Count];
1415 public_fields.CopyTo (Fields, 0);
1416 non_public_fields.CopyTo (Fields, CountPublic);
1419 struct_field_hash = new Hashtable ();
1420 field_hash = new Hashtable ();
1423 StructFields = new TypeInfo [Count];
1424 StructInfo[] sinfo = new StructInfo [Count];
1428 for (int i = 0; i < Count; i++) {
1429 FieldInfo field = (FieldInfo) Fields [i];
1431 sinfo [i] = GetStructInfo (field.FieldType);
1432 if (sinfo [i] == null)
1433 field_hash.Add (field.Name, ++Length);
1434 else if (sinfo [i].InTransit) {
1435 Report.Error (523, String.Format (
1436 "Struct member '{0}.{1}' of type '{2}' causes " +
1437 "a cycle in the structure layout",
1438 type, field.Name, sinfo [i].Type));
1446 TotalLength = Length + 1;
1447 for (int i = 0; i < Count; i++) {
1448 FieldInfo field = (FieldInfo) Fields [i];
1450 if (sinfo [i] == null)
1453 field_hash.Add (field.Name, TotalLength);
1455 HasStructFields = true;
1456 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1457 struct_field_hash.Add (field.Name, StructFields [i]);
1458 TotalLength += sinfo [i].TotalLength;
1462 public int this [string name] {
1464 if (field_hash.Contains (name))
1465 return (int) field_hash [name];
1471 public TypeInfo GetStructField (string name)
1473 return (TypeInfo) struct_field_hash [name];
1476 public static StructInfo GetStructInfo (Type type)
1478 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1479 TypeManager.IsBuiltinType (type))
1482 StructInfo info = (StructInfo) field_type_hash [type];
1486 return new StructInfo (type);
1489 public static StructInfo GetStructInfo (TypeContainer tc)
1491 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1495 return new StructInfo (tc.TypeBuilder);
1501 // This is used by the flow analysis code to store information about a single local variable
1502 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1503 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1504 // it has been assigned or not, but for structs, we need this information for each of its fields.
1506 public class VariableInfo {
1507 public readonly string Name;
1508 public readonly TypeInfo TypeInfo;
1511 // The bit offset of this variable in the flow vector.
1513 public readonly int Offset;
1516 // The number of bits this variable needs in the flow vector.
1517 // The first bit always specifies whether the variable as such has been assigned while
1518 // the remaining bits contain this information for each of a struct's fields.
1520 public readonly int Length;
1523 // If this is a parameter of local variable.
1525 public readonly bool IsParameter;
1527 public readonly LocalInfo LocalInfo;
1528 public readonly int ParameterIndex;
1530 readonly VariableInfo Parent;
1531 VariableInfo[] sub_info;
1533 protected VariableInfo (string name, Type type, int offset)
1536 this.Offset = offset;
1537 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1539 Length = TypeInfo.TotalLength;
1544 protected VariableInfo (VariableInfo parent, TypeInfo type)
1546 this.Name = parent.Name;
1547 this.TypeInfo = type;
1548 this.Offset = parent.Offset + type.Offset;
1549 this.Parent = parent;
1550 this.Length = type.TotalLength;
1552 this.IsParameter = parent.IsParameter;
1553 this.LocalInfo = parent.LocalInfo;
1554 this.ParameterIndex = parent.ParameterIndex;
1559 protected void Initialize ()
1561 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1562 if (sub_fields != null) {
1563 sub_info = new VariableInfo [sub_fields.Length];
1564 for (int i = 0; i < sub_fields.Length; i++) {
1565 if (sub_fields [i] != null)
1566 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1569 sub_info = new VariableInfo [0];
1572 public VariableInfo (LocalInfo local_info, int offset)
1573 : this (local_info.Name, local_info.VariableType, offset)
1575 this.LocalInfo = local_info;
1576 this.IsParameter = false;
1579 public VariableInfo (string name, Type type, int param_idx, int offset)
1580 : this (name, type, offset)
1582 this.ParameterIndex = param_idx;
1583 this.IsParameter = true;
1586 public bool IsAssigned (EmitContext ec)
1588 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1591 public bool IsAssigned (EmitContext ec, Location loc)
1593 if (IsAssigned (ec))
1596 Report.Error (165, loc,
1597 "Use of unassigned local variable `" + Name + "'");
1598 ec.CurrentBranching.SetAssigned (this);
1602 public bool IsAssigned (MyBitVector vector)
1604 if (vector [Offset])
1607 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1608 if (vector [parent.Offset])
1611 // Return unless this is a struct.
1612 if (!TypeInfo.IsStruct)
1615 // Ok, so each field must be assigned.
1616 for (int i = 0; i < TypeInfo.Length; i++) {
1617 if (!vector [Offset + i + 1])
1621 // Ok, now check all fields which are structs.
1622 for (int i = 0; i < sub_info.Length; i++) {
1623 VariableInfo sinfo = sub_info [i];
1627 if (!sinfo.IsAssigned (vector))
1631 vector [Offset] = true;
1635 public void SetAssigned (EmitContext ec)
1637 if (ec.DoFlowAnalysis)
1638 ec.CurrentBranching.SetAssigned (this);
1641 public void SetAssigned (MyBitVector vector)
1643 vector [Offset] = true;
1646 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1648 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1651 Report.Error (170, loc,
1652 "Use of possibly unassigned field `" + name + "'");
1653 ec.CurrentBranching.SetFieldAssigned (this, name);
1657 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1659 int field_idx = TypeInfo.GetFieldIndex (field_name);
1664 return vector [Offset + field_idx];
1667 public void SetFieldAssigned (EmitContext ec, string name)
1669 if (ec.DoFlowAnalysis)
1670 ec.CurrentBranching.SetFieldAssigned (this, name);
1673 public void SetFieldAssigned (MyBitVector vector, string field_name)
1675 int field_idx = TypeInfo.GetFieldIndex (field_name);
1680 vector [Offset + field_idx] = true;
1683 public VariableInfo GetSubStruct (string name)
1685 TypeInfo type = TypeInfo.GetSubStruct (name);
1690 return new VariableInfo (this, type);
1693 public override string ToString ()
1695 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1696 Name, TypeInfo, Offset, Length, IsParameter);
1701 // This is used by the flow code to hold the `layout' of the flow vector for
1702 // all locals and all parameters (ie. we create one instance of this class for the
1703 // locals and another one for the params).
1705 public class VariableMap {
1707 // The number of variables in the map.
1709 public readonly int Count;
1712 // Total length of the flow vector for this map.
1714 public readonly int Length;
1718 public VariableMap (InternalParameters ip)
1720 Count = ip != null ? ip.Count : 0;
1722 // Dont bother allocating anything!
1728 for (int i = 0; i < Count; i++) {
1729 Parameter.Modifier mod = ip.ParameterModifier (i);
1731 if ((mod & Parameter.Modifier.OUT) == 0)
1734 // Dont allocate till we find an out var.
1736 map = new VariableInfo [Count];
1738 map [i] = new VariableInfo (ip.ParameterName (i),
1739 TypeManager.GetElementType (ip.ParameterType (i)), i, Length);
1741 Length += map [i].Length;
1745 public VariableMap (LocalInfo[] locals)
1746 : this (null, locals)
1749 public VariableMap (VariableMap parent, LocalInfo[] locals)
1751 int offset = 0, start = 0;
1752 if (parent != null && parent.map != null) {
1753 offset = parent.Length;
1754 start = parent.Count;
1757 Count = locals.Length + start;
1762 map = new VariableInfo [Count];
1765 if (parent != null && parent.map != null) {
1766 parent.map.CopyTo (map, 0);
1769 for (int i = start; i < Count; i++) {
1770 LocalInfo li = locals [i-start];
1772 if (li.VariableType == null)
1775 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1776 Length += map [i].Length;
1781 // Returns the VariableInfo for variable @index or null if we don't need to
1782 // compute assignment info for this variable.
1784 public VariableInfo this [int index] {
1793 public override string ToString ()
1795 return String.Format ("VariableMap ({0}:{1})", Count, Length);
1800 // This is a special bit vector which can inherit from another bit vector doing a
1801 // copy-on-write strategy. The inherited vector may have a smaller size than the
1804 public class MyBitVector {
1805 public readonly int Count;
1806 public readonly MyBitVector InheritsFrom;
1811 public MyBitVector (int Count)
1812 : this (null, Count)
1815 public MyBitVector (MyBitVector InheritsFrom, int Count)
1817 this.InheritsFrom = InheritsFrom;
1822 // Checks whether this bit vector has been modified. After setting this to true,
1823 // we won't use the inherited vector anymore, but our own copy of it.
1825 public bool IsDirty {
1832 initialize_vector ();
1837 // Get/set bit `index' in the bit vector.
1839 public bool this [int index]
1843 throw new ArgumentOutOfRangeException ();
1845 // We're doing a "copy-on-write" strategy here; as long
1846 // as nobody writes to the array, we can use our parent's
1847 // copy instead of duplicating the vector.
1850 return vector [index];
1851 else if (InheritsFrom != null) {
1852 BitArray inherited = InheritsFrom.Vector;
1854 if (index < inherited.Count)
1855 return inherited [index];
1864 throw new ArgumentOutOfRangeException ();
1866 // Only copy the vector if we're actually modifying it.
1868 if (this [index] != value) {
1869 initialize_vector ();
1871 vector [index] = value;
1877 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1878 // copy of the bit vector.
1880 public static explicit operator BitArray (MyBitVector vector)
1882 vector.initialize_vector ();
1883 return vector.Vector;
1887 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1888 // different size than the current one.
1890 public void Or (MyBitVector new_vector)
1892 BitArray new_array = new_vector.Vector;
1894 initialize_vector ();
1897 if (vector.Count < new_array.Count)
1898 upper = vector.Count;
1900 upper = new_array.Count;
1902 for (int i = 0; i < upper; i++)
1903 vector [i] = vector [i] | new_array [i];
1907 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1908 // a different size than the current one.
1910 public void And (MyBitVector new_vector)
1912 BitArray new_array = new_vector.Vector;
1914 initialize_vector ();
1917 if (vector.Count < new_array.Count)
1918 lower = upper = vector.Count;
1920 lower = new_array.Count;
1921 upper = vector.Count;
1924 for (int i = 0; i < lower; i++)
1925 vector [i] = vector [i] & new_array [i];
1927 for (int i = lower; i < upper; i++)
1931 public static void And (ref MyBitVector target, MyBitVector vector)
1934 target.And (vector);
1936 target = vector.Clone ();
1939 public static void Or (ref MyBitVector target, MyBitVector vector)
1944 target = vector.Clone ();
1948 // This does a deep copy of the bit vector.
1950 public MyBitVector Clone ()
1952 MyBitVector retval = new MyBitVector (Count);
1954 retval.Vector = Vector;
1963 else if (!is_dirty && (InheritsFrom != null))
1964 return InheritsFrom.Vector;
1966 initialize_vector ();
1972 initialize_vector ();
1974 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1975 vector [i] = value [i];
1979 void initialize_vector ()
1984 vector = new BitArray (Count, false);
1985 if (InheritsFrom != null)
1986 Vector = InheritsFrom.Vector;
1991 public override string ToString ()
1993 StringBuilder sb = new StringBuilder ("{");
1995 BitArray vector = Vector;
1998 for (int i = 0; i < vector.Count; i++) {
1999 sb.Append (vector [i] ? "1" : "0");
2003 return sb.ToString ();