2 // flowanalyis.cs: The control flow analysis code
5 // Martin Baulig (martin@ximian.com)
6 // Raja R Harinath (rharinath@novell.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
14 using System.Collections.Generic;
19 // A new instance of this class is created every time a new block is resolved
20 // and if there's branching in the block's control flow.
22 public abstract class FlowBranching
25 // The type of a FlowBranching.
27 public enum BranchingType : byte {
28 // Normal (conditional or toplevel) block.
37 // The statement embedded inside a loop
40 // part of a block headed by a jump target
46 // TryFinally, Using, Lock, CollectionForeach
52 // The toplevel block of a function
60 // The type of one sibling of a branching.
62 public enum SiblingType : byte {
71 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
74 case BranchingType.Exception:
75 case BranchingType.Labeled:
76 case BranchingType.Toplevel:
77 case BranchingType.TryCatch:
78 throw new InvalidOperationException ();
80 case BranchingType.Switch:
81 return new FlowBranchingBreakable (parent, type, SiblingType.SwitchSection, block, loc);
83 case BranchingType.Block:
84 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
86 case BranchingType.Loop:
87 return new FlowBranchingBreakable (parent, type, SiblingType.Conditional, block, loc);
89 case BranchingType.Embedded:
90 return new FlowBranchingContinuable (parent, type, SiblingType.Conditional, block, loc);
93 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
98 // The type of this flow branching.
100 public readonly BranchingType Type;
103 // The block this branching is contained in. This may be null if it's not
104 // a top-level block and it doesn't declare any local variables.
106 public readonly Block Block;
109 // The parent of this branching or null if this is the top-block.
111 public readonly FlowBranching Parent;
114 // Start-Location of this flow branching.
116 public readonly Location Location;
118 static int next_id = 0;
122 // The vector contains a BitArray with information about which local variables
123 // and parameters are already initialized at the current code position.
125 public class UsageVector {
127 // The type of this branching.
129 public readonly SiblingType Type;
132 // Start location of this branching.
134 public Location Location;
137 // This is only valid for SwitchSection, Try, Catch and Finally.
139 public readonly Block Block;
142 // The number of locals in this block.
144 public readonly int CountLocals;
147 // If not null, then we inherit our state from this vector and do a
148 // copy-on-write. If null, then we're the first sibling in a top-level
149 // block and inherit from the empty vector.
151 public readonly UsageVector InheritsFrom;
154 // This is used to construct a list of UsageVector's.
156 public UsageVector Next;
164 static int next_id = 0;
168 // Normally, you should not use any of these constructors.
170 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc, int num_locals)
175 this.InheritsFrom = parent;
176 this.CountLocals = num_locals;
178 locals = num_locals == 0
180 : new MyBitVector (parent == null ? MyBitVector.Empty : parent.locals, num_locals);
183 is_unreachable = parent.is_unreachable;
189 public UsageVector (SiblingType type, UsageVector parent, Block block, Location loc)
190 : this (type, parent, block, loc, parent.CountLocals)
193 private UsageVector (MyBitVector locals, bool is_unreachable, Block block, Location loc)
195 this.Type = SiblingType.Block;
199 this.is_unreachable = is_unreachable;
201 this.locals = locals;
208 // This does a deep copy of the usage vector.
210 public UsageVector Clone ()
212 UsageVector retval = new UsageVector (Type, null, Block, Location, CountLocals);
214 retval.locals = locals.Clone ();
215 retval.is_unreachable = is_unreachable;
220 public bool IsAssigned (VariableInfo var, bool ignoreReachability)
222 if (!ignoreReachability && !var.IsParameter && IsUnreachable)
225 return var.IsAssigned (locals);
228 public void SetAssigned (VariableInfo var)
230 if (!var.IsParameter && IsUnreachable)
233 var.SetAssigned (locals);
236 public bool IsFieldAssigned (VariableInfo var, string name)
238 if (!var.IsParameter && IsUnreachable)
241 return var.IsFieldAssigned (locals, name);
244 public void SetFieldAssigned (VariableInfo var, string name)
246 if (!var.IsParameter && IsUnreachable)
249 var.SetFieldAssigned (locals, name);
252 public bool IsUnreachable {
253 get { return is_unreachable; }
256 public void ResetBarrier ()
258 is_unreachable = false;
263 is_unreachable = true;
266 public static UsageVector MergeSiblings (UsageVector sibling_list, Location loc)
268 if (sibling_list.Next == null)
271 MyBitVector locals = null;
272 bool is_unreachable = sibling_list.is_unreachable;
274 if (!sibling_list.IsUnreachable)
275 locals &= sibling_list.locals;
277 for (UsageVector child = sibling_list.Next; child != null; child = child.Next) {
278 is_unreachable &= child.is_unreachable;
280 if (!child.IsUnreachable)
281 locals &= child.locals;
284 return new UsageVector (locals, is_unreachable, null, loc);
288 // Merges a child branching.
290 public UsageVector MergeChild (UsageVector child, bool overwrite)
292 Report.Debug (2, " MERGING CHILD EFFECTS", this, child, Type);
294 bool new_isunr = child.is_unreachable;
297 // We've now either reached the point after the branching or we will
298 // never get there since we always return or always throw an exception.
300 // If we can reach the point after the branching, mark all locals and
301 // parameters as initialized which have been initialized in all branches
302 // we need to look at (see above).
305 if ((Type == SiblingType.SwitchSection) && !new_isunr) {
306 Report.Error (163, Location,
307 "Control cannot fall through from one " +
308 "case label to another");
312 locals |= child.locals;
314 // throw away un-necessary information about variables in child blocks
315 if (locals.Count != CountLocals)
316 locals = new MyBitVector (locals, CountLocals);
319 is_unreachable = new_isunr;
321 is_unreachable |= new_isunr;
326 public void MergeOrigins (UsageVector o_vectors)
328 Report.Debug (1, " MERGING BREAK ORIGINS", this);
330 if (o_vectors == null)
333 if (IsUnreachable && locals != null)
334 locals.SetAll (true);
336 for (UsageVector vector = o_vectors; vector != null; vector = vector.Next) {
337 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
338 if (vector.IsUnreachable)
340 locals &= vector.locals;
341 is_unreachable &= vector.is_unreachable;
344 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
351 public override string ToString ()
353 return String.Format ("Vector ({0},{1},{2}-{3})", Type, id, is_unreachable, locals);
358 // Creates a new flow branching which is contained in `parent'.
359 // You should only pass non-null for the `block' argument if this block
360 // introduces any new variables - in this case, we need to create a new
361 // usage vector with a different size than our parent's one.
363 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
364 Block block, Location loc)
374 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
375 vector = new UsageVector (stype, parent_vector, Block, loc, Block.AssignableSlots);
377 vector = new UsageVector (stype, Parent.CurrentUsageVector, null, loc);
383 public abstract UsageVector CurrentUsageVector {
388 // Creates a sibling of the current usage vector.
390 public virtual void CreateSibling (Block block, SiblingType type)
392 UsageVector vector = new UsageVector (
393 type, Parent.CurrentUsageVector, block, Location);
396 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
399 public void CreateSibling ()
401 CreateSibling (null, SiblingType.Conditional);
404 protected abstract void AddSibling (UsageVector uv);
406 protected abstract UsageVector Merge ();
408 public UsageVector MergeChild (FlowBranching child)
410 return CurrentUsageVector.MergeChild (child.Merge (), true);
413 public virtual bool CheckRethrow (Location loc)
415 return Parent.CheckRethrow (loc);
418 public virtual bool AddResumePoint (ResumableStatement stmt, out int pc)
420 return Parent.AddResumePoint (stmt, out pc);
423 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
424 public virtual bool AddBreakOrigin (UsageVector vector, Location loc)
426 return Parent.AddBreakOrigin (vector, loc);
429 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
430 public virtual bool AddContinueOrigin (UsageVector vector, Location loc)
432 return Parent.AddContinueOrigin (vector, loc);
435 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
436 public virtual bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
438 return Parent.AddReturnOrigin (vector, stmt);
441 // returns true if we crossed an unwind-protected region (try/catch/finally, lock, using, ...)
442 public virtual bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
444 return Parent.AddGotoOrigin (vector, goto_stmt);
447 public bool IsAssigned (VariableInfo vi)
449 return CurrentUsageVector.IsAssigned (vi, false);
452 public bool IsFieldAssigned (VariableInfo vi, string field_name)
454 return CurrentUsageVector.IsAssigned (vi, false) || CurrentUsageVector.IsFieldAssigned (vi, field_name);
457 protected static Report Report {
458 get { return RootContext.ToplevelTypes.Compiler.Report; }
461 public void SetAssigned (VariableInfo vi)
463 CurrentUsageVector.SetAssigned (vi);
466 public void SetFieldAssigned (VariableInfo vi, string name)
468 CurrentUsageVector.SetFieldAssigned (vi, name);
472 public override string ToString ()
474 StringBuilder sb = new StringBuilder ();
475 sb.Append (GetType ());
483 sb.Append (Block.ID);
485 sb.Append (Block.StartLocation);
488 // sb.Append (Siblings.Length);
489 // sb.Append (" - ");
490 sb.Append (CurrentUsageVector);
492 return sb.ToString ();
497 get { return String.Format ("{0} ({1}:{2}:{3})", GetType (), id, Type, Location); }
501 public class FlowBranchingBlock : FlowBranching
503 UsageVector sibling_list = null;
505 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
506 SiblingType stype, Block block, Location loc)
507 : base (parent, type, stype, block, loc)
510 public override UsageVector CurrentUsageVector {
511 get { return sibling_list; }
514 protected override void AddSibling (UsageVector sibling)
516 if (sibling_list != null && sibling_list.Type == SiblingType.Block)
517 throw new InternalErrorException ("Blocks don't have sibling flow paths");
518 sibling.Next = sibling_list;
519 sibling_list = sibling;
522 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
524 LabeledStatement stmt = Block == null ? null : Block.LookupLabel (goto_stmt.Target);
526 return Parent.AddGotoOrigin (vector, goto_stmt);
529 goto_stmt.SetResolvedTarget (stmt);
530 stmt.AddUsageVector (vector);
534 public static void Error_UnknownLabel (Location loc, string label, Report Report)
536 Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
540 protected override UsageVector Merge ()
542 Report.Debug (2, " MERGING SIBLINGS", Name);
543 UsageVector vector = UsageVector.MergeSiblings (sibling_list, Location);
544 Report.Debug (2, " MERGING SIBLINGS DONE", Name, vector);
549 public class FlowBranchingBreakable : FlowBranchingBlock
551 UsageVector break_origins;
553 public FlowBranchingBreakable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
554 : base (parent, type, stype, block, loc)
557 public override bool AddBreakOrigin (UsageVector vector, Location loc)
559 vector = vector.Clone ();
560 vector.Next = break_origins;
561 break_origins = vector;
565 protected override UsageVector Merge ()
567 UsageVector vector = base.Merge ();
568 vector.MergeOrigins (break_origins);
573 public class FlowBranchingContinuable : FlowBranchingBlock
575 UsageVector continue_origins;
577 public FlowBranchingContinuable (FlowBranching parent, BranchingType type, SiblingType stype, Block block, Location loc)
578 : base (parent, type, stype, block, loc)
581 public override bool AddContinueOrigin (UsageVector vector, Location loc)
583 vector = vector.Clone ();
584 vector.Next = continue_origins;
585 continue_origins = vector;
589 protected override UsageVector Merge ()
591 UsageVector vector = base.Merge ();
592 vector.MergeOrigins (continue_origins);
597 public class FlowBranchingLabeled : FlowBranchingBlock
599 LabeledStatement stmt;
602 public FlowBranchingLabeled (FlowBranching parent, LabeledStatement stmt)
603 : base (parent, BranchingType.Labeled, SiblingType.Conditional, null, stmt.loc)
606 CurrentUsageVector.MergeOrigins (stmt.JumpOrigins);
607 actual = CurrentUsageVector.Clone ();
609 // stand-in for backward jumps
610 CurrentUsageVector.ResetBarrier ();
613 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
615 if (goto_stmt.Target != stmt.Name)
616 return Parent.AddGotoOrigin (vector, goto_stmt);
619 goto_stmt.SetResolvedTarget (stmt);
620 actual.MergeOrigins (vector.Clone ());
625 protected override UsageVector Merge ()
627 UsageVector vector = base.Merge ();
629 if (actual.IsUnreachable)
630 Report.Warning (162, 2, stmt.loc, "Unreachable code detected");
632 actual.MergeChild (vector, false);
637 public class FlowBranchingIterator : FlowBranchingBlock
639 readonly Iterator iterator;
641 public FlowBranchingIterator (FlowBranching parent, Iterator iterator)
642 : base (parent, BranchingType.Iterator, SiblingType.Block, iterator.Block, iterator.Location)
644 this.iterator = iterator;
647 public override bool AddResumePoint (ResumableStatement stmt, out int pc)
649 pc = iterator.AddResumePoint (stmt);
654 public class FlowBranchingToplevel : FlowBranchingBlock
656 UsageVector return_origins;
658 public FlowBranchingToplevel (FlowBranching parent, ParametersBlock stmt)
659 : base (parent, BranchingType.Toplevel, SiblingType.Conditional, stmt, stmt.loc)
663 public override bool CheckRethrow (Location loc)
665 Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
669 public override bool AddResumePoint (ResumableStatement stmt, out int pc)
671 throw new InternalErrorException ("A yield in a non-iterator block");
674 public override bool AddBreakOrigin (UsageVector vector, Location loc)
676 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
680 public override bool AddContinueOrigin (UsageVector vector, Location loc)
682 Report.Error (139, loc, "No enclosing loop out of which to break or continue");
686 public override bool AddReturnOrigin (UsageVector vector, ExitStatement stmt)
688 vector = vector.Clone ();
689 vector.Location = stmt.loc;
690 vector.Next = return_origins;
691 return_origins = vector;
695 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
697 string name = goto_stmt.Target;
698 LabeledStatement s = Block.LookupLabel (name);
700 throw new InternalErrorException ("Shouldn't get here");
702 if (Parent == null) {
703 Error_UnknownLabel (goto_stmt.loc, name, Report);
707 int errors = Report.Errors;
708 Parent.AddGotoOrigin (vector, goto_stmt);
709 if (errors == Report.Errors)
710 Report.Error (1632, goto_stmt.loc, "Control cannot leave the body of an anonymous method");
714 protected override UsageVector Merge ()
716 for (UsageVector origin = return_origins; origin != null; origin = origin.Next)
717 Block.ParametersBlock.CheckOutParameters (origin, origin.Location);
719 UsageVector vector = base.Merge ();
720 Block.ParametersBlock.CheckOutParameters (vector, Block.loc);
721 // Note: we _do_not_ merge in the return origins
727 return Merge ().IsUnreachable;
731 public class FlowBranchingTryCatch : FlowBranchingBlock
733 readonly TryCatch tc;
735 public FlowBranchingTryCatch (FlowBranching parent, TryCatch stmt)
736 : base (parent, BranchingType.Block, SiblingType.Try, null, stmt.loc)
741 public override bool CheckRethrow (Location loc)
743 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
746 public override bool AddResumePoint (ResumableStatement stmt, out int pc)
748 int errors = Report.Errors;
749 Parent.AddResumePoint (tc.IsTryCatchFinally ? stmt : tc, out pc);
750 if (errors == Report.Errors) {
751 if (stmt is AwaitStatement) {
752 if (CurrentUsageVector.Next != null) {
753 Report.Error (1985, stmt.loc, "The `await' operator cannot be used in the body of a catch clause");
755 this.tc.AddResumePoint (stmt, pc);
758 if (CurrentUsageVector.Next == null)
759 Report.Error (1626, stmt.loc, "Cannot yield a value in the body of a try block with a catch clause");
761 Report.Error (1631, stmt.loc, "Cannot yield a value in the body of a catch clause");
768 public override bool AddBreakOrigin (UsageVector vector, Location loc)
770 Parent.AddBreakOrigin (vector, loc);
771 tc.SomeCodeFollows ();
775 public override bool AddContinueOrigin (UsageVector vector, Location loc)
777 Parent.AddContinueOrigin (vector, loc);
778 tc.SomeCodeFollows ();
782 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
784 Parent.AddReturnOrigin (vector, exit_stmt);
785 tc.SomeCodeFollows ();
789 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
791 Parent.AddGotoOrigin (vector, goto_stmt);
796 public class FlowBranchingAsync : FlowBranchingBlock
798 readonly AsyncInitializer async_init;
800 public FlowBranchingAsync (FlowBranching parent, AsyncInitializer async_init)
801 : base (parent, BranchingType.Block, SiblingType.Try, null, async_init.Location)
803 this.async_init = async_init;
806 public override bool CheckRethrow (Location loc)
808 return CurrentUsageVector.Next != null || Parent.CheckRethrow (loc);
811 public override bool AddResumePoint (ResumableStatement stmt, out int pc)
813 pc = async_init.AddResumePoint (stmt);
817 public override bool AddBreakOrigin (UsageVector vector, Location loc)
819 Parent.AddBreakOrigin (vector, loc);
823 public override bool AddContinueOrigin (UsageVector vector, Location loc)
825 Parent.AddContinueOrigin (vector, loc);
829 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
831 Parent.AddReturnOrigin (vector, exit_stmt);
835 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
837 Parent.AddGotoOrigin (vector, goto_stmt);
842 public class FlowBranchingTryFinally : FlowBranching
844 ExceptionStatement stmt;
845 UsageVector current_vector;
846 UsageVector try_vector;
847 UsageVector finally_vector;
849 abstract class SavedOrigin {
850 public readonly SavedOrigin Next;
851 public readonly UsageVector Vector;
853 protected SavedOrigin (SavedOrigin next, UsageVector vector)
856 Vector = vector.Clone ();
859 protected abstract void DoPropagateFinally (FlowBranching parent);
860 public void PropagateFinally (UsageVector finally_vector, FlowBranching parent)
862 if (finally_vector != null)
863 Vector.MergeChild (finally_vector, false);
864 DoPropagateFinally (parent);
868 class BreakOrigin : SavedOrigin {
870 public BreakOrigin (SavedOrigin next, UsageVector vector, Location loc)
871 : base (next, vector)
876 protected override void DoPropagateFinally (FlowBranching parent)
878 parent.AddBreakOrigin (Vector, Loc);
882 class ContinueOrigin : SavedOrigin {
884 public ContinueOrigin (SavedOrigin next, UsageVector vector, Location loc)
885 : base (next, vector)
890 protected override void DoPropagateFinally (FlowBranching parent)
892 parent.AddContinueOrigin (Vector, Loc);
896 class ReturnOrigin : SavedOrigin {
897 public ExitStatement Stmt;
899 public ReturnOrigin (SavedOrigin next, UsageVector vector, ExitStatement stmt)
900 : base (next, vector)
905 protected override void DoPropagateFinally (FlowBranching parent)
907 parent.AddReturnOrigin (Vector, Stmt);
911 class GotoOrigin : SavedOrigin {
914 public GotoOrigin (SavedOrigin next, UsageVector vector, Goto stmt)
915 : base (next, vector)
920 protected override void DoPropagateFinally (FlowBranching parent)
922 parent.AddGotoOrigin (Vector, Stmt);
926 SavedOrigin saved_origins;
928 public FlowBranchingTryFinally (FlowBranching parent,
929 ExceptionStatement stmt)
930 : base (parent, BranchingType.Exception, SiblingType.Try,
936 protected override void AddSibling (UsageVector sibling)
938 switch (sibling.Type) {
939 case SiblingType.Try:
940 try_vector = sibling;
942 case SiblingType.Finally:
943 finally_vector = sibling;
946 throw new InvalidOperationException ();
948 current_vector = sibling;
951 public override UsageVector CurrentUsageVector {
952 get { return current_vector; }
955 public override bool CheckRethrow (Location loc)
957 if (!Parent.CheckRethrow (loc))
959 if (finally_vector == null)
961 Report.Error (724, loc, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
965 public override bool AddResumePoint (ResumableStatement stmt, out int pc)
967 int errors = Report.Errors;
968 Parent.AddResumePoint (this.stmt, out pc);
969 if (errors == Report.Errors) {
970 if (finally_vector == null)
971 this.stmt.AddResumePoint (stmt, pc);
973 if (stmt is AwaitStatement) {
974 Report.Error (1984, stmt.loc, "The `await' operator cannot be used in the body of a finally clause");
976 Report.Error (1625, stmt.loc, "Cannot yield in the body of a finally clause");
983 public override bool AddBreakOrigin (UsageVector vector, Location loc)
985 if (finally_vector != null) {
986 int errors = Report.Errors;
987 Parent.AddBreakOrigin (vector, loc);
988 if (errors == Report.Errors)
989 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
991 saved_origins = new BreakOrigin (saved_origins, vector, loc);
994 // either the loop test or a back jump will follow code
995 stmt.SomeCodeFollows ();
999 public override bool AddContinueOrigin (UsageVector vector, Location loc)
1001 if (finally_vector != null) {
1002 int errors = Report.Errors;
1003 Parent.AddContinueOrigin (vector, loc);
1004 if (errors == Report.Errors)
1005 Report.Error (157, loc, "Control cannot leave the body of a finally clause");
1007 saved_origins = new ContinueOrigin (saved_origins, vector, loc);
1010 // either the loop test or a back jump will follow code
1011 stmt.SomeCodeFollows ();
1015 public override bool AddReturnOrigin (UsageVector vector, ExitStatement exit_stmt)
1017 if (finally_vector != null) {
1018 int errors = Report.Errors;
1019 Parent.AddReturnOrigin (vector, exit_stmt);
1020 if (errors == Report.Errors)
1021 exit_stmt.Error_FinallyClause (Report);
1023 saved_origins = new ReturnOrigin (saved_origins, vector, exit_stmt);
1026 // sets ec.NeedReturnLabel()
1027 stmt.SomeCodeFollows ();
1031 public override bool AddGotoOrigin (UsageVector vector, Goto goto_stmt)
1033 LabeledStatement s = current_vector.Block == null ? null : current_vector.Block.LookupLabel (goto_stmt.Target);
1035 throw new InternalErrorException ("Shouldn't get here");
1037 if (finally_vector != null) {
1038 int errors = Report.Errors;
1039 Parent.AddGotoOrigin (vector, goto_stmt);
1040 if (errors == Report.Errors)
1041 Report.Error (157, goto_stmt.loc, "Control cannot leave the body of a finally clause");
1043 saved_origins = new GotoOrigin (saved_origins, vector, goto_stmt);
1048 protected override UsageVector Merge ()
1050 UsageVector vector = try_vector.Clone ();
1052 if (finally_vector != null)
1053 vector.MergeChild (finally_vector, false);
1055 for (SavedOrigin origin = saved_origins; origin != null; origin = origin.Next)
1056 origin.PropagateFinally (finally_vector, Parent);
1063 // This is used by the flow analysis code to keep track of the type of local variables
1066 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1067 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1068 // you can only assign the whole variable as such.
1070 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1071 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1072 // one bit for each of its fields.
1074 // This class computes this `layout' for each type.
1076 public class TypeInfo
1078 public readonly TypeSpec Type;
1081 // Total number of bits a variable of this type consumes in the flow vector.
1083 public readonly int TotalLength;
1086 // Number of bits the simple fields of a variable of this type consume
1087 // in the flow vector.
1089 public readonly int Length;
1092 // This is only used by sub-structs.
1094 public readonly int Offset;
1097 // If this is a struct.
1099 public readonly bool IsStruct;
1102 // If this is a struct, all fields which are structs theirselves.
1104 public TypeInfo[] SubStructInfo;
1106 readonly StructInfo struct_info;
1107 private static Dictionary<TypeSpec, TypeInfo> type_hash;
1114 public static void Reset ()
1116 type_hash = new Dictionary<TypeSpec, TypeInfo> ();
1117 StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
1120 public static TypeInfo GetTypeInfo (TypeSpec type)
1123 if (type_hash.TryGetValue (type, out info))
1126 info = new TypeInfo (type);
1127 type_hash.Add (type, info);
1131 private TypeInfo (TypeSpec type)
1135 struct_info = StructInfo.GetStructInfo (type);
1136 if (struct_info != null) {
1137 Length = struct_info.Length;
1138 TotalLength = struct_info.TotalLength;
1139 SubStructInfo = struct_info.StructFields;
1148 TypeInfo (StructInfo struct_info, int offset)
1150 this.struct_info = struct_info;
1151 this.Offset = offset;
1152 this.Length = struct_info.Length;
1153 this.TotalLength = struct_info.TotalLength;
1154 this.SubStructInfo = struct_info.StructFields;
1155 this.Type = struct_info.Type;
1156 this.IsStruct = true;
1159 public int GetFieldIndex (string name)
1161 if (struct_info == null)
1164 return struct_info [name];
1167 public TypeInfo GetSubStruct (string name)
1169 if (struct_info == null)
1172 return struct_info.GetStructField (name);
1176 // A struct's constructor must always assign all fields.
1177 // This method checks whether it actually does so.
1179 public bool IsFullyInitialized (BlockContext ec, VariableInfo vi, Location loc)
1181 if (struct_info == null)
1185 FlowBranching branching = ec.CurrentBranching;
1186 for (int i = 0; i < struct_info.Count; i++) {
1187 var field = struct_info.Fields [i];
1189 // Fixed size buffers are not subject to definite assignment checking
1190 if (field is FixedFieldSpec)
1193 if (!branching.IsFieldAssigned (vi, field.Name)) {
1194 if (field.MemberDefinition is Property.BackingField) {
1195 ec.Report.Error (843, loc,
1196 "An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling the default struct contructor from a constructor initializer",
1197 field.GetSignatureForError ());
1199 ec.Report.Error (171, loc,
1200 "Field `{0}' must be fully assigned before control leaves the constructor",
1201 field.GetSignatureForError ());
1210 public override string ToString ()
1212 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1213 Type, Offset, Length, TotalLength);
1217 public readonly TypeSpec Type;
1218 public readonly FieldSpec[] Fields;
1219 public readonly TypeInfo[] StructFields;
1220 public readonly int Count;
1221 public readonly int CountPublic;
1222 public readonly int CountNonPublic;
1223 public readonly int Length;
1224 public readonly int TotalLength;
1225 public readonly bool HasStructFields;
1227 public static Dictionary<TypeSpec, StructInfo> field_type_hash;
1228 private Dictionary<string, TypeInfo> struct_field_hash;
1229 private Dictionary<string, int> field_hash;
1231 protected bool InTransit = false;
1233 // Private constructor. To save memory usage, we only need to create one instance
1234 // of this class per struct type.
1235 private StructInfo (TypeSpec type)
1239 field_type_hash.Add (type, this);
1241 TypeContainer tc = type.MemberDefinition as TypeContainer;
1243 var public_fields = new List<FieldSpec> ();
1244 var non_public_fields = new List<FieldSpec> ();
1247 var fields = tc.Fields;
1249 if (fields != null) {
1250 foreach (FieldBase field in fields) {
1251 if ((field.ModFlags & Modifiers.STATIC) != 0)
1253 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1254 public_fields.Add (field.Spec);
1256 non_public_fields.Add (field.Spec);
1261 CountPublic = public_fields.Count;
1262 CountNonPublic = non_public_fields.Count;
1263 Count = CountPublic + CountNonPublic;
1265 Fields = new FieldSpec[Count];
1266 public_fields.CopyTo (Fields, 0);
1267 non_public_fields.CopyTo (Fields, CountPublic);
1269 struct_field_hash = new Dictionary<string, TypeInfo> ();
1270 field_hash = new Dictionary<string, int> ();
1273 StructFields = new TypeInfo [Count];
1274 StructInfo[] sinfo = new StructInfo [Count];
1278 for (int i = 0; i < Count; i++) {
1279 var field = Fields [i];
1281 sinfo [i] = GetStructInfo (field.MemberType);
1282 if (sinfo [i] == null)
1283 field_hash.Add (field.Name, ++Length);
1284 else if (sinfo [i].InTransit) {
1292 TotalLength = Length + 1;
1293 for (int i = 0; i < Count; i++) {
1294 var field = Fields [i];
1296 if (sinfo [i] == null)
1299 field_hash.Add (field.Name, TotalLength);
1301 HasStructFields = true;
1302 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1303 struct_field_hash.Add (field.Name, StructFields [i]);
1304 TotalLength += sinfo [i].TotalLength;
1308 public int this [string name] {
1311 if (!field_hash.TryGetValue (name, out val))
1318 public TypeInfo GetStructField (string name)
1321 if (struct_field_hash.TryGetValue (name, out ti))
1327 public static StructInfo GetStructInfo (TypeSpec type)
1329 if (!type.IsStruct || type.BuiltinType > 0)
1333 if (field_type_hash.TryGetValue (type, out info))
1336 return new StructInfo (type);
1342 // This is used by the flow analysis code to store information about a single local variable
1343 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1344 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1345 // it has been assigned or not, but for structs, we need this information for each of its fields.
1347 public class VariableInfo {
1348 public readonly string Name;
1349 public readonly TypeInfo TypeInfo;
1352 // The bit offset of this variable in the flow vector.
1354 public readonly int Offset;
1357 // The number of bits this variable needs in the flow vector.
1358 // The first bit always specifies whether the variable as such has been assigned while
1359 // the remaining bits contain this information for each of a struct's fields.
1361 public readonly int Length;
1364 // If this is a parameter of local variable.
1366 public readonly bool IsParameter;
1368 public readonly LocalVariable LocalInfo;
1370 readonly VariableInfo Parent;
1371 VariableInfo[] sub_info;
1373 bool is_ever_assigned;
1374 public bool IsEverAssigned {
1375 get { return is_ever_assigned; }
1378 protected VariableInfo (string name, TypeSpec type, int offset)
1381 this.Offset = offset;
1382 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1384 Length = TypeInfo.TotalLength;
1389 protected VariableInfo (VariableInfo parent, TypeInfo type)
1391 this.Name = parent.Name;
1392 this.TypeInfo = type;
1393 this.Offset = parent.Offset + type.Offset;
1394 this.Parent = parent;
1395 this.Length = type.TotalLength;
1397 this.IsParameter = parent.IsParameter;
1398 this.LocalInfo = parent.LocalInfo;
1403 protected void Initialize ()
1405 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1406 if (sub_fields != null) {
1407 sub_info = new VariableInfo [sub_fields.Length];
1408 for (int i = 0; i < sub_fields.Length; i++) {
1409 if (sub_fields [i] != null)
1410 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1413 sub_info = new VariableInfo [0];
1416 public VariableInfo (LocalVariable local_info, int offset)
1417 : this (local_info.Name, local_info.Type, offset)
1419 this.LocalInfo = local_info;
1420 this.IsParameter = false;
1423 public VariableInfo (ParametersCompiled ip, int i, int offset)
1424 : this (ip.FixedParameters [i].Name, ip.Types [i], offset)
1426 this.IsParameter = true;
1429 public bool IsAssigned (ResolveContext ec)
1431 return !ec.DoFlowAnalysis ||
1432 (ec.OmitStructFlowAnalysis && TypeInfo.Type.IsStruct) ||
1433 ec.CurrentBranching.IsAssigned (this);
1436 public bool IsAssigned (ResolveContext ec, Location loc)
1438 if (IsAssigned (ec))
1441 ec.Report.Error (165, loc,
1442 "Use of unassigned local variable `" + Name + "'");
1443 ec.CurrentBranching.SetAssigned (this);
1447 public bool IsAssigned (MyBitVector vector)
1452 if (vector [Offset])
1455 // FIXME: Fix SetFieldAssigned to set the whole range like SetAssigned below. Then, get rid of this stanza
1456 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent) {
1457 if (vector [parent.Offset]) {
1458 // 'parent' is assigned, but someone forgot to note that all its components are assigned too
1459 parent.SetAssigned (vector);
1464 // Return unless this is a struct.
1465 if (!TypeInfo.IsStruct)
1468 // Ok, so each field must be assigned.
1469 for (int i = 0; i < TypeInfo.Length; i++) {
1470 if (!vector [Offset + i + 1])
1474 // Ok, now check all fields which are structs.
1475 for (int i = 0; i < sub_info.Length; i++) {
1476 VariableInfo sinfo = sub_info [i];
1480 if (!sinfo.IsAssigned (vector))
1484 vector [Offset] = true;
1485 is_ever_assigned = true;
1489 public void SetAssigned (ResolveContext ec)
1491 if (ec.DoFlowAnalysis)
1492 ec.CurrentBranching.SetAssigned (this);
1495 public void SetAssigned (MyBitVector vector)
1498 vector [Offset] = true;
1500 vector.SetRange (Offset, Length);
1501 is_ever_assigned = true;
1504 public bool IsFieldAssigned (ResolveContext ec, string name, Location loc)
1506 if (!ec.DoFlowAnalysis ||
1507 ec.OmitStructFlowAnalysis && TypeInfo.IsStruct ||
1508 ec.CurrentBranching.IsFieldAssigned (this, name))
1511 ec.Report.Error (170, loc,
1512 "Use of possibly unassigned field `" + name + "'");
1513 ec.CurrentBranching.SetFieldAssigned (this, name);
1517 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1519 int field_idx = TypeInfo.GetFieldIndex (field_name);
1524 return vector [Offset + field_idx];
1527 public void SetFieldAssigned (ResolveContext ec, string name)
1529 if (ec.DoFlowAnalysis)
1530 ec.CurrentBranching.SetFieldAssigned (this, name);
1533 public void SetFieldAssigned (MyBitVector vector, string field_name)
1535 int field_idx = TypeInfo.GetFieldIndex (field_name);
1540 vector [Offset + field_idx] = true;
1541 is_ever_assigned = true;
1544 public VariableInfo GetSubStruct (string name)
1546 TypeInfo type = TypeInfo.GetSubStruct (name);
1551 return new VariableInfo (this, type);
1554 public override string ToString ()
1556 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1557 Name, TypeInfo, Offset, Length, IsParameter);
1562 // This is a special bit vector which can inherit from another bit vector doing a
1563 // copy-on-write strategy. The inherited vector may have a smaller size than the
1566 public class MyBitVector {
1567 public readonly int Count;
1568 public static readonly MyBitVector Empty = new MyBitVector ();
1570 // Invariant: vector != null => vector.Count == Count
1571 // Invariant: vector == null || shared == null
1572 // i.e., at most one of 'vector' and 'shared' can be non-null. They can both be null -- that means all-ones
1573 // The object in 'shared' cannot be modified, while 'vector' can be freely modified
1574 System.Collections.BitArray vector, shared;
1578 shared = new System.Collections.BitArray (0, false);
1581 public MyBitVector (MyBitVector InheritsFrom, int Count)
1583 if (InheritsFrom != null)
1584 shared = InheritsFrom.MakeShared (Count);
1589 System.Collections.BitArray MakeShared (int new_count)
1591 // Post-condition: vector == null
1593 // ensure we don't leak out dirty bits from the BitVector we inherited from
1594 if (new_count > Count &&
1595 ((shared != null && shared.Count > Count) ||
1596 (shared == null && vector == null)))
1597 initialize_vector ();
1599 if (vector != null) {
1608 // Get/set bit `index' in the bit vector.
1610 public bool this [int index] {
1613 // FIXME: Disabled due to missing anonymous method flow analysis
1614 // throw new ArgumentOutOfRangeException ();
1618 return vector [index];
1621 if (index < shared.Count)
1622 return shared [index];
1627 // Only copy the vector if we're actually modifying it.
1628 if (this [index] != value) {
1630 initialize_vector ();
1631 vector [index] = value;
1637 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1638 // different size than the current one.
1640 private MyBitVector Or (MyBitVector new_vector)
1642 if (Count == 0 || new_vector.Count == 0)
1645 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1648 int n = new_vector.Count;
1650 for (int i = 0; i < n; ++i)
1658 if (Count == o.Count) {
1659 if (vector == null) {
1662 initialize_vector ();
1672 for (int i = 0; i < min; i++) {
1681 // Performs an `and' operation on the bit vector. The `new_vector' may have
1682 // a different size than the current one.
1684 private MyBitVector And (MyBitVector new_vector)
1689 var o = new_vector.vector != null ? new_vector.vector : new_vector.shared;
1692 for (int i = new_vector.Count; i < Count; ++i)
1702 if (Count == o.Count) {
1703 if (vector == null) {
1704 if (shared == null) {
1705 shared = new_vector.MakeShared (Count);
1708 initialize_vector ();
1718 for (int i = 0; i < min; i++) {
1723 for (int i = min; i < Count; i++)
1729 public static MyBitVector operator & (MyBitVector a, MyBitVector b)
1737 if (a.Count > b.Count)
1738 return a.Clone ().And (b);
1740 return b.Clone ().And (a);
1743 public static MyBitVector operator | (MyBitVector a, MyBitVector b)
1748 return new MyBitVector (null, b.Count);
1750 return new MyBitVector (null, a.Count);
1751 if (a.Count > b.Count)
1752 return a.Clone ().Or (b);
1754 return b.Clone ().Or (a);
1757 public MyBitVector Clone ()
1759 return Count == 0 ? Empty : new MyBitVector (this, Count);
1762 public void SetRange (int offset, int length)
1764 if (offset > Count || offset + length > Count)
1765 throw new ArgumentOutOfRangeException ("flow-analysis");
1767 if (shared == null && vector == null)
1771 if (shared != null) {
1772 if (offset + length <= shared.Count) {
1773 for (; i < length; ++i)
1774 if (!shared [i+offset])
1779 initialize_vector ();
1781 for (; i < length; ++i)
1782 vector [i+offset] = true;
1786 public void SetAll (bool value)
1788 // Don't clobber Empty
1791 shared = value ? null : Empty.MakeShared (Count);
1795 void initialize_vector ()
1797 // Post-condition: vector != null
1798 if (shared == null) {
1799 vector = new System.Collections.BitArray (Count, true);
1803 vector = new System.Collections.BitArray (shared);
1804 if (Count != vector.Count)
1805 vector.Length = Count;
1809 StringBuilder Dump (StringBuilder sb)
1811 var dump = vector == null ? shared : vector;
1813 return sb.Append ("/");
1816 for (int i = 0; i < dump.Count; i++)
1817 sb.Append (dump [i] ? "1" : "0");
1821 public override string ToString ()
1823 return Dump (new StringBuilder ("{")).Append ("}").ToString ();