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, result);
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);
640 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
641 UsageVector f_origins)
643 if (parameters != null) {
644 if (f_vector != null) {
645 MergeFinally (branching, f_origins, f_vector.Parameters);
646 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
648 MergeFinally (branching, f_origins, parameters);
651 if (f_vector != null)
652 MyBitVector.Or (ref locals, f_vector.LocalVector);
656 // Tells control flow analysis that the current code position may be reached with
657 // a forward jump from any of the origins listed in `origin_vectors' which is a
658 // list of UsageVectors.
660 // This is used when resolving forward gotos - in the following example, the
661 // variable `a' is uninitialized in line 8 becase this line may be reached via
662 // the goto in line 4:
672 // 8 Console.WriteLine (a);
675 public void MergeJumpOrigins (ICollection origin_vectors)
677 Report.Debug (1, " MERGING JUMP ORIGINS", this);
679 reachability = Reachability.Never ();
681 if (origin_vectors == null)
686 foreach (UsageVector vector in origin_vectors) {
687 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
690 locals.Or (vector.locals);
691 if (parameters != null)
692 parameters.Or (vector.parameters);
695 locals.And (vector.locals);
696 if (parameters != null)
697 parameters.And (vector.parameters);
700 Reachability.And (ref reachability, vector.Reachability, true);
703 Report.Debug (1, " MERGING JUMP ORIGINS DONE", this);
707 // This is used at the beginning of a finally block if there were
708 // any return statements in the try block or one of the catch blocks.
710 public void MergeFinallyOrigins (UsageVector f_origins)
712 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
714 reachability = Reachability.Never ();
716 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
717 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
719 if (parameters != null)
720 parameters.And (vector.parameters);
722 Reachability.And (ref reachability, vector.Reachability, true);
727 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
730 public void CheckOutParameters (FlowBranching branching)
732 if (parameters != null)
733 branching.CheckOutParameters (parameters, branching.Location);
737 // Performs an `or' operation on the locals and the parameters.
739 public void Or (UsageVector new_vector)
742 locals.Or (new_vector.locals);
743 if (parameters != null)
744 parameters.Or (new_vector.parameters);
748 // Performs an `and' operation on the locals.
750 public void AndLocals (UsageVector new_vector)
753 locals.And (new_vector.locals);
756 public bool HasParameters {
758 return parameters != null;
762 public bool HasLocals {
764 return locals != null;
769 // Returns a deep copy of the parameters.
771 public MyBitVector Parameters {
773 if (parameters != null)
774 return parameters.Clone ();
781 // Returns a deep copy of the locals.
783 public MyBitVector Locals {
785 return locals.Clone ();
789 public MyBitVector ParameterVector {
795 public MyBitVector LocalVector {
805 public override string ToString ()
807 StringBuilder sb = new StringBuilder ();
809 sb.Append ("Vector (");
814 sb.Append (reachability);
815 if (parameters != null) {
817 sb.Append (parameters);
823 return sb.ToString ();
828 // Creates a new flow branching which is contained in `parent'.
829 // You should only pass non-null for the `block' argument if this block
830 // introduces any new variables - in this case, we need to create a new
831 // usage vector with a different size than our parent's one.
833 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
834 Block block, Location loc)
844 param_map = Block.ParameterMap;
845 local_map = Block.LocalMap;
847 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
848 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
850 param_map = Parent.param_map;
851 local_map = Parent.local_map;
852 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
858 public abstract UsageVector CurrentUsageVector {
863 // Creates a sibling of the current usage vector.
865 public virtual void CreateSibling (SiblingType type)
867 AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
869 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
872 protected abstract void AddSibling (UsageVector uv);
874 public abstract void Label (ArrayList origin_vectors);
877 // Check whether all `out' parameters have been assigned.
879 public void CheckOutParameters (MyBitVector parameters, Location loc)
881 for (int i = 0; i < param_map.Count; i++) {
882 VariableInfo var = param_map [i];
887 if (var.IsAssigned (parameters))
890 Report.Error (177, loc, "The out parameter `" +
891 param_map.VariableNames [i] + "' must be " +
892 "assigned before control leave the current method.");
896 protected UsageVector Merge (UsageVector sibling_list)
898 if (sibling_list.Next == null)
901 MyBitVector locals = null;
902 MyBitVector parameters = null;
904 Reachability reachability = null;
906 Report.Debug (2, " MERGING SIBLINGS", this, Name);
908 for (UsageVector child = sibling_list; child != null; child = child.Next) {
909 bool do_break = (Type != BranchingType.Switch) &&
910 (Type != BranchingType.LoopBlock);
912 Report.Debug (2, " MERGING SIBLING ", child,
913 child.Parameters, child.Locals,
914 reachability, child.Reachability, do_break);
916 Reachability.And (ref reachability, child.Reachability, do_break);
918 // A local variable is initialized after a flow branching if it
919 // has been initialized in all its branches which do neither
920 // always return or always throw an exception.
922 // If a branch may return, but does not always return, then we
923 // can treat it like a never-returning branch here: control will
924 // only reach the code position after the branching if we did not
927 // It's important to distinguish between always and sometimes
928 // returning branches here:
931 // 2 if (something) {
935 // 6 Console.WriteLine (a);
937 // The if block in lines 3-4 always returns, so we must not look
938 // at the initialization of `a' in line 4 - thus it'll still be
939 // uninitialized in line 6.
941 // On the other hand, the following is allowed:
948 // 6 Console.WriteLine (a);
950 // Here, `a' is initialized in line 3 and we must not look at
951 // line 5 since it always returns.
953 bool do_break_2 = (child.Type != SiblingType.Block) &&
954 (child.Type != SiblingType.SwitchSection);
955 bool unreachable = (do_break_2 && child.Reachability.AlwaysBreaks) ||
956 child.Reachability.AlwaysThrows ||
957 child.Reachability.AlwaysReturns ||
958 child.Reachability.AlwaysHasBarrier;
960 Report.Debug (2, " MERGING SIBLING #1", reachability,
961 Type, child.Type, child.Reachability.IsUnreachable,
962 do_break_2, unreachable);
965 MyBitVector.And (ref locals, child.LocalVector);
967 // An `out' parameter must be assigned in all branches which do
968 // not always throw an exception.
969 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
970 MyBitVector.And (ref parameters, child.ParameterVector);
972 Report.Debug (2, " MERGING SIBLING #2", parameters, locals);
975 if (reachability == null)
976 reachability = Reachability.Never ();
978 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
979 reachability, Infinite);
981 return new UsageVector (parameters, locals, reachability, Location);
984 protected abstract UsageVector Merge ();
987 // Merge a child branching.
989 public UsageVector MergeChild (FlowBranching child)
991 return CurrentUsageVector.MergeChild (child);
995 // Does the toplevel merging.
997 public Reachability MergeTopBlock ()
999 if ((Type != BranchingType.Block) || (Block == null))
1000 throw new NotSupportedException ();
1002 UsageVector vector = new UsageVector (
1003 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1005 UsageVector result = vector.MergeChild (this);
1007 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1009 if (vector.Reachability.Throws != FlowReturns.Always)
1010 CheckOutParameters (vector.Parameters, Location);
1012 return result.Reachability;
1015 public virtual bool InTryBlock ()
1018 return Parent.InTryBlock ();
1023 public virtual void AddFinallyVector (UsageVector vector)
1026 Parent.AddFinallyVector (vector);
1028 throw new NotSupportedException ();
1031 public bool IsAssigned (VariableInfo vi)
1033 return CurrentUsageVector.IsAssigned (vi);
1036 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1038 if (CurrentUsageVector.IsAssigned (vi))
1041 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1044 public void SetAssigned (VariableInfo vi)
1046 CurrentUsageVector.SetAssigned (vi);
1049 public void SetFieldAssigned (VariableInfo vi, string name)
1051 CurrentUsageVector.SetFieldAssigned (vi, name);
1054 public override string ToString ()
1056 StringBuilder sb = new StringBuilder ();
1057 sb.Append (GetType ());
1063 if (Block != null) {
1065 sb.Append (Block.ID);
1067 sb.Append (Block.StartLocation);
1070 // sb.Append (Siblings.Length);
1071 // sb.Append (" - ");
1072 sb.Append (CurrentUsageVector);
1074 return sb.ToString ();
1077 public string Name {
1079 return String.Format ("{0} ({1}:{2}:{3})",
1080 GetType (), id, Type, Location);
1085 public class FlowBranchingBlock : FlowBranching
1087 UsageVector sibling_list = null;
1089 public FlowBranchingBlock (FlowBranching parent, BranchingType type, SiblingType stype,
1090 Block block, Location loc)
1091 : base (parent, type, stype, block, loc)
1094 public override UsageVector CurrentUsageVector {
1095 get { return sibling_list; }
1098 protected override void AddSibling (UsageVector sibling)
1100 sibling.Next = sibling_list;
1101 sibling_list = sibling;
1104 public override void Label (ArrayList origin_vectors)
1106 if (!CurrentUsageVector.Reachability.IsUnreachable) {
1107 if (origin_vectors == null)
1108 origin_vectors = new ArrayList (1);
1109 origin_vectors.Add (CurrentUsageVector.Clone ());
1112 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1115 protected override UsageVector Merge ()
1117 return Merge (sibling_list);
1121 public class FlowBranchingException : FlowBranching
1123 UsageVector current_vector;
1124 UsageVector try_vector;
1125 UsageVector catch_vectors;
1126 UsageVector finally_vector;
1127 UsageVector finally_origins;
1129 public FlowBranchingException (FlowBranching parent, BranchingType type, Block block, Location loc)
1130 : base (parent, type, SiblingType.Try, block, loc)
1133 protected override void AddSibling (UsageVector sibling)
1135 if (sibling.Type == SiblingType.Try) {
1136 try_vector = sibling;
1137 sibling.Next = catch_vectors;
1138 catch_vectors = sibling;
1139 } else if (sibling.Type == SiblingType.Catch) {
1140 sibling.Next = catch_vectors;
1141 catch_vectors = sibling;
1142 } else if (sibling.Type == SiblingType.Finally) {
1143 sibling.MergeFinallyOrigins (finally_origins);
1144 finally_vector = sibling;
1146 throw new InvalidOperationException ();
1148 current_vector = sibling;
1151 public override UsageVector CurrentUsageVector {
1152 get { return current_vector; }
1155 public override bool InTryBlock ()
1160 public override void AddFinallyVector (UsageVector vector)
1162 vector = vector.Clone ();
1163 vector.Next = finally_origins;
1164 finally_origins = vector;
1167 public override void Label (ArrayList origin_vectors)
1169 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1172 protected override UsageVector Merge ()
1174 UsageVector vector = Merge (catch_vectors);
1176 vector.MergeFinally (this, finally_vector, finally_origins);
1183 // This is used by the flow analysis code to keep track of the type of local variables
1186 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1187 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1188 // you can only assign the whole variable as such.
1190 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1191 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1192 // one bit for each of its fields.
1194 // This class computes this `layout' for each type.
1196 public class TypeInfo
1198 public readonly Type Type;
1201 // Total number of bits a variable of this type consumes in the flow vector.
1203 public readonly int TotalLength;
1206 // Number of bits the simple fields of a variable of this type consume
1207 // in the flow vector.
1209 public readonly int Length;
1212 // This is only used by sub-structs.
1214 public readonly int Offset;
1217 // If this is a struct.
1219 public readonly bool IsStruct;
1222 // If this is a struct, all fields which are structs theirselves.
1224 public TypeInfo[] SubStructInfo;
1226 protected readonly StructInfo struct_info;
1227 private static Hashtable type_hash = new Hashtable ();
1229 public static TypeInfo GetTypeInfo (Type type)
1231 TypeInfo info = (TypeInfo) type_hash [type];
1235 info = new TypeInfo (type);
1236 type_hash.Add (type, info);
1240 public static TypeInfo GetTypeInfo (TypeContainer tc)
1242 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1246 info = new TypeInfo (tc);
1247 type_hash.Add (tc.TypeBuilder, info);
1251 private TypeInfo (Type type)
1255 struct_info = StructInfo.GetStructInfo (type);
1256 if (struct_info != null) {
1257 Length = struct_info.Length;
1258 TotalLength = struct_info.TotalLength;
1259 SubStructInfo = struct_info.StructFields;
1268 private TypeInfo (TypeContainer tc)
1270 this.Type = tc.TypeBuilder;
1272 struct_info = StructInfo.GetStructInfo (tc);
1273 if (struct_info != null) {
1274 Length = struct_info.Length;
1275 TotalLength = struct_info.TotalLength;
1276 SubStructInfo = struct_info.StructFields;
1285 protected TypeInfo (StructInfo struct_info, int offset)
1287 this.struct_info = struct_info;
1288 this.Offset = offset;
1289 this.Length = struct_info.Length;
1290 this.TotalLength = struct_info.TotalLength;
1291 this.SubStructInfo = struct_info.StructFields;
1292 this.Type = struct_info.Type;
1293 this.IsStruct = true;
1296 public int GetFieldIndex (string name)
1298 if (struct_info == null)
1301 return struct_info [name];
1304 public TypeInfo GetSubStruct (string name)
1306 if (struct_info == null)
1309 return struct_info.GetStructField (name);
1313 // A struct's constructor must always assign all fields.
1314 // This method checks whether it actually does so.
1316 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1318 if (struct_info == null)
1322 for (int i = 0; i < struct_info.Count; i++) {
1323 FieldInfo field = struct_info.Fields [i];
1325 if (!branching.IsFieldAssigned (vi, field.Name)) {
1326 Report.Error (171, loc,
1327 "Field `" + TypeManager.CSharpName (Type) +
1328 "." + field.Name + "' must be fully initialized " +
1329 "before control leaves the constructor");
1337 public override string ToString ()
1339 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1340 Type, Offset, Length, TotalLength);
1343 protected class StructInfo {
1344 public readonly Type Type;
1345 public readonly FieldInfo[] Fields;
1346 public readonly TypeInfo[] StructFields;
1347 public readonly int Count;
1348 public readonly int CountPublic;
1349 public readonly int CountNonPublic;
1350 public readonly int Length;
1351 public readonly int TotalLength;
1352 public readonly bool HasStructFields;
1354 private static Hashtable field_type_hash = new Hashtable ();
1355 private Hashtable struct_field_hash;
1356 private Hashtable field_hash;
1358 protected bool InTransit = false;
1360 // Private constructor. To save memory usage, we only need to create one instance
1361 // of this class per struct type.
1362 private StructInfo (Type type)
1366 field_type_hash.Add (type, this);
1368 if (type is TypeBuilder) {
1369 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1371 ArrayList fields = tc.Fields;
1373 ArrayList public_fields = new ArrayList ();
1374 ArrayList non_public_fields = new ArrayList ();
1376 if (fields != null) {
1377 foreach (Field field in fields) {
1378 if ((field.ModFlags & Modifiers.STATIC) != 0)
1380 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1381 public_fields.Add (field.FieldBuilder);
1383 non_public_fields.Add (field.FieldBuilder);
1387 CountPublic = public_fields.Count;
1388 CountNonPublic = non_public_fields.Count;
1389 Count = CountPublic + CountNonPublic;
1391 Fields = new FieldInfo [Count];
1392 public_fields.CopyTo (Fields, 0);
1393 non_public_fields.CopyTo (Fields, CountPublic);
1395 FieldInfo[] public_fields = type.GetFields (
1396 BindingFlags.Instance|BindingFlags.Public);
1397 FieldInfo[] non_public_fields = type.GetFields (
1398 BindingFlags.Instance|BindingFlags.NonPublic);
1400 CountPublic = public_fields.Length;
1401 CountNonPublic = non_public_fields.Length;
1402 Count = CountPublic + CountNonPublic;
1404 Fields = new FieldInfo [Count];
1405 public_fields.CopyTo (Fields, 0);
1406 non_public_fields.CopyTo (Fields, CountPublic);
1409 struct_field_hash = new Hashtable ();
1410 field_hash = new Hashtable ();
1413 StructFields = new TypeInfo [Count];
1414 StructInfo[] sinfo = new StructInfo [Count];
1418 for (int i = 0; i < Count; i++) {
1419 FieldInfo field = (FieldInfo) Fields [i];
1421 sinfo [i] = GetStructInfo (field.FieldType);
1422 if (sinfo [i] == null)
1423 field_hash.Add (field.Name, ++Length);
1424 else if (sinfo [i].InTransit) {
1425 Report.Error (523, String.Format (
1426 "Struct member '{0}.{1}' of type '{2}' causes " +
1427 "a cycle in the structure layout",
1428 type, field.Name, sinfo [i].Type));
1436 TotalLength = Length + 1;
1437 for (int i = 0; i < Count; i++) {
1438 FieldInfo field = (FieldInfo) Fields [i];
1440 if (sinfo [i] == null)
1443 field_hash.Add (field.Name, TotalLength);
1445 HasStructFields = true;
1446 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1447 struct_field_hash.Add (field.Name, StructFields [i]);
1448 TotalLength += sinfo [i].TotalLength;
1452 public int this [string name] {
1454 if (field_hash.Contains (name))
1455 return (int) field_hash [name];
1461 public TypeInfo GetStructField (string name)
1463 return (TypeInfo) struct_field_hash [name];
1466 public static StructInfo GetStructInfo (Type type)
1468 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1469 TypeManager.IsBuiltinType (type))
1472 StructInfo info = (StructInfo) field_type_hash [type];
1476 return new StructInfo (type);
1479 public static StructInfo GetStructInfo (TypeContainer tc)
1481 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1485 return new StructInfo (tc.TypeBuilder);
1491 // This is used by the flow analysis code to store information about a single local variable
1492 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1493 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1494 // it has been assigned or not, but for structs, we need this information for each of its fields.
1496 public class VariableInfo {
1497 public readonly string Name;
1498 public readonly TypeInfo TypeInfo;
1501 // The bit offset of this variable in the flow vector.
1503 public readonly int Offset;
1506 // The number of bits this variable needs in the flow vector.
1507 // The first bit always specifies whether the variable as such has been assigned while
1508 // the remaining bits contain this information for each of a struct's fields.
1510 public readonly int Length;
1513 // If this is a parameter of local variable.
1515 public readonly bool IsParameter;
1517 public readonly LocalInfo LocalInfo;
1518 public readonly int ParameterIndex;
1520 readonly VariableInfo Parent;
1521 VariableInfo[] sub_info;
1523 protected VariableInfo (string name, Type type, int offset)
1526 this.Offset = offset;
1527 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1529 Length = TypeInfo.TotalLength;
1534 protected VariableInfo (VariableInfo parent, TypeInfo type)
1536 this.Name = parent.Name;
1537 this.TypeInfo = type;
1538 this.Offset = parent.Offset + type.Offset;
1539 this.Parent = parent;
1540 this.Length = type.TotalLength;
1542 this.IsParameter = parent.IsParameter;
1543 this.LocalInfo = parent.LocalInfo;
1544 this.ParameterIndex = parent.ParameterIndex;
1549 protected void Initialize ()
1551 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1552 if (sub_fields != null) {
1553 sub_info = new VariableInfo [sub_fields.Length];
1554 for (int i = 0; i < sub_fields.Length; i++) {
1555 if (sub_fields [i] != null)
1556 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1559 sub_info = new VariableInfo [0];
1562 public VariableInfo (LocalInfo local_info, int offset)
1563 : this (local_info.Name, local_info.VariableType, offset)
1565 this.LocalInfo = local_info;
1566 this.IsParameter = false;
1569 public VariableInfo (string name, Type type, int param_idx, int offset)
1570 : this (name, type, offset)
1572 this.ParameterIndex = param_idx;
1573 this.IsParameter = true;
1576 public bool IsAssigned (EmitContext ec)
1578 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1581 public bool IsAssigned (EmitContext ec, Location loc)
1583 if (IsAssigned (ec))
1586 Report.Error (165, loc,
1587 "Use of unassigned local variable `" + Name + "'");
1588 ec.CurrentBranching.SetAssigned (this);
1592 public bool IsAssigned (MyBitVector vector)
1594 if (vector [Offset])
1597 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1598 if (vector [parent.Offset])
1601 // Return unless this is a struct.
1602 if (!TypeInfo.IsStruct)
1605 // Ok, so each field must be assigned.
1606 for (int i = 0; i < TypeInfo.Length; i++) {
1607 if (!vector [Offset + i + 1])
1611 // Ok, now check all fields which are structs.
1612 for (int i = 0; i < sub_info.Length; i++) {
1613 VariableInfo sinfo = sub_info [i];
1617 if (!sinfo.IsAssigned (vector))
1621 vector [Offset] = true;
1625 public void SetAssigned (EmitContext ec)
1627 if (ec.DoFlowAnalysis)
1628 ec.CurrentBranching.SetAssigned (this);
1631 public void SetAssigned (MyBitVector vector)
1633 vector [Offset] = true;
1636 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1638 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1641 Report.Error (170, loc,
1642 "Use of possibly unassigned field `" + name + "'");
1643 ec.CurrentBranching.SetFieldAssigned (this, name);
1647 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1649 int field_idx = TypeInfo.GetFieldIndex (field_name);
1654 return vector [Offset + field_idx];
1657 public void SetFieldAssigned (EmitContext ec, string name)
1659 if (ec.DoFlowAnalysis)
1660 ec.CurrentBranching.SetFieldAssigned (this, name);
1663 public void SetFieldAssigned (MyBitVector vector, string field_name)
1665 int field_idx = TypeInfo.GetFieldIndex (field_name);
1670 vector [Offset + field_idx] = true;
1673 public VariableInfo GetSubStruct (string name)
1675 TypeInfo type = TypeInfo.GetSubStruct (name);
1680 return new VariableInfo (this, type);
1683 public override string ToString ()
1685 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1686 Name, TypeInfo, Offset, Length, IsParameter);
1691 // This is used by the flow code to hold the `layout' of the flow vector for
1692 // all locals and all parameters (ie. we create one instance of this class for the
1693 // locals and another one for the params).
1695 public class VariableMap {
1697 // The number of variables in the map.
1699 public readonly int Count;
1702 // Total length of the flow vector for this map.
1704 public readonly int Length;
1707 // Type and name of all the variables.
1708 // Note that this is null for variables for which we do not need to compute
1711 public readonly Type[] VariableTypes;
1712 public readonly string[] VariableNames;
1716 public VariableMap (InternalParameters ip)
1718 Count = ip != null ? ip.Count : 0;
1719 map = new VariableInfo [Count];
1720 VariableNames = new string [Count];
1721 VariableTypes = new Type [Count];
1724 for (int i = 0; i < Count; i++) {
1725 Parameter.Modifier mod = ip.ParameterModifier (i);
1727 if ((mod & Parameter.Modifier.OUT) == 0)
1730 VariableNames [i] = ip.ParameterName (i);
1731 VariableTypes [i] = TypeManager.GetElementType (ip.ParameterType (i));
1733 map [i] = new VariableInfo (VariableNames [i], VariableTypes [i], i, Length);
1734 Length += map [i].Length;
1738 public VariableMap (LocalInfo[] locals)
1739 : this (null, locals)
1742 public VariableMap (VariableMap parent, LocalInfo[] locals)
1744 int offset = 0, start = 0;
1745 if (parent != null) {
1746 offset = parent.Length;
1747 start = parent.Count;
1750 Count = locals.Length + start;
1751 map = new VariableInfo [Count];
1752 VariableNames = new string [Count];
1753 VariableTypes = new Type [Count];
1756 if (parent != null) {
1757 parent.map.CopyTo (map, 0);
1758 parent.VariableNames.CopyTo (VariableNames, 0);
1759 parent.VariableTypes.CopyTo (VariableTypes, 0);
1762 for (int i = start; i < Count; i++) {
1763 LocalInfo li = locals [i-start];
1765 if (li.VariableType == null)
1768 VariableNames [i] = li.Name;
1769 VariableTypes [i] = li.VariableType;
1771 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1772 Length += map [i].Length;
1777 // Returns the VariableInfo for variable @index or null if we don't need to
1778 // compute assignment info for this variable.
1780 public VariableInfo this [int index] {
1786 public override string ToString ()
1788 return String.Format ("VariableMap ({0}:{1})", Count, Length);
1793 // This is a special bit vector which can inherit from another bit vector doing a
1794 // copy-on-write strategy. The inherited vector may have a smaller size than the
1797 public class MyBitVector {
1798 public readonly int Count;
1799 public readonly MyBitVector InheritsFrom;
1804 public MyBitVector (int Count)
1805 : this (null, Count)
1808 public MyBitVector (MyBitVector InheritsFrom, int Count)
1810 this.InheritsFrom = InheritsFrom;
1815 // Checks whether this bit vector has been modified. After setting this to true,
1816 // we won't use the inherited vector anymore, but our own copy of it.
1818 public bool IsDirty {
1825 initialize_vector ();
1830 // Get/set bit `index' in the bit vector.
1832 public bool this [int index]
1836 throw new ArgumentOutOfRangeException ();
1838 // We're doing a "copy-on-write" strategy here; as long
1839 // as nobody writes to the array, we can use our parent's
1840 // copy instead of duplicating the vector.
1843 return vector [index];
1844 else if (InheritsFrom != null) {
1845 BitArray inherited = InheritsFrom.Vector;
1847 if (index < inherited.Count)
1848 return inherited [index];
1857 throw new ArgumentOutOfRangeException ();
1859 // Only copy the vector if we're actually modifying it.
1861 if (this [index] != value) {
1862 initialize_vector ();
1864 vector [index] = value;
1870 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1871 // copy of the bit vector.
1873 public static explicit operator BitArray (MyBitVector vector)
1875 vector.initialize_vector ();
1876 return vector.Vector;
1880 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1881 // different size than the current one.
1883 public void Or (MyBitVector new_vector)
1885 BitArray new_array = new_vector.Vector;
1887 initialize_vector ();
1890 if (vector.Count < new_array.Count)
1891 upper = vector.Count;
1893 upper = new_array.Count;
1895 for (int i = 0; i < upper; i++)
1896 vector [i] = vector [i] | new_array [i];
1900 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1901 // a different size than the current one.
1903 public void And (MyBitVector new_vector)
1905 BitArray new_array = new_vector.Vector;
1907 initialize_vector ();
1910 if (vector.Count < new_array.Count)
1911 lower = upper = vector.Count;
1913 lower = new_array.Count;
1914 upper = vector.Count;
1917 for (int i = 0; i < lower; i++)
1918 vector [i] = vector [i] & new_array [i];
1920 for (int i = lower; i < upper; i++)
1924 public static void And (ref MyBitVector target, MyBitVector vector)
1927 target.And (vector);
1929 target = vector.Clone ();
1932 public static void Or (ref MyBitVector target, MyBitVector vector)
1937 target = vector.Clone ();
1941 // This does a deep copy of the bit vector.
1943 public MyBitVector Clone ()
1945 MyBitVector retval = new MyBitVector (Count);
1947 retval.Vector = Vector;
1956 else if (!is_dirty && (InheritsFrom != null))
1957 return InheritsFrom.Vector;
1959 initialize_vector ();
1965 initialize_vector ();
1967 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1968 vector [i] = value [i];
1972 void initialize_vector ()
1977 vector = new BitArray (Count, false);
1978 if (InheritsFrom != null)
1979 Vector = InheritsFrom.Vector;
1984 public override string ToString ()
1986 StringBuilder sb = new StringBuilder ("{");
1988 BitArray vector = Vector;
1991 for (int i = 0; i < vector.Count; i++) {
1992 sb.Append (vector [i] ? "1" : "0");
1996 return sb.ToString ();