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;
119 // Performs an `And' operation on the FlowReturns status
120 // (for instance, a block only returns Always if all its siblings
123 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
125 if (a == FlowReturns.Undefined)
129 case FlowReturns.Never:
130 if (b == FlowReturns.Never)
131 return FlowReturns.Never;
133 return FlowReturns.Sometimes;
135 case FlowReturns.Sometimes:
136 return FlowReturns.Sometimes;
138 case FlowReturns.Always:
139 if (b == FlowReturns.Always)
140 return FlowReturns.Always;
142 return FlowReturns.Sometimes;
145 throw new ArgumentException ();
149 public static FlowReturns OrFlowReturns (FlowReturns a, FlowReturns b)
151 if (a == FlowReturns.Undefined)
155 case FlowReturns.Never:
158 case FlowReturns.Sometimes:
159 if (b == FlowReturns.Always)
160 return FlowReturns.Always;
162 return FlowReturns.Sometimes;
164 case FlowReturns.Always:
165 return FlowReturns.Always;
168 throw new ArgumentException ();
172 public static void And (ref Reachability a, Reachability b, bool do_break)
180 // `break' does not "break" in a Switch or a LoopBlock
182 bool a_breaks = do_break && a.AlwaysBreaks;
183 bool b_breaks = do_break && b.AlwaysBreaks;
185 bool a_has_barrier, b_has_barrier;
188 // This is the normal case: the code following a barrier
189 // cannot be reached.
191 a_has_barrier = a.AlwaysHasBarrier;
192 b_has_barrier = b.AlwaysHasBarrier;
195 // Special case for Switch and LoopBlocks: we can reach the
196 // code after the barrier via the `break'.
198 a_has_barrier = !a.AlwaysBreaks && a.AlwaysHasBarrier;
199 b_has_barrier = !b.AlwaysBreaks && b.AlwaysHasBarrier;
202 bool a_unreachable = a_breaks || a.AlwaysThrows || a_has_barrier;
203 bool b_unreachable = b_breaks || b.AlwaysThrows || b_has_barrier;
206 // Do all code paths always return ?
208 if (a.AlwaysReturns) {
209 if (b.AlwaysReturns || b_unreachable)
210 a.returns = FlowReturns.Always;
212 a.returns = FlowReturns.Sometimes;
213 } else if (b.AlwaysReturns) {
214 if (a.AlwaysReturns || a_unreachable)
215 a.returns = FlowReturns.Always;
217 a.returns = FlowReturns.Sometimes;
218 } else if (!a.MayReturn) {
220 a.returns = FlowReturns.Sometimes;
222 a.returns = FlowReturns.Never;
223 } else if (!b.MayReturn) {
225 a.returns = FlowReturns.Sometimes;
227 a.returns = FlowReturns.Never;
230 a.breaks = AndFlowReturns (a.breaks, b.breaks);
231 a.throws = AndFlowReturns (a.throws, b.throws);
232 a.barrier = AndFlowReturns (a.barrier, b.barrier);
234 a.reachable = AndFlowReturns (a.reachable, b.reachable);
237 public void Or (Reachability b)
239 returns = OrFlowReturns (returns, b.returns);
240 breaks = OrFlowReturns (breaks, b.breaks);
241 throws = OrFlowReturns (throws, b.throws);
242 barrier = OrFlowReturns (barrier, b.barrier);
247 public static Reachability Never ()
249 return new Reachability (
250 FlowReturns.Never, FlowReturns.Never,
251 FlowReturns.Never, FlowReturns.Never);
256 if ((returns == FlowReturns.Always) || (breaks == FlowReturns.Always) ||
257 (throws == FlowReturns.Always) || (barrier == FlowReturns.Always))
258 reachable = FlowReturns.Never;
259 else if ((returns == FlowReturns.Never) && (breaks == FlowReturns.Never) &&
260 (throws == FlowReturns.Never) && (barrier == FlowReturns.Never))
261 reachable = FlowReturns.Always;
263 reachable = FlowReturns.Sometimes;
266 public bool AlwaysBreaks {
267 get { return breaks == FlowReturns.Always; }
270 public bool MayBreak {
271 get { return breaks != FlowReturns.Never; }
274 public bool AlwaysReturns {
275 get { return returns == FlowReturns.Always; }
278 public bool MayReturn {
279 get { return returns != FlowReturns.Never; }
282 public bool AlwaysThrows {
283 get { return throws == FlowReturns.Always; }
286 public bool MayThrow {
287 get { return throws != FlowReturns.Never; }
290 public bool AlwaysHasBarrier {
291 get { return barrier == FlowReturns.Always; }
294 public bool MayHaveBarrier {
295 get { return barrier != FlowReturns.Never; }
298 public bool IsUnreachable {
299 get { return reachable == FlowReturns.Never; }
302 public void SetReturns ()
304 returns = FlowReturns.Always;
308 public void SetReturnsSometimes ()
310 returns = FlowReturns.Sometimes;
314 public void SetBreaks ()
316 breaks = FlowReturns.Always;
320 public void ResetBreaks ()
322 breaks = FlowReturns.Never;
326 public void SetThrows ()
328 throws = FlowReturns.Always;
332 public void SetBarrier ()
334 barrier = FlowReturns.Always;
338 static string ShortName (FlowReturns returns)
341 case FlowReturns.Never:
343 case FlowReturns.Sometimes:
350 public override string ToString ()
352 return String.Format ("[{0}:{1}:{2}:{3}:{4}]",
353 ShortName (returns), ShortName (breaks),
354 ShortName (throws), ShortName (barrier),
355 ShortName (reachable));
359 public static FlowBranching CreateBranching (FlowBranching parent, BranchingType type, Block block, Location loc)
362 case BranchingType.Exception:
363 return new FlowBranchingException (parent, block, loc);
365 case BranchingType.Switch:
366 return new FlowBranchingBlock (parent, type, SiblingType.SwitchSection, block, loc);
368 case BranchingType.SwitchSection:
369 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
371 case BranchingType.Block:
372 return new FlowBranchingBlock (parent, type, SiblingType.Block, block, loc);
374 case BranchingType.Loop:
375 return new FlowBranchingLoop (parent, block, loc);
378 return new FlowBranchingBlock (parent, type, SiblingType.Conditional, block, loc);
383 // The type of this flow branching.
385 public readonly BranchingType Type;
388 // The block this branching is contained in. This may be null if it's not
389 // a top-level block and it doesn't declare any local variables.
391 public readonly Block Block;
394 // The parent of this branching or null if this is the top-block.
396 public readonly FlowBranching Parent;
399 // Start-Location of this flow branching.
401 public readonly Location Location;
404 // If this is an infinite loop.
406 public bool Infinite;
411 VariableMap param_map, local_map;
413 static int next_id = 0;
417 // The vector contains a BitArray with information about which local variables
418 // and parameters are already initialized at the current code position.
420 public class UsageVector {
422 // The type of this branching.
424 public readonly SiblingType Type;
427 // Start location of this branching.
429 public readonly Location Location;
432 // If this is true, then the usage vector has been modified and must be
433 // merged when we're done with this branching.
438 // The number of parameters in this block.
440 public readonly int CountParameters;
443 // The number of locals in this block.
445 public readonly int CountLocals;
448 // If not null, then we inherit our state from this vector and do a
449 // copy-on-write. If null, then we're the first sibling in a top-level
450 // block and inherit from the empty vector.
452 public readonly UsageVector InheritsFrom;
455 // This is used to construct a list of UsageVector's.
457 public UsageVector Next;
462 MyBitVector locals, parameters;
463 Reachability reachability;
465 static int next_id = 0;
469 // Normally, you should not use any of these constructors.
471 public UsageVector (SiblingType type, UsageVector parent, Location loc, int num_params, int num_locals)
475 this.InheritsFrom = parent;
476 this.CountParameters = num_params;
477 this.CountLocals = num_locals;
479 if (parent != null) {
481 locals = new MyBitVector (parent.locals, CountLocals);
484 parameters = new MyBitVector (parent.parameters, num_params);
486 reachability = parent.Reachability.Clone ();
489 locals = new MyBitVector (null, CountLocals);
492 parameters = new MyBitVector (null, num_params);
494 reachability = Reachability.Never ();
500 public UsageVector (SiblingType type, UsageVector parent, Location loc)
501 : this (type, parent, loc, parent.CountParameters, parent.CountLocals)
504 public UsageVector (MyBitVector parameters, MyBitVector locals,
505 Reachability reachability, Location loc)
507 this.Type = SiblingType.Block;
510 this.reachability = reachability;
511 this.parameters = parameters;
512 this.locals = locals;
518 // This does a deep copy of the usage vector.
520 public UsageVector Clone ()
522 UsageVector retval = new UsageVector (Type, null, Location, CountParameters, CountLocals);
524 if (retval.locals != null)
525 retval.locals = locals.Clone ();
527 if (parameters != null)
528 retval.parameters = parameters.Clone ();
530 retval.reachability = reachability.Clone ();
535 public bool IsAssigned (VariableInfo var)
537 if (!var.IsParameter && Reachability.AlwaysBreaks)
540 return var.IsAssigned (var.IsParameter ? parameters : locals);
543 public void SetAssigned (VariableInfo var)
545 if (!var.IsParameter && Reachability.AlwaysBreaks)
549 var.SetAssigned (var.IsParameter ? parameters : locals);
552 public bool IsFieldAssigned (VariableInfo var, string name)
554 if (!var.IsParameter && Reachability.AlwaysBreaks)
557 return var.IsFieldAssigned (var.IsParameter ? parameters : locals, name);
560 public void SetFieldAssigned (VariableInfo var, string name)
562 if (!var.IsParameter && Reachability.AlwaysBreaks)
566 var.SetFieldAssigned (var.IsParameter ? parameters : locals, name);
569 public Reachability Reachability {
575 public void Return ()
577 if (!reachability.IsUnreachable) {
579 reachability.SetReturns ();
585 if (!reachability.IsUnreachable) {
587 reachability.SetBreaks ();
593 if (!reachability.IsUnreachable) {
595 reachability.SetThrows ();
601 if (!reachability.IsUnreachable) {
603 reachability.SetBarrier ();
608 // Merges a child branching.
610 public UsageVector MergeChild (FlowBranching branching)
612 UsageVector result = branching.Merge ();
614 Report.Debug (2, " MERGING CHILD", this, IsDirty,
615 result.ParameterVector, result.LocalVector,
616 result.Reachability, reachability, Type);
618 Reachability new_r = result.Reachability;
620 if (branching.Type == BranchingType.Loop) {
621 bool may_leave_loop = new_r.MayBreak;
622 new_r.ResetBreaks ();
624 if (branching.Infinite && !may_leave_loop) {
625 if (new_r.Returns == FlowReturns.Sometimes) {
626 // If we're an infinite loop and do not break,
627 // the code after the loop can never be reached.
628 // However, if we may return from the loop,
629 // then we do always return (or stay in the
636 if (new_r.Returns == FlowReturns.Always) {
637 // We're either finite or we may leave the loop.
638 new_r.SetReturnsSometimes ();
641 } else if (branching.Type == BranchingType.Switch)
642 new_r.ResetBreaks ();
645 // We've now either reached the point after the branching or we will
646 // never get there since we always return or always throw an exception.
648 // If we can reach the point after the branching, mark all locals and
649 // parameters as initialized which have been initialized in all branches
650 // we need to look at (see above).
653 if ((Type == SiblingType.SwitchSection) && !new_r.IsUnreachable) {
654 Report.Error (163, Location,
655 "Control cannot fall through from one " +
656 "case label to another");
660 if (locals != null && result.LocalVector != null)
661 locals.Or (result.LocalVector);
663 if (result.ParameterVector != null)
664 parameters.Or (result.ParameterVector);
666 reachability.Or (new_r);
668 Report.Debug (2, " MERGING CHILD DONE", this, result,
669 new_r, reachability);
676 protected void MergeFinally (FlowBranching branching, UsageVector f_origins,
677 MyBitVector f_params)
679 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
680 MyBitVector temp_params = f_params.Clone ();
681 temp_params.Or (vector.Parameters);
685 public void MergeFinally (FlowBranching branching, UsageVector f_vector,
686 UsageVector f_origins)
688 if (parameters != null) {
689 if (f_vector != null) {
690 MergeFinally (branching, f_origins, f_vector.Parameters);
691 MyBitVector.Or (ref parameters, f_vector.ParameterVector);
693 MergeFinally (branching, f_origins, parameters);
696 if (f_vector != null && f_vector.LocalVector != null)
697 MyBitVector.Or (ref locals, f_vector.LocalVector);
701 // Tells control flow analysis that the current code position may be reached with
702 // a forward jump from any of the origins listed in `origin_vectors' which is a
703 // list of UsageVectors.
705 // This is used when resolving forward gotos - in the following example, the
706 // variable `a' is uninitialized in line 8 becase this line may be reached via
707 // the goto in line 4:
717 // 8 Console.WriteLine (a);
720 public void MergeJumpOrigins (UsageVector o_vectors)
722 Report.Debug (1, " MERGING JUMP ORIGINS", this);
724 reachability = Reachability.Never ();
726 if (o_vectors == null)
731 for (UsageVector vector = o_vectors; vector != null;
732 vector = vector.Next) {
733 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
736 if (locals != null && vector.Locals != null)
737 locals.Or (vector.locals);
739 if (parameters != null)
740 parameters.Or (vector.parameters);
743 if (locals != null && vector.Locals != null)
744 locals.And (vector.locals);
745 if (parameters != null)
746 parameters.And (vector.parameters);
749 Reachability.And (ref reachability, vector.Reachability, true);
752 Report.Debug (1, " MERGING JUMP ORIGINS DONE", this);
756 // This is used at the beginning of a finally block if there were
757 // any return statements in the try block or one of the catch blocks.
759 public void MergeFinallyOrigins (UsageVector f_origins)
761 Report.Debug (1, " MERGING FINALLY ORIGIN", this);
763 reachability = Reachability.Never ();
765 for (UsageVector vector = f_origins; vector != null; vector = vector.Next) {
766 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
768 if (parameters != null)
769 parameters.And (vector.parameters);
771 Reachability.And (ref reachability, vector.Reachability, true);
774 Report.Debug (1, " MERGING FINALLY ORIGIN DONE", this);
777 public void MergeBreakOrigins (UsageVector o_vectors)
779 Report.Debug (1, " MERGING BREAK ORIGINS", this);
781 if (o_vectors == null)
786 for (UsageVector vector = o_vectors; vector != null;
787 vector = vector.Next) {
788 Report.Debug (1, " MERGING BREAK ORIGIN", vector);
791 if (locals != null && vector.Locals != null)
792 locals.Or (vector.locals);
794 if (parameters != null)
795 parameters.Or (vector.parameters);
798 if (locals != null && vector.Locals != null)
799 locals.And (vector.locals);
800 if (parameters != null)
801 parameters.And (vector.parameters);
805 Report.Debug (1, " MERGING BREAK ORIGINS DONE", this);
808 public void CheckOutParameters (FlowBranching branching)
810 if (parameters != null)
811 branching.CheckOutParameters (parameters, branching.Location);
815 // Performs an `or' operation on the locals and the parameters.
817 public void Or (UsageVector new_vector)
820 locals.Or (new_vector.locals);
821 if (parameters != null)
822 parameters.Or (new_vector.parameters);
826 // Performs an `and' operation on the locals.
828 public void AndLocals (UsageVector new_vector)
831 locals.And (new_vector.locals);
834 public bool HasParameters {
836 return parameters != null;
840 public bool HasLocals {
842 return locals != null;
847 // Returns a deep copy of the parameters.
849 public MyBitVector Parameters {
851 if (parameters != null)
852 return parameters.Clone ();
859 // Returns a deep copy of the locals.
861 public MyBitVector Locals {
864 return locals.Clone ();
870 public MyBitVector ParameterVector {
876 public MyBitVector LocalVector {
886 public override string ToString ()
888 StringBuilder sb = new StringBuilder ();
890 sb.Append ("Vector (");
897 sb.Append (reachability);
898 if (parameters != null) {
900 sb.Append (parameters);
906 return sb.ToString ();
911 // Creates a new flow branching which is contained in `parent'.
912 // You should only pass non-null for the `block' argument if this block
913 // introduces any new variables - in this case, we need to create a new
914 // usage vector with a different size than our parent's one.
916 protected FlowBranching (FlowBranching parent, BranchingType type, SiblingType stype,
917 Block block, Location loc)
927 param_map = Block.ParameterMap;
928 local_map = Block.LocalMap;
930 UsageVector parent_vector = parent != null ? parent.CurrentUsageVector : null;
931 vector = new UsageVector (stype, parent_vector, loc, param_map.Length, local_map.Length);
935 param_map = Parent.param_map;
936 local_map = Parent.local_map;
937 vector = new UsageVector (stype, Parent.CurrentUsageVector, loc);
943 public abstract UsageVector CurrentUsageVector {
948 // Creates a sibling of the current usage vector.
950 public virtual void CreateSibling (SiblingType type)
952 AddSibling (new UsageVector (type, Parent.CurrentUsageVector, Location));
954 Report.Debug (1, " CREATED SIBLING", CurrentUsageVector);
957 protected abstract void AddSibling (UsageVector uv);
959 public abstract void Label (UsageVector origin_vectors);
962 // Check whether all `out' parameters have been assigned.
964 public void CheckOutParameters (MyBitVector parameters, Location loc)
966 for (int i = 0; i < param_map.Count; i++) {
967 VariableInfo var = param_map [i];
972 if (var.IsAssigned (parameters))
975 Report.Error (177, loc, "The out parameter `" +
976 var.Name + "' must be " +
977 "assigned before control leave the current method.");
981 protected UsageVector Merge (UsageVector sibling_list)
983 if (sibling_list.Next == null)
986 MyBitVector locals = null;
987 MyBitVector parameters = null;
989 Reachability reachability = null;
991 Report.Debug (2, " MERGING SIBLINGS", this, Name);
993 for (UsageVector child = sibling_list; child != null; child = child.Next) {
994 bool do_break = (Type != BranchingType.Switch) &&
995 (Type != BranchingType.Loop);
997 Report.Debug (2, " MERGING SIBLING ", child,
998 child.ParameterVector, child.LocalVector,
999 reachability, child.Reachability, do_break);
1001 Reachability.And (ref reachability, child.Reachability, do_break);
1003 // A local variable is initialized after a flow branching if it
1004 // has been initialized in all its branches which do neither
1005 // always return or always throw an exception.
1007 // If a branch may return, but does not always return, then we
1008 // can treat it like a never-returning branch here: control will
1009 // only reach the code position after the branching if we did not
1012 // It's important to distinguish between always and sometimes
1013 // returning branches here:
1016 // 2 if (something) {
1020 // 6 Console.WriteLine (a);
1022 // The if block in lines 3-4 always returns, so we must not look
1023 // at the initialization of `a' in line 4 - thus it'll still be
1024 // uninitialized in line 6.
1026 // On the other hand, the following is allowed:
1033 // 6 Console.WriteLine (a);
1035 // Here, `a' is initialized in line 3 and we must not look at
1036 // line 5 since it always returns.
1038 bool do_break_2 = (child.Type != SiblingType.Block) &&
1039 (child.Type != SiblingType.SwitchSection);
1040 bool always_throws = (child.Type != SiblingType.Try) &&
1041 child.Reachability.AlwaysThrows;
1042 bool unreachable = always_throws ||
1043 (do_break_2 && child.Reachability.AlwaysBreaks) ||
1044 child.Reachability.AlwaysReturns ||
1045 child.Reachability.AlwaysHasBarrier;
1047 Report.Debug (2, " MERGING SIBLING #1", reachability,
1048 Type, child.Type, child.Reachability.IsUnreachable,
1049 do_break_2, always_throws, unreachable);
1051 if (!unreachable && (child.LocalVector != null))
1052 MyBitVector.And (ref locals, child.LocalVector);
1054 // An `out' parameter must be assigned in all branches which do
1055 // not always throw an exception.
1056 if ((child.ParameterVector != null) && !child.Reachability.AlwaysThrows)
1057 MyBitVector.And (ref parameters, child.ParameterVector);
1059 Report.Debug (2, " MERGING SIBLING #2", parameters, locals);
1062 if (reachability == null)
1063 reachability = Reachability.Never ();
1065 Report.Debug (2, " MERGING SIBLINGS DONE", parameters, locals,
1066 reachability, Infinite);
1068 return new UsageVector (parameters, locals, reachability, Location);
1071 protected abstract UsageVector Merge ();
1074 // Merge a child branching.
1076 public UsageVector MergeChild (FlowBranching child)
1078 return CurrentUsageVector.MergeChild (child);
1082 // Does the toplevel merging.
1084 public Reachability MergeTopBlock ()
1086 if ((Type != BranchingType.Block) || (Block == null))
1087 throw new NotSupportedException ();
1089 UsageVector vector = new UsageVector (
1090 SiblingType.Conditional, null, Location, param_map.Length, local_map.Length);
1092 UsageVector result = vector.MergeChild (this);
1094 Report.Debug (4, "MERGE TOP BLOCK", Location, vector, result.Reachability);
1096 if (vector.Reachability.Throws != FlowReturns.Always)
1097 CheckOutParameters (vector.Parameters, Location);
1099 return result.Reachability;
1103 // Checks whether we're in a `try' block.
1105 public virtual bool InTryOrCatch (bool is_return)
1107 if ((Block != null) && Block.IsDestructor)
1109 else if (!is_return &&
1110 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1112 else if (Parent != null)
1113 return Parent.InTryOrCatch (is_return);
1119 // Checks whether we're in a `catch' block.
1121 public virtual bool InCatch ()
1124 return Parent.InCatch ();
1130 // Checks whether we're in a `finally' block.
1132 public virtual bool InFinally (bool is_return)
1135 ((Type == BranchingType.Loop) || (Type == BranchingType.Switch)))
1137 else if (Parent != null)
1138 return Parent.InFinally (is_return);
1143 public virtual bool InLoop ()
1145 if (Type == BranchingType.Loop)
1147 else if (Parent != null)
1148 return Parent.InLoop ();
1153 public virtual bool InSwitch ()
1155 if (Type == BranchingType.Switch)
1157 else if (Parent != null)
1158 return Parent.InSwitch ();
1163 public virtual bool BreakCrossesTryCatchBoundary ()
1165 if ((Type == BranchingType.Loop) || (Type == BranchingType.Switch))
1167 else if (Parent != null)
1168 return Parent.BreakCrossesTryCatchBoundary ();
1173 public virtual void AddFinallyVector (UsageVector vector)
1176 Parent.AddFinallyVector (vector);
1177 else if ((Block == null) || !Block.IsDestructor)
1178 throw new NotSupportedException ();
1181 public virtual void AddBreakVector (UsageVector vector)
1184 Parent.AddBreakVector (vector);
1185 else if ((Block == null) || !Block.IsDestructor)
1186 throw new NotSupportedException ();
1189 public bool IsAssigned (VariableInfo vi)
1191 return CurrentUsageVector.IsAssigned (vi);
1194 public bool IsFieldAssigned (VariableInfo vi, string field_name)
1196 if (CurrentUsageVector.IsAssigned (vi))
1199 return CurrentUsageVector.IsFieldAssigned (vi, field_name);
1202 public void SetAssigned (VariableInfo vi)
1204 CurrentUsageVector.SetAssigned (vi);
1207 public void SetFieldAssigned (VariableInfo vi, string name)
1209 CurrentUsageVector.SetFieldAssigned (vi, name);
1212 public override string ToString ()
1214 StringBuilder sb = new StringBuilder ();
1215 sb.Append (GetType ());
1221 if (Block != null) {
1223 sb.Append (Block.ID);
1225 sb.Append (Block.StartLocation);
1228 // sb.Append (Siblings.Length);
1229 // sb.Append (" - ");
1230 sb.Append (CurrentUsageVector);
1232 return sb.ToString ();
1235 public string Name {
1237 return String.Format ("{0} ({1}:{2}:{3})",
1238 GetType (), id, Type, Location);
1243 public class FlowBranchingBlock : FlowBranching
1245 UsageVector sibling_list = null;
1247 public FlowBranchingBlock (FlowBranching parent, BranchingType type,
1248 SiblingType stype, Block block, Location loc)
1249 : base (parent, type, stype, block, loc)
1252 public override UsageVector CurrentUsageVector {
1253 get { return sibling_list; }
1256 protected override void AddSibling (UsageVector sibling)
1258 sibling.Next = sibling_list;
1259 sibling_list = sibling;
1262 public override void Label (UsageVector origin_vectors)
1264 if (!CurrentUsageVector.Reachability.IsUnreachable) {
1265 UsageVector vector = CurrentUsageVector.Clone ();
1266 vector.Next = origin_vectors;
1267 origin_vectors = vector;
1270 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1273 protected override UsageVector Merge ()
1275 return Merge (sibling_list);
1279 public class FlowBranchingLoop : FlowBranchingBlock
1281 UsageVector break_origins;
1283 public FlowBranchingLoop (FlowBranching parent, Block block, Location loc)
1284 : base (parent, BranchingType.Loop, SiblingType.Conditional, block, loc)
1287 public override void AddBreakVector (UsageVector vector)
1289 vector = vector.Clone ();
1290 vector.Next = break_origins;
1291 break_origins = vector;
1294 protected override UsageVector Merge ()
1296 UsageVector vector = base.Merge ();
1298 vector.MergeBreakOrigins (break_origins);
1304 public class FlowBranchingException : FlowBranching
1306 UsageVector current_vector;
1307 UsageVector catch_vectors;
1308 UsageVector finally_vector;
1309 UsageVector finally_origins;
1312 public FlowBranchingException (FlowBranching parent, Block block, Location loc)
1313 : base (parent, BranchingType.Exception, SiblingType.Try, block, loc)
1316 protected override void AddSibling (UsageVector sibling)
1318 if (sibling.Type == SiblingType.Try) {
1319 sibling.Next = catch_vectors;
1320 catch_vectors = sibling;
1322 } else if (sibling.Type == SiblingType.Catch) {
1323 sibling.Next = catch_vectors;
1324 catch_vectors = sibling;
1326 } else if (sibling.Type == SiblingType.Finally) {
1327 sibling.MergeFinallyOrigins (finally_origins);
1328 finally_vector = sibling;
1331 throw new InvalidOperationException ();
1333 current_vector = sibling;
1336 public override UsageVector CurrentUsageVector {
1337 get { return current_vector; }
1340 public override bool InTryOrCatch (bool is_return)
1342 return finally_vector == null;
1345 public override bool InCatch ()
1347 return !in_try && (finally_vector == null);
1350 public override bool InFinally (bool is_return)
1352 return finally_vector != null;
1355 public override bool BreakCrossesTryCatchBoundary ()
1360 public override void AddFinallyVector (UsageVector vector)
1362 vector = vector.Clone ();
1363 vector.Next = finally_origins;
1364 finally_origins = vector;
1367 public override void Label (UsageVector origin_vectors)
1369 CurrentUsageVector.MergeJumpOrigins (origin_vectors);
1372 protected override UsageVector Merge ()
1374 UsageVector vector = Merge (catch_vectors);
1376 vector.MergeFinally (this, finally_vector, finally_origins);
1383 // This is used by the flow analysis code to keep track of the type of local variables
1386 // The flow code uses a BitVector to keep track of whether a variable has been assigned
1387 // or not. This is easy for fundamental types (int, char etc.) or reference types since
1388 // you can only assign the whole variable as such.
1390 // For structs, we also need to keep track of all its fields. To do this, we allocate one
1391 // bit for the struct itself (it's used if you assign/access the whole struct) followed by
1392 // one bit for each of its fields.
1394 // This class computes this `layout' for each type.
1396 public class TypeInfo
1398 public readonly Type Type;
1401 // Total number of bits a variable of this type consumes in the flow vector.
1403 public readonly int TotalLength;
1406 // Number of bits the simple fields of a variable of this type consume
1407 // in the flow vector.
1409 public readonly int Length;
1412 // This is only used by sub-structs.
1414 public readonly int Offset;
1417 // If this is a struct.
1419 public readonly bool IsStruct;
1422 // If this is a struct, all fields which are structs theirselves.
1424 public TypeInfo[] SubStructInfo;
1426 protected readonly StructInfo struct_info;
1427 private static Hashtable type_hash = new Hashtable ();
1429 public static TypeInfo GetTypeInfo (Type type)
1431 TypeInfo info = (TypeInfo) type_hash [type];
1435 info = new TypeInfo (type);
1436 type_hash.Add (type, info);
1440 public static TypeInfo GetTypeInfo (TypeContainer tc)
1442 TypeInfo info = (TypeInfo) type_hash [tc.TypeBuilder];
1446 info = new TypeInfo (tc);
1447 type_hash.Add (tc.TypeBuilder, info);
1451 private TypeInfo (Type type)
1455 struct_info = StructInfo.GetStructInfo (type);
1456 if (struct_info != null) {
1457 Length = struct_info.Length;
1458 TotalLength = struct_info.TotalLength;
1459 SubStructInfo = struct_info.StructFields;
1468 private TypeInfo (TypeContainer tc)
1470 this.Type = tc.TypeBuilder;
1472 struct_info = StructInfo.GetStructInfo (tc);
1473 if (struct_info != null) {
1474 Length = struct_info.Length;
1475 TotalLength = struct_info.TotalLength;
1476 SubStructInfo = struct_info.StructFields;
1485 protected TypeInfo (StructInfo struct_info, int offset)
1487 this.struct_info = struct_info;
1488 this.Offset = offset;
1489 this.Length = struct_info.Length;
1490 this.TotalLength = struct_info.TotalLength;
1491 this.SubStructInfo = struct_info.StructFields;
1492 this.Type = struct_info.Type;
1493 this.IsStruct = true;
1496 public int GetFieldIndex (string name)
1498 if (struct_info == null)
1501 return struct_info [name];
1504 public TypeInfo GetSubStruct (string name)
1506 if (struct_info == null)
1509 return struct_info.GetStructField (name);
1513 // A struct's constructor must always assign all fields.
1514 // This method checks whether it actually does so.
1516 public bool IsFullyInitialized (FlowBranching branching, VariableInfo vi, Location loc)
1518 if (struct_info == null)
1522 for (int i = 0; i < struct_info.Count; i++) {
1523 FieldInfo field = struct_info.Fields [i];
1525 if (!branching.IsFieldAssigned (vi, field.Name)) {
1526 Report.Error (171, loc,
1527 "Field `" + TypeManager.CSharpName (Type) +
1528 "." + field.Name + "' must be fully initialized " +
1529 "before control leaves the constructor");
1537 public override string ToString ()
1539 return String.Format ("TypeInfo ({0}:{1}:{2}:{3})",
1540 Type, Offset, Length, TotalLength);
1543 protected class StructInfo {
1544 public readonly Type Type;
1545 public readonly FieldInfo[] Fields;
1546 public readonly TypeInfo[] StructFields;
1547 public readonly int Count;
1548 public readonly int CountPublic;
1549 public readonly int CountNonPublic;
1550 public readonly int Length;
1551 public readonly int TotalLength;
1552 public readonly bool HasStructFields;
1554 private static Hashtable field_type_hash = new Hashtable ();
1555 private Hashtable struct_field_hash;
1556 private Hashtable field_hash;
1558 protected bool InTransit = false;
1560 // Private constructor. To save memory usage, we only need to create one instance
1561 // of this class per struct type.
1562 private StructInfo (Type type)
1566 field_type_hash.Add (type, this);
1568 if (type is TypeBuilder) {
1569 TypeContainer tc = TypeManager.LookupTypeContainer (type);
1571 ArrayList fields = tc.Fields;
1573 ArrayList public_fields = new ArrayList ();
1574 ArrayList non_public_fields = new ArrayList ();
1576 if (fields != null) {
1577 foreach (Field field in fields) {
1578 if ((field.ModFlags & Modifiers.STATIC) != 0)
1580 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
1581 public_fields.Add (field.FieldBuilder);
1583 non_public_fields.Add (field.FieldBuilder);
1587 CountPublic = public_fields.Count;
1588 CountNonPublic = non_public_fields.Count;
1589 Count = CountPublic + CountNonPublic;
1591 Fields = new FieldInfo [Count];
1592 public_fields.CopyTo (Fields, 0);
1593 non_public_fields.CopyTo (Fields, CountPublic);
1595 FieldInfo[] public_fields = type.GetFields (
1596 BindingFlags.Instance|BindingFlags.Public);
1597 FieldInfo[] non_public_fields = type.GetFields (
1598 BindingFlags.Instance|BindingFlags.NonPublic);
1600 CountPublic = public_fields.Length;
1601 CountNonPublic = non_public_fields.Length;
1602 Count = CountPublic + CountNonPublic;
1604 Fields = new FieldInfo [Count];
1605 public_fields.CopyTo (Fields, 0);
1606 non_public_fields.CopyTo (Fields, CountPublic);
1609 struct_field_hash = new Hashtable ();
1610 field_hash = new Hashtable ();
1613 StructFields = new TypeInfo [Count];
1614 StructInfo[] sinfo = new StructInfo [Count];
1618 for (int i = 0; i < Count; i++) {
1619 FieldInfo field = (FieldInfo) Fields [i];
1621 sinfo [i] = GetStructInfo (field.FieldType);
1622 if (sinfo [i] == null)
1623 field_hash.Add (field.Name, ++Length);
1624 else if (sinfo [i].InTransit) {
1625 Report.Error (523, String.Format (
1626 "Struct member '{0}.{1}' of type '{2}' causes " +
1627 "a cycle in the structure layout",
1628 type, field.Name, sinfo [i].Type));
1636 TotalLength = Length + 1;
1637 for (int i = 0; i < Count; i++) {
1638 FieldInfo field = (FieldInfo) Fields [i];
1640 if (sinfo [i] == null)
1643 field_hash.Add (field.Name, TotalLength);
1645 HasStructFields = true;
1646 StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
1647 struct_field_hash.Add (field.Name, StructFields [i]);
1648 TotalLength += sinfo [i].TotalLength;
1652 public int this [string name] {
1654 if (field_hash.Contains (name))
1655 return (int) field_hash [name];
1661 public TypeInfo GetStructField (string name)
1663 return (TypeInfo) struct_field_hash [name];
1666 public static StructInfo GetStructInfo (Type type)
1668 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
1669 TypeManager.IsBuiltinType (type))
1672 StructInfo info = (StructInfo) field_type_hash [type];
1676 return new StructInfo (type);
1679 public static StructInfo GetStructInfo (TypeContainer tc)
1681 StructInfo info = (StructInfo) field_type_hash [tc.TypeBuilder];
1685 return new StructInfo (tc.TypeBuilder);
1691 // This is used by the flow analysis code to store information about a single local variable
1692 // or parameter. Depending on the variable's type, we need to allocate one or more elements
1693 // in the BitVector - if it's a fundamental or reference type, we just need to know whether
1694 // it has been assigned or not, but for structs, we need this information for each of its fields.
1696 public class VariableInfo {
1697 public readonly string Name;
1698 public readonly TypeInfo TypeInfo;
1701 // The bit offset of this variable in the flow vector.
1703 public readonly int Offset;
1706 // The number of bits this variable needs in the flow vector.
1707 // The first bit always specifies whether the variable as such has been assigned while
1708 // the remaining bits contain this information for each of a struct's fields.
1710 public readonly int Length;
1713 // If this is a parameter of local variable.
1715 public readonly bool IsParameter;
1717 public readonly LocalInfo LocalInfo;
1718 public readonly int ParameterIndex;
1720 readonly VariableInfo Parent;
1721 VariableInfo[] sub_info;
1723 protected VariableInfo (string name, Type type, int offset)
1726 this.Offset = offset;
1727 this.TypeInfo = TypeInfo.GetTypeInfo (type);
1729 Length = TypeInfo.TotalLength;
1734 protected VariableInfo (VariableInfo parent, TypeInfo type)
1736 this.Name = parent.Name;
1737 this.TypeInfo = type;
1738 this.Offset = parent.Offset + type.Offset;
1739 this.Parent = parent;
1740 this.Length = type.TotalLength;
1742 this.IsParameter = parent.IsParameter;
1743 this.LocalInfo = parent.LocalInfo;
1744 this.ParameterIndex = parent.ParameterIndex;
1749 protected void Initialize ()
1751 TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
1752 if (sub_fields != null) {
1753 sub_info = new VariableInfo [sub_fields.Length];
1754 for (int i = 0; i < sub_fields.Length; i++) {
1755 if (sub_fields [i] != null)
1756 sub_info [i] = new VariableInfo (this, sub_fields [i]);
1759 sub_info = new VariableInfo [0];
1762 public VariableInfo (LocalInfo local_info, int offset)
1763 : this (local_info.Name, local_info.VariableType, offset)
1765 this.LocalInfo = local_info;
1766 this.IsParameter = false;
1769 public VariableInfo (string name, Type type, int param_idx, int offset)
1770 : this (name, type, offset)
1772 this.ParameterIndex = param_idx;
1773 this.IsParameter = true;
1776 public bool IsAssigned (EmitContext ec)
1778 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (this);
1781 public bool IsAssigned (EmitContext ec, Location loc)
1783 if (IsAssigned (ec))
1786 Report.Error (165, loc,
1787 "Use of unassigned local variable `" + Name + "'");
1788 ec.CurrentBranching.SetAssigned (this);
1792 public bool IsAssigned (MyBitVector vector)
1794 if (vector [Offset])
1797 for (VariableInfo parent = Parent; parent != null; parent = parent.Parent)
1798 if (vector [parent.Offset])
1801 // Return unless this is a struct.
1802 if (!TypeInfo.IsStruct)
1805 // Ok, so each field must be assigned.
1806 for (int i = 0; i < TypeInfo.Length; i++) {
1807 if (!vector [Offset + i + 1])
1811 // Ok, now check all fields which are structs.
1812 for (int i = 0; i < sub_info.Length; i++) {
1813 VariableInfo sinfo = sub_info [i];
1817 if (!sinfo.IsAssigned (vector))
1821 vector [Offset] = true;
1825 public void SetAssigned (EmitContext ec)
1827 if (ec.DoFlowAnalysis)
1828 ec.CurrentBranching.SetAssigned (this);
1831 public void SetAssigned (MyBitVector vector)
1833 vector [Offset] = true;
1836 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
1838 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsFieldAssigned (this, name))
1841 Report.Error (170, loc,
1842 "Use of possibly unassigned field `" + name + "'");
1843 ec.CurrentBranching.SetFieldAssigned (this, name);
1847 public bool IsFieldAssigned (MyBitVector vector, string field_name)
1849 int field_idx = TypeInfo.GetFieldIndex (field_name);
1854 return vector [Offset + field_idx];
1857 public void SetFieldAssigned (EmitContext ec, string name)
1859 if (ec.DoFlowAnalysis)
1860 ec.CurrentBranching.SetFieldAssigned (this, name);
1863 public void SetFieldAssigned (MyBitVector vector, string field_name)
1865 int field_idx = TypeInfo.GetFieldIndex (field_name);
1870 vector [Offset + field_idx] = true;
1873 public VariableInfo GetSubStruct (string name)
1875 TypeInfo type = TypeInfo.GetSubStruct (name);
1880 return new VariableInfo (this, type);
1883 public override string ToString ()
1885 return String.Format ("VariableInfo ({0}:{1}:{2}:{3}:{4})",
1886 Name, TypeInfo, Offset, Length, IsParameter);
1891 // This is used by the flow code to hold the `layout' of the flow vector for
1892 // all locals and all parameters (ie. we create one instance of this class for the
1893 // locals and another one for the params).
1895 public class VariableMap {
1897 // The number of variables in the map.
1899 public readonly int Count;
1902 // Total length of the flow vector for this map.
1904 public readonly int Length;
1908 public VariableMap (InternalParameters ip)
1910 Count = ip != null ? ip.Count : 0;
1912 // Dont bother allocating anything!
1918 for (int i = 0; i < Count; i++) {
1919 Parameter.Modifier mod = ip.ParameterModifier (i);
1921 if ((mod & Parameter.Modifier.OUT) == 0)
1924 // Dont allocate till we find an out var.
1926 map = new VariableInfo [Count];
1928 map [i] = new VariableInfo (ip.ParameterName (i),
1929 TypeManager.GetElementType (ip.ParameterType (i)), i, Length);
1931 Length += map [i].Length;
1935 public VariableMap (LocalInfo[] locals)
1936 : this (null, locals)
1939 public VariableMap (VariableMap parent, LocalInfo[] locals)
1941 int offset = 0, start = 0;
1942 if (parent != null && parent.map != null) {
1943 offset = parent.Length;
1944 start = parent.Count;
1947 Count = locals.Length + start;
1952 map = new VariableInfo [Count];
1955 if (parent != null && parent.map != null) {
1956 parent.map.CopyTo (map, 0);
1959 for (int i = start; i < Count; i++) {
1960 LocalInfo li = locals [i-start];
1962 if (li.VariableType == null)
1965 map [i] = li.VariableInfo = new VariableInfo (li, Length);
1966 Length += map [i].Length;
1971 // Returns the VariableInfo for variable @index or null if we don't need to
1972 // compute assignment info for this variable.
1974 public VariableInfo this [int index] {
1983 public override string ToString ()
1985 return String.Format ("VariableMap ({0}:{1})", Count, Length);
1990 // This is a special bit vector which can inherit from another bit vector doing a
1991 // copy-on-write strategy. The inherited vector may have a smaller size than the
1994 public class MyBitVector {
1995 public readonly int Count;
1996 public readonly MyBitVector InheritsFrom;
2001 public MyBitVector (int Count)
2002 : this (null, Count)
2005 public MyBitVector (MyBitVector InheritsFrom, int Count)
2007 this.InheritsFrom = InheritsFrom;
2012 // Checks whether this bit vector has been modified. After setting this to true,
2013 // we won't use the inherited vector anymore, but our own copy of it.
2015 public bool IsDirty {
2022 initialize_vector ();
2027 // Get/set bit `index' in the bit vector.
2029 public bool this [int index]
2033 throw new ArgumentOutOfRangeException ();
2035 // We're doing a "copy-on-write" strategy here; as long
2036 // as nobody writes to the array, we can use our parent's
2037 // copy instead of duplicating the vector.
2040 return vector [index];
2041 else if (InheritsFrom != null) {
2042 BitArray inherited = InheritsFrom.Vector;
2044 if (index < inherited.Count)
2045 return inherited [index];
2054 throw new ArgumentOutOfRangeException ();
2056 // Only copy the vector if we're actually modifying it.
2058 if (this [index] != value) {
2059 initialize_vector ();
2061 vector [index] = value;
2067 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
2068 // copy of the bit vector.
2070 public static explicit operator BitArray (MyBitVector vector)
2072 vector.initialize_vector ();
2073 return vector.Vector;
2077 // Performs an `or' operation on the bit vector. The `new_vector' may have a
2078 // different size than the current one.
2080 public void Or (MyBitVector new_vector)
2082 BitArray new_array = new_vector.Vector;
2084 initialize_vector ();
2087 if (vector.Count < new_array.Count)
2088 upper = vector.Count;
2090 upper = new_array.Count;
2092 for (int i = 0; i < upper; i++)
2093 vector [i] = vector [i] | new_array [i];
2097 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
2098 // a different size than the current one.
2100 public void And (MyBitVector new_vector)
2102 BitArray new_array = new_vector.Vector;
2104 initialize_vector ();
2107 if (vector.Count < new_array.Count)
2108 lower = upper = vector.Count;
2110 lower = new_array.Count;
2111 upper = vector.Count;
2114 for (int i = 0; i < lower; i++)
2115 vector [i] = vector [i] & new_array [i];
2117 for (int i = lower; i < upper; i++)
2121 public static void And (ref MyBitVector target, MyBitVector vector)
2124 target.And (vector);
2126 target = vector.Clone ();
2129 public static void Or (ref MyBitVector target, MyBitVector vector)
2134 target = vector.Clone ();
2138 // This does a deep copy of the bit vector.
2140 public MyBitVector Clone ()
2142 MyBitVector retval = new MyBitVector (Count);
2144 retval.Vector = Vector;
2153 else if (!is_dirty && (InheritsFrom != null))
2154 return InheritsFrom.Vector;
2156 initialize_vector ();
2162 initialize_vector ();
2164 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
2165 vector [i] = value [i];
2169 void initialize_vector ()
2174 vector = new BitArray (Count, false);
2175 if (InheritsFrom != null)
2176 Vector = InheritsFrom.Vector;
2181 public override string ToString ()
2183 StringBuilder sb = new StringBuilder ("{");
2185 BitArray vector = Vector;
2188 for (int i = 0; i < vector.Count; i++) {
2189 sb.Append (vector [i] ? "1" : "0");
2193 return sb.ToString ();