2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// Return value indicates whether all code paths emitted return.
36 public abstract bool Emit (EmitContext ec);
38 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
44 if (e.Type != TypeManager.bool_type){
45 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
51 31, loc, "Can not convert the expression to a boolean");
54 if (CodeGen.SymbolWriter != null)
61 /// Encapsulates the emission of a boolean test and jumping to a
64 /// This will emit the bool expression in `bool_expr' and if
65 /// `target_is_for_true' is true, then the code will generate a
66 /// brtrue to the target. Otherwise a brfalse.
68 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
69 Label target, bool target_is_for_true)
71 ILGenerator ig = ec.ig;
74 if (bool_expr is Unary){
75 Unary u = (Unary) bool_expr;
77 if (u.Oper == Unary.Operator.LogicalNot){
80 u.EmitLogicalNot (ec);
82 } else if (bool_expr is Binary){
83 Binary b = (Binary) bool_expr;
85 if (b.EmitBranchable (ec, target, target_is_for_true))
92 if (target_is_for_true){
94 ig.Emit (OpCodes.Brfalse, target);
96 ig.Emit (OpCodes.Brtrue, target);
99 ig.Emit (OpCodes.Brtrue, target);
101 ig.Emit (OpCodes.Brfalse, target);
105 public static void Warning_DeadCodeFound (Location loc)
107 Report.Warning (162, loc, "Unreachable code detected");
111 public class EmptyStatement : Statement {
112 public override bool Resolve (EmitContext ec)
117 public override bool Emit (EmitContext ec)
123 public class If : Statement {
125 public Statement TrueStatement;
126 public Statement FalseStatement;
128 public If (Expression expr, Statement trueStatement, Location l)
131 TrueStatement = trueStatement;
135 public If (Expression expr,
136 Statement trueStatement,
137 Statement falseStatement,
141 TrueStatement = trueStatement;
142 FalseStatement = falseStatement;
146 public override bool Resolve (EmitContext ec)
148 Report.Debug (1, "START IF BLOCK");
150 expr = ResolveBoolean (ec, expr, loc);
155 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
157 if (!TrueStatement.Resolve (ec)) {
158 ec.KillFlowBranching ();
162 ec.CurrentBranching.CreateSibling ();
164 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
165 ec.KillFlowBranching ();
169 ec.EndFlowBranching ();
171 Report.Debug (1, "END IF BLOCK");
176 public override bool Emit (EmitContext ec)
178 ILGenerator ig = ec.ig;
179 Label false_target = ig.DefineLabel ();
181 bool is_true_ret, is_false_ret;
184 // Dead code elimination
186 if (expr is BoolConstant){
187 bool take = ((BoolConstant) expr).Value;
190 if (FalseStatement != null){
191 Warning_DeadCodeFound (FalseStatement.loc);
193 return TrueStatement.Emit (ec);
195 Warning_DeadCodeFound (TrueStatement.loc);
196 if (FalseStatement != null)
197 return FalseStatement.Emit (ec);
201 EmitBoolExpression (ec, expr, false_target, false);
203 is_true_ret = TrueStatement.Emit (ec);
204 is_false_ret = is_true_ret;
206 if (FalseStatement != null){
207 bool branch_emitted = false;
209 end = ig.DefineLabel ();
211 ig.Emit (OpCodes.Br, end);
212 branch_emitted = true;
215 ig.MarkLabel (false_target);
216 is_false_ret = FalseStatement.Emit (ec);
221 ig.MarkLabel (false_target);
222 is_false_ret = false;
225 return is_true_ret && is_false_ret;
229 public class Do : Statement {
230 public Expression expr;
231 public readonly Statement EmbeddedStatement;
233 public Do (Statement statement, Expression boolExpr, Location l)
236 EmbeddedStatement = statement;
240 public override bool Resolve (EmitContext ec)
242 if (!EmbeddedStatement.Resolve (ec))
245 expr = ResolveBoolean (ec, expr, loc);
252 public override bool Emit (EmitContext ec)
254 ILGenerator ig = ec.ig;
255 Label loop = ig.DefineLabel ();
256 Label old_begin = ec.LoopBegin;
257 Label old_end = ec.LoopEnd;
258 bool old_inloop = ec.InLoop;
259 bool old_breaks = ec.Breaks;
260 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
262 ec.LoopBegin = ig.DefineLabel ();
263 ec.LoopEnd = ig.DefineLabel ();
265 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
269 EmbeddedStatement.Emit (ec);
270 bool breaks = ec.Breaks;
271 ig.MarkLabel (ec.LoopBegin);
274 // Dead code elimination
276 if (expr is BoolConstant){
277 bool res = ((BoolConstant) expr).Value;
280 ec.ig.Emit (OpCodes.Br, loop);
282 EmitBoolExpression (ec, expr, loop, true);
284 ig.MarkLabel (ec.LoopEnd);
286 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
287 ec.LoopBegin = old_begin;
288 ec.LoopEnd = old_end;
289 ec.InLoop = old_inloop;
290 ec.Breaks = old_breaks;
293 // Inform whether we are infinite or not
295 if (expr is BoolConstant){
296 BoolConstant bc = (BoolConstant) expr;
298 if (bc.Value == true)
299 return breaks == false;
306 public class While : Statement {
307 public Expression expr;
308 public readonly Statement Statement;
310 public While (Expression boolExpr, Statement statement, Location l)
312 this.expr = boolExpr;
313 Statement = statement;
317 public override bool Resolve (EmitContext ec)
319 expr = ResolveBoolean (ec, expr, loc);
323 return Statement.Resolve (ec);
326 public override bool Emit (EmitContext ec)
328 ILGenerator ig = ec.ig;
329 Label old_begin = ec.LoopBegin;
330 Label old_end = ec.LoopEnd;
331 bool old_inloop = ec.InLoop;
332 bool old_breaks = ec.Breaks;
333 Label while_loop = ig.DefineLabel ();
334 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
337 ec.LoopBegin = ig.DefineLabel ();
338 ec.LoopEnd = ig.DefineLabel ();
340 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
342 ig.Emit (OpCodes.Br, ec.LoopBegin);
343 ig.MarkLabel (while_loop);
346 // Inform whether we are infinite or not
348 if (expr is BoolConstant){
349 BoolConstant bc = (BoolConstant) expr;
351 ig.MarkLabel (ec.LoopBegin);
352 if (bc.Value == false){
353 Warning_DeadCodeFound (Statement.loc);
361 ig.Emit (OpCodes.Br, ec.LoopBegin);
364 // Inform that we are infinite (ie, `we return'), only
365 // if we do not `break' inside the code.
367 ret = breaks == false;
369 ig.MarkLabel (ec.LoopEnd);
373 ig.MarkLabel (ec.LoopBegin);
375 EmitBoolExpression (ec, expr, while_loop, true);
376 ig.MarkLabel (ec.LoopEnd);
381 ec.LoopBegin = old_begin;
382 ec.LoopEnd = old_end;
383 ec.InLoop = old_inloop;
384 ec.Breaks = old_breaks;
385 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
391 public class For : Statement {
393 readonly Statement InitStatement;
394 readonly Statement Increment;
395 readonly Statement Statement;
397 public For (Statement initStatement,
403 InitStatement = initStatement;
405 Increment = increment;
406 Statement = statement;
410 public override bool Resolve (EmitContext ec)
414 if (InitStatement != null){
415 if (!InitStatement.Resolve (ec))
420 Test = ResolveBoolean (ec, Test, loc);
425 if (Increment != null){
426 if (!Increment.Resolve (ec))
430 return Statement.Resolve (ec) && ok;
433 public override bool Emit (EmitContext ec)
435 ILGenerator ig = ec.ig;
436 Label old_begin = ec.LoopBegin;
437 Label old_end = ec.LoopEnd;
438 bool old_inloop = ec.InLoop;
439 bool old_breaks = ec.Breaks;
440 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
441 Label loop = ig.DefineLabel ();
442 Label test = ig.DefineLabel ();
444 if (InitStatement != null)
445 if (! (InitStatement is EmptyStatement))
446 InitStatement.Emit (ec);
448 ec.LoopBegin = ig.DefineLabel ();
449 ec.LoopEnd = ig.DefineLabel ();
451 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
453 ig.Emit (OpCodes.Br, test);
457 bool breaks = ec.Breaks;
459 ig.MarkLabel (ec.LoopBegin);
460 if (!(Increment is EmptyStatement))
465 // If test is null, there is no test, and we are just
469 EmitBoolExpression (ec, Test, loop, true);
471 ig.Emit (OpCodes.Br, loop);
472 ig.MarkLabel (ec.LoopEnd);
474 ec.LoopBegin = old_begin;
475 ec.LoopEnd = old_end;
476 ec.InLoop = old_inloop;
477 ec.Breaks = old_breaks;
478 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
481 // Inform whether we are infinite or not
484 if (Test is BoolConstant){
485 BoolConstant bc = (BoolConstant) Test;
488 return breaks == false;
496 public class StatementExpression : Statement {
499 public StatementExpression (ExpressionStatement expr, Location l)
505 public override bool Resolve (EmitContext ec)
507 expr = (Expression) expr.Resolve (ec);
511 public override bool Emit (EmitContext ec)
513 ILGenerator ig = ec.ig;
515 if (expr is ExpressionStatement)
516 ((ExpressionStatement) expr).EmitStatement (ec);
519 ig.Emit (OpCodes.Pop);
525 public override string ToString ()
527 return "StatementExpression (" + expr + ")";
532 /// Implements the return statement
534 public class Return : Statement {
535 public Expression Expr;
537 public Return (Expression expr, Location l)
543 public override bool Resolve (EmitContext ec)
546 Expr = Expr.Resolve (ec);
551 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
553 if (ec.CurrentBranching.InTryBlock ())
554 ec.CurrentBranching.AddFinallyVector (vector);
556 vector.Returns = FlowReturns.ALWAYS;
557 vector.Breaks = FlowReturns.ALWAYS;
562 public override bool Emit (EmitContext ec)
565 Report.Error (157,loc,"Control can not leave the body of the finally block");
569 if (ec.ReturnType == null){
571 Report.Error (127, loc, "Return with a value not allowed here");
576 Report.Error (126, loc, "An object of type `" +
577 TypeManager.CSharpName (ec.ReturnType) + "' is " +
578 "expected for the return statement");
582 if (Expr.Type != ec.ReturnType)
583 Expr = Expression.ConvertImplicitRequired (
584 ec, Expr, ec.ReturnType, loc);
591 if (ec.InTry || ec.InCatch)
592 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
595 if (ec.InTry || ec.InCatch) {
596 if (!ec.HasReturnLabel) {
597 ec.ReturnLabel = ec.ig.DefineLabel ();
598 ec.HasReturnLabel = true;
600 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
602 ec.ig.Emit (OpCodes.Ret);
608 public class Goto : Statement {
611 LabeledStatement label;
613 public override bool Resolve (EmitContext ec)
615 label = block.LookupLabel (target);
619 "No such label `" + target + "' in this scope");
623 // If this is a forward goto.
624 if (!label.IsDefined)
625 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
627 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
632 public Goto (Block parent_block, string label, Location l)
634 block = parent_block;
639 public string Target {
645 public override bool Emit (EmitContext ec)
647 Label l = label.LabelTarget (ec);
648 ec.ig.Emit (OpCodes.Br, l);
654 public class LabeledStatement : Statement {
661 public LabeledStatement (string label_name)
663 this.label_name = label_name;
666 public Label LabelTarget (EmitContext ec)
670 label = ec.ig.DefineLabel ();
676 public bool IsDefined {
682 public void AddUsageVector (FlowBranching.UsageVector vector)
685 vectors = new ArrayList ();
687 vectors.Add (vector.Clone ());
690 public override bool Resolve (EmitContext ec)
693 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
698 public override bool Emit (EmitContext ec)
701 ec.ig.MarkLabel (label);
709 /// `goto default' statement
711 public class GotoDefault : Statement {
713 public GotoDefault (Location l)
718 public override bool Resolve (EmitContext ec)
720 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
721 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
725 public override bool Emit (EmitContext ec)
727 if (ec.Switch == null){
728 Report.Error (153, loc, "goto default is only valid in a switch statement");
732 if (!ec.Switch.GotDefault){
733 Report.Error (159, loc, "No default target on switch statement");
736 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
742 /// `goto case' statement
744 public class GotoCase : Statement {
748 public GotoCase (Expression e, Location l)
754 public override bool Resolve (EmitContext ec)
756 if (ec.Switch == null){
757 Report.Error (153, loc, "goto case is only valid in a switch statement");
761 expr = expr.Resolve (ec);
765 if (!(expr is Constant)){
766 Report.Error (159, loc, "Target expression for goto case is not constant");
770 object val = Expression.ConvertIntLiteral (
771 (Constant) expr, ec.Switch.SwitchType, loc);
776 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
781 "No such label 'case " + val + "': for the goto case");
784 label = sl.ILLabelCode;
786 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
787 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
791 public override bool Emit (EmitContext ec)
793 ec.ig.Emit (OpCodes.Br, label);
798 public class Throw : Statement {
801 public Throw (Expression expr, Location l)
807 public override bool Resolve (EmitContext ec)
810 expr = expr.Resolve (ec);
814 ExprClass eclass = expr.eclass;
816 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
817 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
818 Expression.Error118 (loc, expr, "value, variable, property " +
819 "or indexer access ");
825 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)) {
826 Report.Error (155, loc,
827 "The type caught or thrown must be derived " +
828 "from System.Exception");
833 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
834 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
838 public override bool Emit (EmitContext ec)
842 ec.ig.Emit (OpCodes.Rethrow);
846 "A throw statement with no argument is only " +
847 "allowed in a catch clause");
854 ec.ig.Emit (OpCodes.Throw);
860 public class Break : Statement {
862 public Break (Location l)
867 public override bool Resolve (EmitContext ec)
869 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
873 public override bool Emit (EmitContext ec)
875 ILGenerator ig = ec.ig;
877 if (ec.InLoop == false && ec.Switch == null){
878 Report.Error (139, loc, "No enclosing loop or switch to continue to");
883 if (ec.InTry || ec.InCatch)
884 ig.Emit (OpCodes.Leave, ec.LoopEnd);
886 ig.Emit (OpCodes.Br, ec.LoopEnd);
892 public class Continue : Statement {
894 public Continue (Location l)
899 public override bool Resolve (EmitContext ec)
901 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
905 public override bool Emit (EmitContext ec)
907 Label begin = ec.LoopBegin;
910 Report.Error (139, loc, "No enclosing loop to continue to");
915 // UGH: Non trivial. This Br might cross a try/catch boundary
919 // try { ... } catch { continue; }
923 // try {} catch { while () { continue; }}
925 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
926 ec.ig.Emit (OpCodes.Leave, begin);
927 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
928 throw new Exception ("Should never happen");
930 ec.ig.Emit (OpCodes.Br, begin);
936 // This is used in the control flow analysis code to specify whether the
937 // current code block may return to its enclosing block before reaching
940 public enum FlowReturns {
941 // It can never return.
944 // This means that the block contains a conditional return statement
948 // The code always returns, ie. there's an unconditional return / break
952 // The code always throws an exception.
955 // The current code block is unreachable. This happens if it's immediately
956 // following a FlowReturns.ALWAYS block.
961 // This is a special bit vector which can inherit from another bit vector doing a
962 // copy-on-write strategy. The inherited vector may have a smaller size than the
965 public class MyBitVector {
966 public readonly int Count;
967 public readonly MyBitVector InheritsFrom;
972 public MyBitVector (int Count)
976 public MyBitVector (MyBitVector InheritsFrom, int Count)
978 this.InheritsFrom = InheritsFrom;
983 // Checks whether this bit vector has been modified. After setting this to true,
984 // we won't use the inherited vector anymore, but our own copy of it.
986 public bool IsDirty {
993 initialize_vector ();
998 // Get/set bit `index' in the bit vector.
1000 public bool this [int index]
1004 throw new ArgumentOutOfRangeException ();
1006 // We're doing a "copy-on-write" strategy here; as long
1007 // as nobody writes to the array, we can use our parent's
1008 // copy instead of duplicating the vector.
1011 return vector [index];
1012 else if (InheritsFrom != null) {
1013 BitArray inherited = InheritsFrom.Vector;
1015 if (index < inherited.Count)
1016 return inherited [index];
1025 throw new ArgumentOutOfRangeException ();
1027 // Only copy the vector if we're actually modifying it.
1029 if (this [index] != value) {
1030 initialize_vector ();
1032 vector [index] = value;
1038 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1039 // copy of the bit vector.
1041 public static explicit operator BitArray (MyBitVector vector)
1043 vector.initialize_vector ();
1044 return vector.Vector;
1048 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1049 // different size than the current one.
1051 public void Or (MyBitVector new_vector)
1053 BitArray new_array = new_vector.Vector;
1055 initialize_vector ();
1058 if (vector.Count < new_array.Count)
1059 upper = vector.Count;
1061 upper = new_array.Count;
1063 for (int i = 0; i < upper; i++)
1064 vector [i] = vector [i] | new_array [i];
1068 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1069 // a different size than the current one.
1071 public void And (MyBitVector new_vector)
1073 BitArray new_array = new_vector.Vector;
1075 initialize_vector ();
1078 if (vector.Count < new_array.Count)
1079 lower = upper = vector.Count;
1081 lower = new_array.Count;
1082 upper = vector.Count;
1085 for (int i = 0; i < lower; i++)
1086 vector [i] = vector [i] & new_array [i];
1088 for (int i = lower; i < upper; i++)
1093 // This does a deep copy of the bit vector.
1095 public MyBitVector Clone ()
1097 MyBitVector retval = new MyBitVector (Count);
1099 retval.Vector = Vector;
1108 else if (!is_dirty && (InheritsFrom != null))
1109 return InheritsFrom.Vector;
1111 initialize_vector ();
1117 initialize_vector ();
1119 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1120 vector [i] = value [i];
1124 void initialize_vector ()
1129 vector = new BitArray (Count, false);
1130 if (InheritsFrom != null)
1131 Vector = InheritsFrom.Vector;
1136 public override string ToString ()
1138 StringBuilder sb = new StringBuilder ("MyBitVector (");
1140 BitArray vector = Vector;
1144 sb.Append ("INHERITED - ");
1145 for (int i = 0; i < vector.Count; i++) {
1148 sb.Append (vector [i]);
1152 return sb.ToString ();
1157 // The type of a FlowBranching.
1159 public enum FlowBranchingType {
1160 // Normal (conditional or toplevel) block.
1174 // A new instance of this class is created every time a new block is resolved
1175 // and if there's branching in the block's control flow.
1177 public class FlowBranching {
1179 // The type of this flow branching.
1181 public readonly FlowBranchingType Type;
1184 // The block this branching is contained in. This may be null if it's not
1185 // a top-level block and it doesn't declare any local variables.
1187 public readonly Block Block;
1190 // The parent of this branching or null if this is the top-block.
1192 public readonly FlowBranching Parent;
1195 // Start-Location of this flow branching.
1197 public readonly Location Location;
1200 // A list of UsageVectors. A new vector is added each time control flow may
1201 // take a different path.
1203 public ArrayList Siblings;
1208 InternalParameters param_info;
1211 ArrayList finally_vectors;
1213 static int next_id = 0;
1217 // Performs an `And' operation on the FlowReturns status
1218 // (for instance, a block only returns ALWAYS if all its siblings
1221 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1223 if (b == FlowReturns.UNREACHABLE)
1227 case FlowReturns.NEVER:
1228 if (b == FlowReturns.NEVER)
1229 return FlowReturns.NEVER;
1231 return FlowReturns.SOMETIMES;
1233 case FlowReturns.SOMETIMES:
1234 return FlowReturns.SOMETIMES;
1236 case FlowReturns.ALWAYS:
1237 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1238 return FlowReturns.ALWAYS;
1240 return FlowReturns.SOMETIMES;
1242 case FlowReturns.EXCEPTION:
1243 if (b == FlowReturns.EXCEPTION)
1244 return FlowReturns.EXCEPTION;
1245 else if (b == FlowReturns.ALWAYS)
1246 return FlowReturns.ALWAYS;
1248 return FlowReturns.SOMETIMES;
1255 // The vector contains a BitArray with information about which local variables
1256 // and parameters are already initialized at the current code position.
1258 public class UsageVector {
1260 // If this is true, then the usage vector has been modified and must be
1261 // merged when we're done with this branching.
1263 public bool IsDirty;
1266 // The number of parameters in this block.
1268 public readonly int CountParameters;
1271 // The number of locals in this block.
1273 public readonly int CountLocals;
1276 // If not null, then we inherit our state from this vector and do a
1277 // copy-on-write. If null, then we're the first sibling in a top-level
1278 // block and inherit from the empty vector.
1280 public readonly UsageVector InheritsFrom;
1285 MyBitVector locals, parameters;
1286 FlowReturns real_returns, real_breaks;
1287 bool returns_set, breaks_set, is_finally;
1289 static int next_id = 0;
1293 // Normally, you should not use any of these constructors.
1295 public UsageVector (UsageVector parent, int num_params, int num_locals)
1297 this.InheritsFrom = parent;
1298 this.CountParameters = num_params;
1299 this.CountLocals = num_locals;
1300 this.real_returns = FlowReturns.NEVER;
1301 this.real_breaks = FlowReturns.NEVER;
1303 if (parent != null) {
1304 locals = new MyBitVector (parent.locals, CountLocals);
1306 parameters = new MyBitVector (parent.parameters, num_params);
1308 locals = new MyBitVector (null, CountLocals);
1310 parameters = new MyBitVector (null, num_params);
1316 public UsageVector (UsageVector parent)
1317 : this (parent, parent.CountParameters, parent.CountLocals)
1321 // This does a deep copy of the usage vector.
1323 public UsageVector Clone ()
1325 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1327 retval.locals = locals.Clone ();
1328 if (parameters != null)
1329 retval.parameters = parameters.Clone ();
1330 retval.real_returns = real_returns;
1331 retval.real_breaks = real_breaks;
1337 // State of parameter `number'.
1339 public bool this [int number]
1344 else if (number == 0)
1345 throw new ArgumentException ();
1347 return parameters [number - 1];
1353 else if (number == 0)
1354 throw new ArgumentException ();
1356 parameters [number - 1] = value;
1361 // State of the local variable `vi'.
1363 public bool this [VariableInfo vi]
1366 if (vi.Number == -1)
1368 else if (vi.Number == 0)
1369 throw new ArgumentException ();
1371 return locals [vi.Number - 1];
1375 if (vi.Number == -1)
1377 else if (vi.Number == 0)
1378 throw new ArgumentException ();
1380 locals [vi.Number - 1] = value;
1385 // Specifies when the current block returns.
1387 public FlowReturns Returns {
1389 return real_returns;
1393 real_returns = value;
1399 // Specifies whether control may return to our containing block
1400 // before reaching the end of this block. This happens if there
1401 // is a break/continue/goto/return in it.
1403 public FlowReturns Breaks {
1409 real_breaks = value;
1415 // Merge a child branching.
1417 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1419 MyBitVector new_locals = null;
1420 MyBitVector new_params = null;
1422 FlowReturns new_returns = FlowReturns.NEVER;
1423 FlowReturns new_breaks = FlowReturns.NEVER;
1424 bool new_returns_set = false, new_breaks_set = false;
1427 Report.Debug (1, "MERGING CHILDREN", branching, this);
1429 foreach (UsageVector child in children) {
1430 Report.Debug (1, " MERGING CHILD", child);
1432 // If Returns is already set, perform an `And' operation on it,
1433 // otherwise just set just.
1434 if (!new_returns_set) {
1435 new_returns = child.Returns;
1436 new_returns_set = true;
1438 new_returns = AndFlowReturns (new_returns, child.Returns);
1440 // If Breaks is already set, perform an `And' operation on it,
1441 // otherwise just set just.
1442 if (!new_breaks_set) {
1443 new_breaks = child.Breaks;
1444 new_breaks_set = true;
1446 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1448 // Ignore unreachable children.
1449 if (child.Returns == FlowReturns.UNREACHABLE)
1452 // If we're a switch section, `break' won't leave the current
1453 // branching (NOTE: the type check here means that we're "a"
1454 // switch section, not that we're "in" a switch section!).
1455 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1456 child.Returns : child.Breaks;
1458 // A local variable is initialized after a flow branching if it
1459 // has been initialized in all its branches which do neither
1460 // always return or always throw an exception.
1462 // If a branch may return, but does not always return, then we
1463 // can treat it like a never-returning branch here: control will
1464 // only reach the code position after the branching if we did not
1467 // It's important to distinguish between always and sometimes
1468 // returning branches here:
1471 // 2 if (something) {
1475 // 6 Console.WriteLine (a);
1477 // The if block in lines 3-4 always returns, so we must not look
1478 // at the initialization of `a' in line 4 - thus it'll still be
1479 // uninitialized in line 6.
1481 // On the other hand, the following is allowed:
1488 // 6 Console.WriteLine (a);
1490 // Here, `a' is initialized in line 3 and we must not look at
1491 // line 5 since it always returns.
1493 if ((breaks != FlowReturns.EXCEPTION) &&
1494 (breaks != FlowReturns.ALWAYS)) {
1495 if (new_locals != null)
1496 new_locals.And (child.locals);
1498 new_locals = locals.Clone ();
1499 new_locals.Or (child.locals);
1503 // An `out' parameter must be assigned in all branches which do
1504 // not always throw an exception.
1505 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1506 if (parameters != null) {
1507 if (new_params != null)
1508 new_params.And (child.parameters);
1510 new_params = parameters.Clone ();
1511 new_params.Or (child.parameters);
1516 // If we always return, check whether all `out' parameters have
1518 if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1519 branching.CheckOutParameters (
1520 child.parameters, branching.Location);
1524 // Set new `Returns' status.
1526 Returns = new_returns;
1529 Returns = AndFlowReturns (Returns, new_returns);
1532 // We've now either reached the point after the branching or we will
1533 // never get there since we always return or always throw an exception.
1535 // If we can reach the point after the branching, mark all locals and
1536 // parameters as initialized which have been initialized in all branches
1537 // we need to look at (see above).
1540 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1543 if ((new_locals != null) &&
1544 ((breaks == FlowReturns.NEVER) || (breaks == FlowReturns.SOMETIMES))) {
1545 locals.Or (new_locals);
1548 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1549 parameters.Or (new_params);
1552 // If we may have returned (this only happens if there was a reachable
1553 // `return' statement in one of the branches), then we may return to our
1554 // parent block before reaching the end of the block, so set `Breaks'.
1557 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1558 real_breaks = Returns;
1562 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1563 new_returns, new_breaks, this);
1569 // Tells control flow analysis that the current code position may be reached with
1570 // a forward jump from any of the origins listed in `origin_vectors' which is a
1571 // list of UsageVectors.
1573 // This is used when resolving forward gotos - in the following example, the
1574 // variable `a' is uninitialized in line 8 becase this line may be reached via
1575 // the goto in line 4:
1585 // 8 Console.WriteLine (a);
1588 public void MergeJumpOrigins (ICollection origin_vectors)
1590 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1592 real_breaks = FlowReturns.NEVER;
1595 foreach (UsageVector vector in origin_vectors) {
1596 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1598 locals.And (vector.locals);
1599 if (parameters != null)
1600 parameters.And (vector.parameters);
1601 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1604 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1608 // This is used at the beginning of a finally block if there were
1609 // any return statements in the try block or one of the catch blocks.
1611 public void MergeFinallyOrigins (ICollection finally_vectors)
1613 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1615 real_breaks = FlowReturns.NEVER;
1618 foreach (UsageVector vector in finally_vectors) {
1619 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1621 if (parameters != null)
1622 parameters.And (vector.parameters);
1623 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1628 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1632 // Performs an `or' operation on the locals and the parameters.
1634 public void Or (UsageVector new_vector)
1636 locals.Or (new_vector.locals);
1637 if (parameters != null)
1638 parameters.Or (new_vector.parameters);
1642 // Performs an `and' operation on the locals.
1644 public void AndLocals (UsageVector new_vector)
1646 locals.And (new_vector.locals);
1650 // Returns a deep copy of the parameters.
1652 public MyBitVector Parameters {
1654 if (parameters != null)
1655 return parameters.Clone ();
1662 // Returns a deep copy of the locals.
1664 public MyBitVector Locals {
1666 return locals.Clone ();
1674 public override string ToString ()
1676 StringBuilder sb = new StringBuilder ();
1678 sb.Append ("Vector (");
1681 sb.Append (Returns);
1684 if (parameters != null) {
1686 sb.Append (parameters);
1692 return sb.ToString ();
1696 FlowBranching (FlowBranchingType type, Location loc)
1698 this.Siblings = new ArrayList ();
1700 this.Location = loc;
1706 // Creates a new flow branching for `block'.
1707 // This is used from Block.Resolve to create the top-level branching of
1710 public FlowBranching (Block block, InternalParameters ip, Location loc)
1711 : this (FlowBranchingType.BLOCK, loc)
1717 param_map = new int [(param_info != null) ? param_info.Count : 0];
1720 for (int i = 0; i < param_map.Length; i++) {
1721 Parameter.Modifier mod = param_info.ParameterModifier (i);
1723 if ((mod & Parameter.Modifier.OUT) == 0)
1726 param_map [i] = ++num_params;
1729 Siblings = new ArrayList ();
1730 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1734 // Creates a new flow branching which is contained in `parent'.
1735 // You should only pass non-null for the `block' argument if this block
1736 // introduces any new variables - in this case, we need to create a new
1737 // usage vector with a different size than our parent's one.
1739 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1740 Block block, Location loc)
1746 if (parent != null) {
1747 param_info = parent.param_info;
1748 param_map = parent.param_map;
1749 num_params = parent.num_params;
1754 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1755 Block.CountVariables);
1757 vector = new UsageVector (Parent.CurrentUsageVector);
1759 Siblings.Add (vector);
1762 case FlowBranchingType.EXCEPTION:
1763 finally_vectors = new ArrayList ();
1772 // Returns the branching's current usage vector.
1774 public UsageVector CurrentUsageVector
1777 return (UsageVector) Siblings [Siblings.Count - 1];
1782 // Creates a sibling of the current usage vector.
1784 public void CreateSibling ()
1786 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1788 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1792 // Creates a sibling for a `finally' block.
1794 public void CreateSiblingForFinally ()
1796 if (Type != FlowBranchingType.EXCEPTION)
1797 throw new NotSupportedException ();
1801 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1805 // Check whether all `out' parameters have been assigned.
1807 public void CheckOutParameters (MyBitVector parameters, Location loc)
1812 for (int i = 0; i < param_map.Length; i++) {
1813 if (param_map [i] == 0)
1816 if (!parameters [param_map [i] - 1]) {
1818 177, loc, "The out parameter `" +
1819 param_info.ParameterName (i) + "` must be " +
1820 "assigned before control leave the current method.");
1827 // Merge a child branching.
1829 public FlowReturns MergeChild (FlowBranching child)
1831 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1835 // Does the toplevel merging.
1837 public FlowReturns MergeTopBlock ()
1839 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1840 throw new NotSupportedException ();
1842 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1844 vector.MergeChildren (this, Siblings);
1847 Siblings.Add (vector);
1849 Report.Debug (1, "MERGING TOP BLOCK", vector);
1851 if (vector.Returns != FlowReturns.EXCEPTION)
1852 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1854 return vector.Returns;
1857 public bool InTryBlock ()
1859 if (finally_vectors != null)
1861 else if (Parent != null)
1862 return Parent.InTryBlock ();
1867 public void AddFinallyVector (UsageVector vector)
1869 if (finally_vectors != null) {
1870 finally_vectors.Add (vector.Clone ());
1875 Parent.AddFinallyVector (vector);
1877 throw new NotSupportedException ();
1880 public bool IsVariableAssigned (VariableInfo vi)
1882 Report.Debug (2, "CHECK VARIABLE ACCESS", this, vi);
1884 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1887 return CurrentUsageVector [vi];
1890 public void SetVariableAssigned (VariableInfo vi)
1892 Report.Debug (2, "SET VARIABLE ACCESS", this, vi, CurrentUsageVector);
1894 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1897 CurrentUsageVector [vi] = true;
1900 public bool IsParameterAssigned (int number)
1902 Report.Debug (2, "IS PARAMETER ASSIGNED", this, number);
1904 if (param_map [number] == 0)
1907 return CurrentUsageVector [param_map [number]];
1910 public void SetParameterAssigned (int number)
1912 Report.Debug (2, "SET PARAMETER ACCESS", this, number, param_map [number],
1913 CurrentUsageVector);
1915 if (param_map [number] == 0)
1918 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
1919 CurrentUsageVector [param_map [number]] = true;
1922 public override string ToString ()
1924 StringBuilder sb = new StringBuilder ("FlowBranching (");
1929 if (Block != null) {
1931 sb.Append (Block.ID);
1933 sb.Append (Block.StartLocation);
1936 sb.Append (Siblings.Count);
1938 sb.Append (CurrentUsageVector);
1940 return sb.ToString ();
1944 public class VariableInfo {
1945 public Expression Type;
1946 public LocalBuilder LocalBuilder;
1947 public Type VariableType;
1948 public readonly Location Location;
1953 public bool Assigned;
1954 public bool ReadOnly;
1956 public VariableInfo (Expression type, Location l)
1959 LocalBuilder = null;
1963 public void MakePinned ()
1965 TypeManager.MakePinned (LocalBuilder);
1968 public override string ToString ()
1970 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
1975 /// Block represents a C# block.
1979 /// This class is used in a number of places: either to represent
1980 /// explicit blocks that the programmer places or implicit blocks.
1982 /// Implicit blocks are used as labels or to introduce variable
1985 public class Block : Statement {
1986 public readonly Block Parent;
1987 public readonly bool Implicit;
1988 public readonly Location StartLocation;
1989 public Location EndLocation;
1992 // The statements in this block
1994 ArrayList statements;
1997 // An array of Blocks. We keep track of children just
1998 // to generate the local variable declarations.
2000 // Statements and child statements are handled through the
2006 // Labels. (label, block) pairs.
2011 // Keeps track of (name, type) pairs
2013 Hashtable variables;
2016 // Keeps track of constants
2017 Hashtable constants;
2020 // Maps variable names to ILGenerator.LocalBuilders
2022 Hashtable local_builders;
2030 public Block (Block parent)
2031 : this (parent, false, Location.Null, Location.Null)
2034 public Block (Block parent, bool implicit_block)
2035 : this (parent, implicit_block, Location.Null, Location.Null)
2038 public Block (Block parent, Location start, Location end)
2039 : this (parent, false, start, end)
2042 public Block (Block parent, bool implicit_block, Location start, Location end)
2045 parent.AddChild (this);
2047 this.Parent = parent;
2048 this.Implicit = implicit_block;
2049 this.StartLocation = start;
2050 this.EndLocation = end;
2053 statements = new ArrayList ();
2062 void AddChild (Block b)
2064 if (children == null)
2065 children = new ArrayList ();
2070 public void SetEndLocation (Location loc)
2076 /// Adds a label to the current block.
2080 /// false if the name already exists in this block. true
2084 public bool AddLabel (string name, LabeledStatement target)
2087 labels = new Hashtable ();
2088 if (labels.Contains (name))
2091 labels.Add (name, target);
2095 public LabeledStatement LookupLabel (string name)
2097 if (labels != null){
2098 if (labels.Contains (name))
2099 return ((LabeledStatement) labels [name]);
2103 return Parent.LookupLabel (name);
2108 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2110 if (variables == null)
2111 variables = new Hashtable ();
2113 if (GetVariableType (name) != null)
2118 Parameter p = pars.GetParameterByName (name, out idx);
2123 VariableInfo vi = new VariableInfo (type, l);
2125 variables.Add (name, vi);
2127 if (variables_initialized)
2128 throw new Exception ();
2130 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2134 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2136 if (AddVariable (type, name, pars, l) == null)
2139 if (constants == null)
2140 constants = new Hashtable ();
2142 constants.Add (name, value);
2146 public Hashtable Variables {
2152 public VariableInfo GetVariableInfo (string name)
2154 if (variables != null) {
2156 temp = variables [name];
2159 return (VariableInfo) temp;
2164 return Parent.GetVariableInfo (name);
2169 public Expression GetVariableType (string name)
2171 VariableInfo vi = GetVariableInfo (name);
2179 public Expression GetConstantExpression (string name)
2181 if (constants != null) {
2183 temp = constants [name];
2186 return (Expression) temp;
2190 return Parent.GetConstantExpression (name);
2196 /// True if the variable named @name has been defined
2199 public bool IsVariableDefined (string name)
2201 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2202 if (variables != null) {
2203 if (variables.Contains (name))
2208 return Parent.IsVariableDefined (name);
2214 /// True if the variable named @name is a constant
2216 public bool IsConstant (string name)
2218 Expression e = null;
2220 e = GetConstantExpression (name);
2226 /// Use to fetch the statement associated with this label
2228 public Statement this [string name] {
2230 return (Statement) labels [name];
2235 /// A list of labels that were not used within this block
2237 public string [] GetUnreferenced ()
2239 // FIXME: Implement me
2243 public void AddStatement (Statement s)
2260 bool variables_initialized = false;
2261 int count_variables = 0, first_variable = 0;
2263 void UpdateVariableInfo (EmitContext ec)
2265 DeclSpace ds = ec.DeclSpace;
2270 first_variable += Parent.CountVariables;
2272 count_variables = first_variable;
2273 if (variables != null) {
2274 foreach (VariableInfo vi in variables.Values) {
2275 Report.Debug (2, "VARIABLE", vi);
2277 Type type = ds.ResolveType (vi.Type, false, vi.Location);
2283 vi.VariableType = type;
2285 Report.Debug (2, "VARIABLE", vi, type, type.IsValueType,
2286 TypeManager.IsValueType (type),
2287 TypeManager.IsBuiltinType (type));
2289 // FIXME: we don't have support for structs yet.
2290 if (TypeManager.IsValueType (type) && !TypeManager.IsBuiltinType (type))
2293 vi.Number = ++count_variables;
2297 variables_initialized = true;
2302 // The number of local variables in this block
2304 public int CountVariables
2307 if (!variables_initialized)
2308 throw new Exception ();
2310 return count_variables;
2315 /// Emits the variable declarations and labels.
2318 /// tc: is our typecontainer (to resolve type references)
2319 /// ig: is the code generator:
2320 /// toplevel: the toplevel block. This is used for checking
2321 /// that no two labels with the same name are used.
2323 public void EmitMeta (EmitContext ec, Block toplevel)
2325 DeclSpace ds = ec.DeclSpace;
2326 ILGenerator ig = ec.ig;
2328 if (!variables_initialized)
2329 UpdateVariableInfo (ec);
2332 // Process this block variables
2334 if (variables != null){
2335 local_builders = new Hashtable ();
2337 foreach (DictionaryEntry de in variables){
2338 string name = (string) de.Key;
2339 VariableInfo vi = (VariableInfo) de.Value;
2341 if (vi.VariableType == null)
2344 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2346 if (CodeGen.SymbolWriter != null)
2347 vi.LocalBuilder.SetLocalSymInfo (name);
2349 if (constants == null)
2352 Expression cv = (Expression) constants [name];
2356 Expression e = cv.Resolve (ec);
2360 if (!(e is Constant)){
2361 Report.Error (133, vi.Location,
2362 "The expression being assigned to `" +
2363 name + "' must be constant (" + e + ")");
2367 constants.Remove (name);
2368 constants.Add (name, e);
2373 // Now, handle the children
2375 if (children != null){
2376 foreach (Block b in children)
2377 b.EmitMeta (ec, toplevel);
2381 public void UsageWarning ()
2385 if (variables != null){
2386 foreach (DictionaryEntry de in variables){
2387 VariableInfo vi = (VariableInfo) de.Value;
2392 name = (string) de.Key;
2396 219, vi.Location, "The variable `" + name +
2397 "' is assigned but its value is never used");
2400 168, vi.Location, "The variable `" +
2402 "' is declared but never used");
2407 if (children != null)
2408 foreach (Block b in children)
2412 public override bool Resolve (EmitContext ec)
2414 Block prev_block = ec.CurrentBlock;
2417 ec.CurrentBlock = this;
2418 ec.StartFlowBranching (this);
2420 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2422 if (!variables_initialized)
2423 UpdateVariableInfo (ec);
2425 foreach (Statement s in statements){
2426 if (s.Resolve (ec) == false)
2430 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2432 ec.EndFlowBranching ();
2433 ec.CurrentBlock = prev_block;
2437 public override bool Emit (EmitContext ec)
2439 bool is_ret = false, this_ret = false;
2440 Block prev_block = ec.CurrentBlock;
2441 bool warning_shown = false;
2443 ec.CurrentBlock = this;
2445 if (CodeGen.SymbolWriter != null) {
2446 ec.Mark (StartLocation);
2448 foreach (Statement s in statements) {
2451 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2452 warning_shown = true;
2453 Warning_DeadCodeFound (s.loc);
2455 this_ret = s.Emit (ec);
2460 ec.Mark (EndLocation);
2462 foreach (Statement s in statements){
2463 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2464 warning_shown = true;
2465 Warning_DeadCodeFound (s.loc);
2467 this_ret = s.Emit (ec);
2473 ec.CurrentBlock = prev_block;
2478 public class SwitchLabel {
2481 public Location loc;
2482 public Label ILLabel;
2483 public Label ILLabelCode;
2486 // if expr == null, then it is the default case.
2488 public SwitchLabel (Expression expr, Location l)
2494 public Expression Label {
2500 public object Converted {
2507 // Resolves the expression, reduces it to a literal if possible
2508 // and then converts it to the requested type.
2510 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2512 ILLabel = ec.ig.DefineLabel ();
2513 ILLabelCode = ec.ig.DefineLabel ();
2518 Expression e = label.Resolve (ec);
2523 if (!(e is Constant)){
2524 Console.WriteLine ("Value is: " + label);
2525 Report.Error (150, loc, "A constant value is expected");
2529 if (e is StringConstant || e is NullLiteral){
2530 if (required_type == TypeManager.string_type){
2532 ILLabel = ec.ig.DefineLabel ();
2537 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2538 if (converted == null)
2545 public class SwitchSection {
2546 // An array of SwitchLabels.
2547 public readonly ArrayList Labels;
2548 public readonly Block Block;
2550 public SwitchSection (ArrayList labels, Block block)
2557 public class Switch : Statement {
2558 public readonly ArrayList Sections;
2559 public Expression Expr;
2562 /// Maps constants whose type type SwitchType to their SwitchLabels.
2564 public Hashtable Elements;
2567 /// The governing switch type
2569 public Type SwitchType;
2575 Label default_target;
2576 Expression new_expr;
2579 // The types allowed to be implicitly cast from
2580 // on the governing type
2582 static Type [] allowed_types;
2584 public Switch (Expression e, ArrayList sects, Location l)
2591 public bool GotDefault {
2597 public Label DefaultTarget {
2599 return default_target;
2604 // Determines the governing type for a switch. The returned
2605 // expression might be the expression from the switch, or an
2606 // expression that includes any potential conversions to the
2607 // integral types or to string.
2609 Expression SwitchGoverningType (EmitContext ec, Type t)
2611 if (t == TypeManager.int32_type ||
2612 t == TypeManager.uint32_type ||
2613 t == TypeManager.char_type ||
2614 t == TypeManager.byte_type ||
2615 t == TypeManager.sbyte_type ||
2616 t == TypeManager.ushort_type ||
2617 t == TypeManager.short_type ||
2618 t == TypeManager.uint64_type ||
2619 t == TypeManager.int64_type ||
2620 t == TypeManager.string_type ||
2621 t == TypeManager.bool_type ||
2622 t.IsSubclassOf (TypeManager.enum_type))
2625 if (allowed_types == null){
2626 allowed_types = new Type [] {
2627 TypeManager.sbyte_type,
2628 TypeManager.byte_type,
2629 TypeManager.short_type,
2630 TypeManager.ushort_type,
2631 TypeManager.int32_type,
2632 TypeManager.uint32_type,
2633 TypeManager.int64_type,
2634 TypeManager.uint64_type,
2635 TypeManager.char_type,
2636 TypeManager.bool_type,
2637 TypeManager.string_type
2642 // Try to find a *user* defined implicit conversion.
2644 // If there is no implicit conversion, or if there are multiple
2645 // conversions, we have to report an error
2647 Expression converted = null;
2648 foreach (Type tt in allowed_types){
2651 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
2655 if (converted != null){
2656 Report.Error (-12, loc, "More than one conversion to an integral " +
2657 " type exists for type `" +
2658 TypeManager.CSharpName (Expr.Type)+"'");
2666 void error152 (string n)
2669 152, "The label `" + n + ":' " +
2670 "is already present on this switch statement");
2674 // Performs the basic sanity checks on the switch statement
2675 // (looks for duplicate keys and non-constant expressions).
2677 // It also returns a hashtable with the keys that we will later
2678 // use to compute the switch tables
2680 bool CheckSwitch (EmitContext ec)
2684 Elements = new Hashtable ();
2686 got_default = false;
2688 if (TypeManager.IsEnumType (SwitchType)){
2689 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2691 compare_type = SwitchType;
2693 foreach (SwitchSection ss in Sections){
2694 foreach (SwitchLabel sl in ss.Labels){
2695 if (!sl.ResolveAndReduce (ec, SwitchType)){
2700 if (sl.Label == null){
2702 error152 ("default");
2709 object key = sl.Converted;
2711 if (key is Constant)
2712 key = ((Constant) key).GetValue ();
2715 key = NullLiteral.Null;
2717 string lname = null;
2718 if (compare_type == TypeManager.uint64_type){
2719 ulong v = (ulong) key;
2721 if (Elements.Contains (v))
2722 lname = v.ToString ();
2724 Elements.Add (v, sl);
2725 } else if (compare_type == TypeManager.int64_type){
2726 long v = (long) key;
2728 if (Elements.Contains (v))
2729 lname = v.ToString ();
2731 Elements.Add (v, sl);
2732 } else if (compare_type == TypeManager.uint32_type){
2733 uint v = (uint) key;
2735 if (Elements.Contains (v))
2736 lname = v.ToString ();
2738 Elements.Add (v, sl);
2739 } else if (compare_type == TypeManager.char_type){
2740 char v = (char) key;
2742 if (Elements.Contains (v))
2743 lname = v.ToString ();
2745 Elements.Add (v, sl);
2746 } else if (compare_type == TypeManager.byte_type){
2747 byte v = (byte) key;
2749 if (Elements.Contains (v))
2750 lname = v.ToString ();
2752 Elements.Add (v, sl);
2753 } else if (compare_type == TypeManager.sbyte_type){
2754 sbyte v = (sbyte) key;
2756 if (Elements.Contains (v))
2757 lname = v.ToString ();
2759 Elements.Add (v, sl);
2760 } else if (compare_type == TypeManager.short_type){
2761 short v = (short) key;
2763 if (Elements.Contains (v))
2764 lname = v.ToString ();
2766 Elements.Add (v, sl);
2767 } else if (compare_type == TypeManager.ushort_type){
2768 ushort v = (ushort) key;
2770 if (Elements.Contains (v))
2771 lname = v.ToString ();
2773 Elements.Add (v, sl);
2774 } else if (compare_type == TypeManager.string_type){
2775 if (key is NullLiteral){
2776 if (Elements.Contains (NullLiteral.Null))
2779 Elements.Add (NullLiteral.Null, null);
2781 string s = (string) key;
2783 if (Elements.Contains (s))
2786 Elements.Add (s, sl);
2788 } else if (compare_type == TypeManager.int32_type) {
2791 if (Elements.Contains (v))
2792 lname = v.ToString ();
2794 Elements.Add (v, sl);
2795 } else if (compare_type == TypeManager.bool_type) {
2796 bool v = (bool) key;
2798 if (Elements.Contains (v))
2799 lname = v.ToString ();
2801 Elements.Add (v, sl);
2805 throw new Exception ("Unknown switch type!" +
2806 SwitchType + " " + compare_type);
2810 error152 ("case + " + lname);
2821 void EmitObjectInteger (ILGenerator ig, object k)
2824 IntConstant.EmitInt (ig, (int) k);
2825 else if (k is Constant) {
2826 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2829 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2832 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2834 IntConstant.EmitInt (ig, (int) (long) k);
2835 ig.Emit (OpCodes.Conv_I8);
2838 LongConstant.EmitLong (ig, (long) k);
2840 else if (k is ulong)
2842 if ((ulong) k < (1L<<32))
2844 IntConstant.EmitInt (ig, (int) (long) k);
2845 ig.Emit (OpCodes.Conv_U8);
2849 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2853 IntConstant.EmitInt (ig, (int) ((char) k));
2854 else if (k is sbyte)
2855 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2857 IntConstant.EmitInt (ig, (int) ((byte) k));
2858 else if (k is short)
2859 IntConstant.EmitInt (ig, (int) ((short) k));
2860 else if (k is ushort)
2861 IntConstant.EmitInt (ig, (int) ((ushort) k));
2863 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2865 throw new Exception ("Unhandled case");
2868 // structure used to hold blocks of keys while calculating table switch
2869 class KeyBlock : IComparable
2871 public KeyBlock (long _nFirst)
2873 nFirst = nLast = _nFirst;
2877 public ArrayList rgKeys = null;
2880 get { return (int) (nLast - nFirst + 1); }
2882 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2884 return kbLast.nLast - kbFirst.nFirst + 1;
2886 public int CompareTo (object obj)
2888 KeyBlock kb = (KeyBlock) obj;
2889 int nLength = Length;
2890 int nLengthOther = kb.Length;
2891 if (nLengthOther == nLength)
2892 return (int) (kb.nFirst - nFirst);
2893 return nLength - nLengthOther;
2898 /// This method emits code for a lookup-based switch statement (non-string)
2899 /// Basically it groups the cases into blocks that are at least half full,
2900 /// and then spits out individual lookup opcodes for each block.
2901 /// It emits the longest blocks first, and short blocks are just
2902 /// handled with direct compares.
2904 /// <param name="ec"></param>
2905 /// <param name="val"></param>
2906 /// <returns></returns>
2907 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2909 int cElements = Elements.Count;
2910 object [] rgKeys = new object [cElements];
2911 Elements.Keys.CopyTo (rgKeys, 0);
2912 Array.Sort (rgKeys);
2914 // initialize the block list with one element per key
2915 ArrayList rgKeyBlocks = new ArrayList ();
2916 foreach (object key in rgKeys)
2917 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
2920 // iteratively merge the blocks while they are at least half full
2921 // there's probably a really cool way to do this with a tree...
2922 while (rgKeyBlocks.Count > 1)
2924 ArrayList rgKeyBlocksNew = new ArrayList ();
2925 kbCurr = (KeyBlock) rgKeyBlocks [0];
2926 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2928 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2929 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2932 kbCurr.nLast = kb.nLast;
2936 // start a new block
2937 rgKeyBlocksNew.Add (kbCurr);
2941 rgKeyBlocksNew.Add (kbCurr);
2942 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2944 rgKeyBlocks = rgKeyBlocksNew;
2947 // initialize the key lists
2948 foreach (KeyBlock kb in rgKeyBlocks)
2949 kb.rgKeys = new ArrayList ();
2951 // fill the key lists
2953 if (rgKeyBlocks.Count > 0) {
2954 kbCurr = (KeyBlock) rgKeyBlocks [0];
2955 foreach (object key in rgKeys)
2957 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
2959 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2960 kbCurr.rgKeys.Add (key);
2964 // sort the blocks so we can tackle the largest ones first
2965 rgKeyBlocks.Sort ();
2967 // okay now we can start...
2968 ILGenerator ig = ec.ig;
2969 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2970 Label lblDefault = ig.DefineLabel ();
2972 Type typeKeys = null;
2973 if (rgKeys.Length > 0)
2974 typeKeys = rgKeys [0].GetType (); // used for conversions
2976 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2978 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2979 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2982 foreach (object key in kb.rgKeys)
2984 ig.Emit (OpCodes.Ldloc, val);
2985 EmitObjectInteger (ig, key);
2986 SwitchLabel sl = (SwitchLabel) Elements [key];
2987 ig.Emit (OpCodes.Beq, sl.ILLabel);
2992 // TODO: if all the keys in the block are the same and there are
2993 // no gaps/defaults then just use a range-check.
2994 if (SwitchType == TypeManager.int64_type ||
2995 SwitchType == TypeManager.uint64_type)
2997 // TODO: optimize constant/I4 cases
2999 // check block range (could be > 2^31)
3000 ig.Emit (OpCodes.Ldloc, val);
3001 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3002 ig.Emit (OpCodes.Blt, lblDefault);
3003 ig.Emit (OpCodes.Ldloc, val);
3004 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3005 ig.Emit (OpCodes.Bgt, lblDefault);
3008 ig.Emit (OpCodes.Ldloc, val);
3011 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3012 ig.Emit (OpCodes.Sub);
3014 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3019 ig.Emit (OpCodes.Ldloc, val);
3020 int nFirst = (int) kb.nFirst;
3023 IntConstant.EmitInt (ig, nFirst);
3024 ig.Emit (OpCodes.Sub);
3026 else if (nFirst < 0)
3028 IntConstant.EmitInt (ig, -nFirst);
3029 ig.Emit (OpCodes.Add);
3033 // first, build the list of labels for the switch
3035 int cJumps = kb.Length;
3036 Label [] rgLabels = new Label [cJumps];
3037 for (int iJump = 0; iJump < cJumps; iJump++)
3039 object key = kb.rgKeys [iKey];
3040 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3042 SwitchLabel sl = (SwitchLabel) Elements [key];
3043 rgLabels [iJump] = sl.ILLabel;
3047 rgLabels [iJump] = lblDefault;
3049 // emit the switch opcode
3050 ig.Emit (OpCodes.Switch, rgLabels);
3053 // mark the default for this block
3055 ig.MarkLabel (lblDefault);
3058 // TODO: find the default case and emit it here,
3059 // to prevent having to do the following jump.
3060 // make sure to mark other labels in the default section
3062 // the last default just goes to the end
3063 ig.Emit (OpCodes.Br, lblDefault);
3065 // now emit the code for the sections
3066 bool fFoundDefault = false;
3067 bool fAllReturn = true;
3068 foreach (SwitchSection ss in Sections)
3070 foreach (SwitchLabel sl in ss.Labels)
3072 ig.MarkLabel (sl.ILLabel);
3073 ig.MarkLabel (sl.ILLabelCode);
3074 if (sl.Label == null)
3076 ig.MarkLabel (lblDefault);
3077 fFoundDefault = true;
3080 fAllReturn &= ss.Block.Emit (ec);
3081 //ig.Emit (OpCodes.Br, lblEnd);
3084 if (!fFoundDefault) {
3085 ig.MarkLabel (lblDefault);
3088 ig.MarkLabel (lblEnd);
3093 // This simple emit switch works, but does not take advantage of the
3095 // TODO: remove non-string logic from here
3096 // TODO: binary search strings?
3098 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3100 ILGenerator ig = ec.ig;
3101 Label end_of_switch = ig.DefineLabel ();
3102 Label next_test = ig.DefineLabel ();
3103 Label null_target = ig.DefineLabel ();
3104 bool default_found = false;
3105 bool first_test = true;
3106 bool pending_goto_end = false;
3107 bool all_return = true;
3108 bool is_string = false;
3112 // Special processing for strings: we cant compare
3115 if (SwitchType == TypeManager.string_type){
3116 ig.Emit (OpCodes.Ldloc, val);
3119 if (Elements.Contains (NullLiteral.Null)){
3120 ig.Emit (OpCodes.Brfalse, null_target);
3122 ig.Emit (OpCodes.Brfalse, default_target);
3124 ig.Emit (OpCodes.Ldloc, val);
3125 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3126 ig.Emit (OpCodes.Stloc, val);
3129 SwitchSection last_section;
3130 last_section = (SwitchSection) Sections [Sections.Count-1];
3132 foreach (SwitchSection ss in Sections){
3133 Label sec_begin = ig.DefineLabel ();
3135 if (pending_goto_end)
3136 ig.Emit (OpCodes.Br, end_of_switch);
3138 int label_count = ss.Labels.Count;
3140 foreach (SwitchLabel sl in ss.Labels){
3141 ig.MarkLabel (sl.ILLabel);
3144 ig.MarkLabel (next_test);
3145 next_test = ig.DefineLabel ();
3148 // If we are the default target
3150 if (sl.Label == null){
3151 ig.MarkLabel (default_target);
3152 default_found = true;
3154 object lit = sl.Converted;
3156 if (lit is NullLiteral){
3158 if (label_count == 1)
3159 ig.Emit (OpCodes.Br, next_test);
3164 StringConstant str = (StringConstant) lit;
3166 ig.Emit (OpCodes.Ldloc, val);
3167 ig.Emit (OpCodes.Ldstr, str.Value);
3168 if (label_count == 1)
3169 ig.Emit (OpCodes.Bne_Un, next_test);
3171 ig.Emit (OpCodes.Beq, sec_begin);
3173 ig.Emit (OpCodes.Ldloc, val);
3174 EmitObjectInteger (ig, lit);
3175 ig.Emit (OpCodes.Ceq);
3176 if (label_count == 1)
3177 ig.Emit (OpCodes.Brfalse, next_test);
3179 ig.Emit (OpCodes.Brtrue, sec_begin);
3183 if (label_count != 1 && ss != last_section)
3184 ig.Emit (OpCodes.Br, next_test);
3187 ig.MarkLabel (null_target);
3188 ig.MarkLabel (sec_begin);
3189 foreach (SwitchLabel sl in ss.Labels)
\r
3190 ig.MarkLabel (sl.ILLabelCode);
3191 if (ss.Block.Emit (ec))
3192 pending_goto_end = false;
3195 pending_goto_end = true;
3199 if (!default_found){
3200 ig.MarkLabel (default_target);
3203 ig.MarkLabel (next_test);
3204 ig.MarkLabel (end_of_switch);
3209 public override bool Resolve (EmitContext ec)
3211 Expr = Expr.Resolve (ec);
3215 new_expr = SwitchGoverningType (ec, Expr.Type);
3216 if (new_expr == null){
3217 Report.Error (151, loc, "An integer type or string was expected for switch");
3222 SwitchType = new_expr.Type;
3224 if (!CheckSwitch (ec))
3227 Switch old_switch = ec.Switch;
3229 ec.Switch.SwitchType = SwitchType;
3231 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3234 foreach (SwitchSection ss in Sections){
3236 ec.CurrentBranching.CreateSibling ();
3240 if (ss.Block.Resolve (ec) != true)
3244 ec.EndFlowBranching ();
3245 ec.Switch = old_switch;
3250 public override bool Emit (EmitContext ec)
3252 // Store variable for comparission purposes
3253 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3255 ec.ig.Emit (OpCodes.Stloc, value);
3257 ILGenerator ig = ec.ig;
3259 default_target = ig.DefineLabel ();
3262 // Setup the codegen context
3264 Label old_end = ec.LoopEnd;
3265 Switch old_switch = ec.Switch;
3267 ec.LoopEnd = ig.DefineLabel ();
3272 if (SwitchType == TypeManager.string_type)
3273 all_return = SimpleSwitchEmit (ec, value);
3275 all_return = TableSwitchEmit (ec, value);
3277 // Restore context state.
3278 ig.MarkLabel (ec.LoopEnd);
3281 // Restore the previous context
3283 ec.LoopEnd = old_end;
3284 ec.Switch = old_switch;
3290 public class Lock : Statement {
3292 Statement Statement;
3294 public Lock (Expression expr, Statement stmt, Location l)
3301 public override bool Resolve (EmitContext ec)
3303 expr = expr.Resolve (ec);
3304 return Statement.Resolve (ec) && expr != null;
3307 public override bool Emit (EmitContext ec)
3309 Type type = expr.Type;
3312 if (type.IsValueType){
3313 Report.Error (185, loc, "lock statement requires the expression to be " +
3314 " a reference type (type is: `" +
3315 TypeManager.CSharpName (type) + "'");
3319 ILGenerator ig = ec.ig;
3320 LocalBuilder temp = ig.DeclareLocal (type);
3323 ig.Emit (OpCodes.Dup);
3324 ig.Emit (OpCodes.Stloc, temp);
3325 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3328 Label end = ig.BeginExceptionBlock ();
3329 bool old_in_try = ec.InTry;
3331 Label finish = ig.DefineLabel ();
3332 val = Statement.Emit (ec);
3333 ec.InTry = old_in_try;
3334 // ig.Emit (OpCodes.Leave, finish);
3336 ig.MarkLabel (finish);
3339 ig.BeginFinallyBlock ();
3340 ig.Emit (OpCodes.Ldloc, temp);
3341 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3342 ig.EndExceptionBlock ();
3348 public class Unchecked : Statement {
3349 public readonly Block Block;
3351 public Unchecked (Block b)
3356 public override bool Resolve (EmitContext ec)
3358 return Block.Resolve (ec);
3361 public override bool Emit (EmitContext ec)
3363 bool previous_state = ec.CheckState;
3364 bool previous_state_const = ec.ConstantCheckState;
3367 ec.CheckState = false;
3368 ec.ConstantCheckState = false;
3369 val = Block.Emit (ec);
3370 ec.CheckState = previous_state;
3371 ec.ConstantCheckState = previous_state_const;
3377 public class Checked : Statement {
3378 public readonly Block Block;
3380 public Checked (Block b)
3385 public override bool Resolve (EmitContext ec)
3387 bool previous_state = ec.CheckState;
3388 bool previous_state_const = ec.ConstantCheckState;
3390 ec.CheckState = true;
3391 ec.ConstantCheckState = true;
3392 bool ret = Block.Resolve (ec);
3393 ec.CheckState = previous_state;
3394 ec.ConstantCheckState = previous_state_const;
3399 public override bool Emit (EmitContext ec)
3401 bool previous_state = ec.CheckState;
3402 bool previous_state_const = ec.ConstantCheckState;
3405 ec.CheckState = true;
3406 ec.ConstantCheckState = true;
3407 val = Block.Emit (ec);
3408 ec.CheckState = previous_state;
3409 ec.ConstantCheckState = previous_state_const;
3415 public class Unsafe : Statement {
3416 public readonly Block Block;
3418 public Unsafe (Block b)
3423 public override bool Resolve (EmitContext ec)
3425 bool previous_state = ec.InUnsafe;
3429 val = Block.Resolve (ec);
3430 ec.InUnsafe = previous_state;
3435 public override bool Emit (EmitContext ec)
3437 bool previous_state = ec.InUnsafe;
3441 val = Block.Emit (ec);
3442 ec.InUnsafe = previous_state;
3451 public class Fixed : Statement {
3453 ArrayList declarators;
3454 Statement statement;
3459 public bool is_object;
3460 public VariableInfo vi;
3461 public Expression expr;
3462 public Expression converted;
3465 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3468 declarators = decls;
3473 public override bool Resolve (EmitContext ec)
3475 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3476 if (expr_type == null)
3479 data = new FixedData [declarators.Count];
3482 foreach (Pair p in declarators){
3483 VariableInfo vi = (VariableInfo) p.First;
3484 Expression e = (Expression) p.Second;
3489 // The rules for the possible declarators are pretty wise,
3490 // but the production on the grammar is more concise.
3492 // So we have to enforce these rules here.
3494 // We do not resolve before doing the case 1 test,
3495 // because the grammar is explicit in that the token &
3496 // is present, so we need to test for this particular case.
3500 // Case 1: & object.
3502 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3503 Expression child = ((Unary) e).Expr;
3506 if (child is ParameterReference || child is LocalVariableReference){
3509 "No need to use fixed statement for parameters or " +
3510 "local variable declarations (address is already " +
3519 child = ((Unary) e).Expr;
3521 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3524 data [i].is_object = true;
3526 data [i].converted = null;
3540 if (e.Type.IsArray){
3541 Type array_type = e.Type.GetElementType ();
3545 // Provided that array_type is unmanaged,
3547 if (!TypeManager.VerifyUnManaged (array_type, loc))
3551 // and T* is implicitly convertible to the
3552 // pointer type given in the fixed statement.
3554 ArrayPtr array_ptr = new ArrayPtr (e);
3556 Expression converted = Expression.ConvertImplicitRequired (
3557 ec, array_ptr, vi.VariableType, loc);
3558 if (converted == null)
3561 data [i].is_object = false;
3563 data [i].converted = converted;
3573 if (e.Type == TypeManager.string_type){
3574 data [i].is_object = false;
3576 data [i].converted = null;
3582 return statement.Resolve (ec);
3585 public override bool Emit (EmitContext ec)
3587 ILGenerator ig = ec.ig;
3589 bool is_ret = false;
3591 for (int i = 0; i < data.Length; i++) {
3592 VariableInfo vi = data [i].vi;
3595 // Case 1: & object.
3597 if (data [i].is_object) {
3599 // Store pointer in pinned location
3601 data [i].expr.Emit (ec);
3602 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3604 is_ret = statement.Emit (ec);
3606 // Clear the pinned variable.
3607 ig.Emit (OpCodes.Ldc_I4_0);
3608 ig.Emit (OpCodes.Conv_U);
3609 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3617 if (data [i].expr.Type.IsArray){
3619 // Store pointer in pinned location
3621 data [i].converted.Emit (ec);
3623 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3625 is_ret = statement.Emit (ec);
3627 // Clear the pinned variable.
3628 ig.Emit (OpCodes.Ldc_I4_0);
3629 ig.Emit (OpCodes.Conv_U);
3630 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3638 if (data [i].expr.Type == TypeManager.string_type){
3639 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3640 TypeManager.MakePinned (pinned_string);
3642 data [i].expr.Emit (ec);
3643 ig.Emit (OpCodes.Stloc, pinned_string);
3645 Expression sptr = new StringPtr (pinned_string);
3646 Expression converted = Expression.ConvertImplicitRequired (
3647 ec, sptr, vi.VariableType, loc);
3649 if (converted == null)
3652 converted.Emit (ec);
3653 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3655 is_ret = statement.Emit (ec);
3657 // Clear the pinned variable
3658 ig.Emit (OpCodes.Ldnull);
3659 ig.Emit (OpCodes.Stloc, pinned_string);
3667 public class Catch {
3668 public readonly string Name;
3669 public readonly Block Block;
3670 public readonly Location Location;
3674 public Catch (Expression type, string name, Block block, Location l)
3682 public Type CatchType {
3685 throw new InvalidOperationException ();
3691 public bool IsGeneral {
3693 return type == null;
3697 public bool Resolve (EmitContext ec)
3700 type = type.DoResolve (ec);
3705 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
3706 Report.Error (155, Location,
3707 "The type caught or thrown must be derived " +
3708 "from System.Exception");
3713 if (!Block.Resolve (ec))
3720 public class Try : Statement {
3721 public readonly Block Fini, Block;
3722 public readonly ArrayList Specific;
3723 public readonly Catch General;
3726 // specific, general and fini might all be null.
3728 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3730 if (specific == null && general == null){
3731 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3735 this.Specific = specific;
3736 this.General = general;
3741 public override bool Resolve (EmitContext ec)
3745 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
3747 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3749 if (!Block.Resolve (ec))
3752 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3754 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3756 foreach (Catch c in Specific){
3757 ec.CurrentBranching.CreateSibling ();
3758 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3760 if (c.Name != null) {
3761 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
3763 throw new Exception ();
3768 if (!c.Resolve (ec))
3771 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3773 if ((current.Returns == FlowReturns.NEVER) ||
3774 (current.Returns == FlowReturns.SOMETIMES)) {
3775 vector.AndLocals (current);
3779 if (General != null){
3780 ec.CurrentBranching.CreateSibling ();
3781 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3783 if (!General.Resolve (ec))
3786 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3788 if ((current.Returns == FlowReturns.NEVER) ||
3789 (current.Returns == FlowReturns.SOMETIMES)) {
3790 vector.AndLocals (current);
3794 ec.CurrentBranching.CreateSiblingForFinally ();
3795 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3798 if (!Fini.Resolve (ec))
3801 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3803 FlowReturns returns = ec.EndFlowBranching ();
3805 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3807 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3808 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3811 ec.CurrentBranching.CurrentUsageVector.Or (vector);
3813 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3818 public override bool Emit (EmitContext ec)
3820 ILGenerator ig = ec.ig;
3822 Label finish = ig.DefineLabel ();;
3826 end = ig.BeginExceptionBlock ();
3827 bool old_in_try = ec.InTry;
3829 returns = Block.Emit (ec);
3830 ec.InTry = old_in_try;
3833 // System.Reflection.Emit provides this automatically:
3834 // ig.Emit (OpCodes.Leave, finish);
3836 bool old_in_catch = ec.InCatch;
3838 DeclSpace ds = ec.DeclSpace;
3840 foreach (Catch c in Specific){
3843 ig.BeginCatchBlock (c.CatchType);
3845 if (c.Name != null){
3846 vi = c.Block.GetVariableInfo (c.Name);
3848 throw new Exception ("Variable does not exist in this block");
3850 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3852 ig.Emit (OpCodes.Pop);
3854 if (!c.Block.Emit (ec))
3858 if (General != null){
3859 ig.BeginCatchBlock (TypeManager.object_type);
3860 ig.Emit (OpCodes.Pop);
3861 if (!General.Block.Emit (ec))
3864 ec.InCatch = old_in_catch;
3866 ig.MarkLabel (finish);
3868 ig.BeginFinallyBlock ();
3869 bool old_in_finally = ec.InFinally;
3870 ec.InFinally = true;
3872 ec.InFinally = old_in_finally;
3875 ig.EndExceptionBlock ();
3878 if (!returns || ec.InTry || ec.InCatch)
3881 // Unfortunately, System.Reflection.Emit automatically emits a leave
3882 // to the end of the finally block. This is a problem if `returns'
3883 // is true since we may jump to a point after the end of the method.
3884 // As a workaround, emit an explicit ret here.
3886 if (ec.ReturnType != null)
3887 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
3888 ec.ig.Emit (OpCodes.Ret);
3895 // FIXME: We still do not support the expression variant of the using
3898 public class Using : Statement {
3899 object expression_or_block;
3900 Statement Statement;
3905 Expression [] converted_vars;
3906 ExpressionStatement [] assign;
3908 public Using (object expression_or_block, Statement stmt, Location l)
3910 this.expression_or_block = expression_or_block;
3916 // Resolves for the case of using using a local variable declaration.
3918 bool ResolveLocalVariableDecls (EmitContext ec)
3920 bool need_conv = false;
3921 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3924 if (expr_type == null)
3928 // The type must be an IDisposable or an implicit conversion
3931 converted_vars = new Expression [var_list.Count];
3932 assign = new ExpressionStatement [var_list.Count];
3933 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3934 foreach (DictionaryEntry e in var_list){
3935 Expression var = (Expression) e.Key;
3937 var = var.ResolveLValue (ec, new EmptyExpression ());
3941 converted_vars [i] = Expression.ConvertImplicit (
3942 ec, var, TypeManager.idisposable_type, loc);
3944 if (converted_vars [i] == null)
3952 foreach (DictionaryEntry e in var_list){
3953 LocalVariableReference var = (LocalVariableReference) e.Key;
3954 Expression new_expr = (Expression) e.Value;
3957 a = new Assign (var, new_expr, loc);
3963 converted_vars [i] = var;
3964 assign [i] = (ExpressionStatement) a;
3971 bool ResolveExpression (EmitContext ec)
3973 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3974 conv = Expression.ConvertImplicit (
3975 ec, expr, TypeManager.idisposable_type, loc);
3985 // Emits the code for the case of using using a local variable declaration.
3987 bool EmitLocalVariableDecls (EmitContext ec)
3989 ILGenerator ig = ec.ig;
3992 bool old_in_try = ec.InTry;
3994 for (i = 0; i < assign.Length; i++) {
3995 assign [i].EmitStatement (ec);
3997 ig.BeginExceptionBlock ();
3999 Statement.Emit (ec);
4000 ec.InTry = old_in_try;
4002 bool old_in_finally = ec.InFinally;
4003 ec.InFinally = true;
4004 var_list.Reverse ();
4005 foreach (DictionaryEntry e in var_list){
4006 LocalVariableReference var = (LocalVariableReference) e.Key;
4007 Label skip = ig.DefineLabel ();
4010 ig.BeginFinallyBlock ();
4013 ig.Emit (OpCodes.Brfalse, skip);
4014 converted_vars [i].Emit (ec);
4015 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4016 ig.MarkLabel (skip);
4017 ig.EndExceptionBlock ();
4019 ec.InFinally = old_in_finally;
4024 bool EmitExpression (EmitContext ec)
4027 // Make a copy of the expression and operate on that.
4029 ILGenerator ig = ec.ig;
4030 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4035 ig.Emit (OpCodes.Stloc, local_copy);
4037 bool old_in_try = ec.InTry;
4039 ig.BeginExceptionBlock ();
4040 Statement.Emit (ec);
4041 ec.InTry = old_in_try;
4043 Label skip = ig.DefineLabel ();
4044 bool old_in_finally = ec.InFinally;
4045 ig.BeginFinallyBlock ();
4046 ig.Emit (OpCodes.Ldloc, local_copy);
4047 ig.Emit (OpCodes.Brfalse, skip);
4048 ig.Emit (OpCodes.Ldloc, local_copy);
4049 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4050 ig.MarkLabel (skip);
4051 ec.InFinally = old_in_finally;
4052 ig.EndExceptionBlock ();
4057 public override bool Resolve (EmitContext ec)
4059 if (expression_or_block is DictionaryEntry){
4060 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4061 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4063 if (!ResolveLocalVariableDecls (ec))
4066 } else if (expression_or_block is Expression){
4067 expr = (Expression) expression_or_block;
4069 expr = expr.Resolve (ec);
4073 expr_type = expr.Type;
4075 if (!ResolveExpression (ec))
4079 return Statement.Resolve (ec);
4082 public override bool Emit (EmitContext ec)
4084 if (expression_or_block is DictionaryEntry)
4085 return EmitLocalVariableDecls (ec);
4086 else if (expression_or_block is Expression)
4087 return EmitExpression (ec);
4094 /// Implementation of the foreach C# statement
4096 public class Foreach : Statement {
4098 LocalVariableReference variable;
4100 Statement statement;
4101 ForeachHelperMethods hm;
4102 Expression empty, conv;
4103 Type array_type, element_type;
4106 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4107 Statement stmt, Location l)
4110 this.variable = var;
4116 public override bool Resolve (EmitContext ec)
4118 expr = expr.Resolve (ec);
4122 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4123 if (var_type == null)
4127 // We need an instance variable. Not sure this is the best
4128 // way of doing this.
4130 // FIXME: When we implement propertyaccess, will those turn
4131 // out to return values in ExprClass? I think they should.
4133 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4134 expr.eclass == ExprClass.PropertyAccess)){
4135 error1579 (expr.Type);
4139 if (expr.Type.IsArray) {
4140 array_type = expr.Type;
4141 element_type = array_type.GetElementType ();
4143 empty = new EmptyExpression (element_type);
4145 hm = ProbeCollectionType (ec, expr.Type);
4147 error1579 (expr.Type);
4151 array_type = expr.Type;
4152 element_type = hm.element_type;
4154 empty = new EmptyExpression (hm.element_type);
4158 // FIXME: maybe we can apply the same trick we do in the
4159 // array handling to avoid creating empty and conv in some cases.
4161 // Although it is not as important in this case, as the type
4162 // will not likely be object (what the enumerator will return).
4164 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4168 if (variable.ResolveLValue (ec, empty) == null)
4171 if (!statement.Resolve (ec))
4178 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4180 static MethodInfo FetchMethodMoveNext (Type t)
4182 MemberInfo [] move_next_list;
4184 move_next_list = TypeContainer.FindMembers (
4185 t, MemberTypes.Method,
4186 BindingFlags.Public | BindingFlags.Instance,
4187 Type.FilterName, "MoveNext");
4188 if (move_next_list == null || move_next_list.Length == 0)
4191 foreach (MemberInfo m in move_next_list){
4192 MethodInfo mi = (MethodInfo) m;
4195 args = TypeManager.GetArgumentTypes (mi);
4196 if (args != null && args.Length == 0){
4197 if (mi.ReturnType == TypeManager.bool_type)
4205 // Retrieves a `public T get_Current ()' method from the Type `t'
4207 static MethodInfo FetchMethodGetCurrent (Type t)
4209 MemberInfo [] move_next_list;
4211 move_next_list = TypeContainer.FindMembers (
4212 t, MemberTypes.Method,
4213 BindingFlags.Public | BindingFlags.Instance,
4214 Type.FilterName, "get_Current");
4215 if (move_next_list == null || move_next_list.Length == 0)
4218 foreach (MemberInfo m in move_next_list){
4219 MethodInfo mi = (MethodInfo) m;
4222 args = TypeManager.GetArgumentTypes (mi);
4223 if (args != null && args.Length == 0)
4230 // This struct records the helper methods used by the Foreach construct
4232 class ForeachHelperMethods {
4233 public EmitContext ec;
4234 public MethodInfo get_enumerator;
4235 public MethodInfo move_next;
4236 public MethodInfo get_current;
4237 public Type element_type;
4238 public Type enumerator_type;
4239 public bool is_disposable;
4241 public ForeachHelperMethods (EmitContext ec)
4244 this.element_type = TypeManager.object_type;
4245 this.enumerator_type = TypeManager.ienumerator_type;
4246 this.is_disposable = true;
4250 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4255 if (!(m is MethodInfo))
4258 if (m.Name != "GetEnumerator")
4261 MethodInfo mi = (MethodInfo) m;
4262 Type [] args = TypeManager.GetArgumentTypes (mi);
4264 if (args.Length != 0)
4267 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4268 EmitContext ec = hm.ec;
4271 // Check whether GetEnumerator is accessible to us
4273 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4275 Type declaring = mi.DeclaringType;
4276 if (prot == MethodAttributes.Private){
4277 if (declaring != ec.ContainerType)
4279 } else if (prot == MethodAttributes.FamANDAssem){
4280 // If from a different assembly, false
4281 if (!(mi is MethodBuilder))
4284 // Are we being invoked from the same class, or from a derived method?
4286 if (ec.ContainerType != declaring){
4287 if (!ec.ContainerType.IsSubclassOf (declaring))
4290 } else if (prot == MethodAttributes.FamORAssem){
4291 if (!(mi is MethodBuilder ||
4292 ec.ContainerType == declaring ||
4293 ec.ContainerType.IsSubclassOf (declaring)))
4295 } if (prot == MethodAttributes.Family){
4296 if (!(ec.ContainerType == declaring ||
4297 ec.ContainerType.IsSubclassOf (declaring)))
4302 // Ok, we can access it, now make sure that we can do something
4303 // with this `GetEnumerator'
4306 if (mi.ReturnType == TypeManager.ienumerator_type ||
4307 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4308 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4309 hm.move_next = TypeManager.bool_movenext_void;
4310 hm.get_current = TypeManager.object_getcurrent_void;
4315 // Ok, so they dont return an IEnumerable, we will have to
4316 // find if they support the GetEnumerator pattern.
4318 Type return_type = mi.ReturnType;
4320 hm.move_next = FetchMethodMoveNext (return_type);
4321 if (hm.move_next == null)
4323 hm.get_current = FetchMethodGetCurrent (return_type);
4324 if (hm.get_current == null)
4327 hm.element_type = hm.get_current.ReturnType;
4328 hm.enumerator_type = return_type;
4329 hm.is_disposable = TypeManager.ImplementsInterface (
4330 hm.enumerator_type, TypeManager.idisposable_type);
4336 /// This filter is used to find the GetEnumerator method
4337 /// on which IEnumerator operates
4339 static MemberFilter FilterEnumerator;
4343 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4346 void error1579 (Type t)
4348 Report.Error (1579, loc,
4349 "foreach statement cannot operate on variables of type `" +
4350 t.FullName + "' because that class does not provide a " +
4351 " GetEnumerator method or it is inaccessible");
4354 static bool TryType (Type t, ForeachHelperMethods hm)
4358 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4359 BindingFlags.Public | BindingFlags.NonPublic |
4360 BindingFlags.Instance,
4361 FilterEnumerator, hm);
4363 if (mi == null || mi.Length == 0)
4366 hm.get_enumerator = (MethodInfo) mi [0];
4371 // Looks for a usable GetEnumerator in the Type, and if found returns
4372 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4374 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4376 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4378 if (TryType (t, hm))
4382 // Now try to find the method in the interfaces
4385 Type [] ifaces = t.GetInterfaces ();
4387 foreach (Type i in ifaces){
4388 if (TryType (i, hm))
4393 // Since TypeBuilder.GetInterfaces only returns the interface
4394 // types for this type, we have to keep looping, but once
4395 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4396 // done, because it returns all the types
4398 if ((t is TypeBuilder))
4408 // FIXME: possible optimization.
4409 // We might be able to avoid creating `empty' if the type is the sam
4411 bool EmitCollectionForeach (EmitContext ec)
4413 ILGenerator ig = ec.ig;
4414 LocalBuilder enumerator, disposable;
4416 enumerator = ig.DeclareLocal (hm.enumerator_type);
4417 if (hm.is_disposable)
4418 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4423 // Instantiate the enumerator
4425 if (expr.Type.IsValueType){
4426 if (expr is IMemoryLocation){
4427 IMemoryLocation ml = (IMemoryLocation) expr;
4429 ml.AddressOf (ec, AddressOp.Load);
4431 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4432 " does not implement IMemoryLocation");
4433 ig.Emit (OpCodes.Call, hm.get_enumerator);
4436 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4438 ig.Emit (OpCodes.Stloc, enumerator);
4441 // Protect the code in a try/finalize block, so that
4442 // if the beast implement IDisposable, we get rid of it
4445 bool old_in_try = ec.InTry;
4447 if (hm.is_disposable) {
4448 l = ig.BeginExceptionBlock ();
4452 Label end_try = ig.DefineLabel ();
4454 ig.MarkLabel (ec.LoopBegin);
4455 ig.Emit (OpCodes.Ldloc, enumerator);
4456 ig.Emit (OpCodes.Callvirt, hm.move_next);
4457 ig.Emit (OpCodes.Brfalse, end_try);
4458 ig.Emit (OpCodes.Ldloc, enumerator);
4459 ig.Emit (OpCodes.Callvirt, hm.get_current);
4460 variable.EmitAssign (ec, conv);
4461 statement.Emit (ec);
4462 ig.Emit (OpCodes.Br, ec.LoopBegin);
4463 ig.MarkLabel (end_try);
4464 ec.InTry = old_in_try;
4466 // The runtime provides this for us.
4467 // ig.Emit (OpCodes.Leave, end);
4470 // Now the finally block
4472 if (hm.is_disposable) {
4473 Label end_finally = ig.DefineLabel ();
4474 bool old_in_finally = ec.InFinally;
4475 ec.InFinally = true;
4476 ig.BeginFinallyBlock ();
4478 ig.Emit (OpCodes.Ldloc, enumerator);
4479 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4480 ig.Emit (OpCodes.Stloc, disposable);
4481 ig.Emit (OpCodes.Ldloc, disposable);
4482 ig.Emit (OpCodes.Brfalse, end_finally);
4483 ig.Emit (OpCodes.Ldloc, disposable);
4484 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4485 ig.MarkLabel (end_finally);
4486 ec.InFinally = old_in_finally;
4488 // The runtime generates this anyways.
4489 // ig.Emit (OpCodes.Endfinally);
4491 ig.EndExceptionBlock ();
4494 ig.MarkLabel (ec.LoopEnd);
4499 // FIXME: possible optimization.
4500 // We might be able to avoid creating `empty' if the type is the sam
4502 bool EmitArrayForeach (EmitContext ec)
4504 int rank = array_type.GetArrayRank ();
4505 ILGenerator ig = ec.ig;
4507 LocalBuilder copy = ig.DeclareLocal (array_type);
4510 // Make our copy of the array
4513 ig.Emit (OpCodes.Stloc, copy);
4516 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4520 ig.Emit (OpCodes.Ldc_I4_0);
4521 ig.Emit (OpCodes.Stloc, counter);
4522 test = ig.DefineLabel ();
4523 ig.Emit (OpCodes.Br, test);
4525 loop = ig.DefineLabel ();
4526 ig.MarkLabel (loop);
4528 ig.Emit (OpCodes.Ldloc, copy);
4529 ig.Emit (OpCodes.Ldloc, counter);
4530 ArrayAccess.EmitLoadOpcode (ig, var_type);
4532 variable.EmitAssign (ec, conv);
4534 statement.Emit (ec);
4536 ig.MarkLabel (ec.LoopBegin);
4537 ig.Emit (OpCodes.Ldloc, counter);
4538 ig.Emit (OpCodes.Ldc_I4_1);
4539 ig.Emit (OpCodes.Add);
4540 ig.Emit (OpCodes.Stloc, counter);
4542 ig.MarkLabel (test);
4543 ig.Emit (OpCodes.Ldloc, counter);
4544 ig.Emit (OpCodes.Ldloc, copy);
4545 ig.Emit (OpCodes.Ldlen);
4546 ig.Emit (OpCodes.Conv_I4);
4547 ig.Emit (OpCodes.Blt, loop);
4549 LocalBuilder [] dim_len = new LocalBuilder [rank];
4550 LocalBuilder [] dim_count = new LocalBuilder [rank];
4551 Label [] loop = new Label [rank];
4552 Label [] test = new Label [rank];
4555 for (dim = 0; dim < rank; dim++){
4556 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
4557 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
4558 test [dim] = ig.DefineLabel ();
4559 loop [dim] = ig.DefineLabel ();
4562 for (dim = 0; dim < rank; dim++){
4563 ig.Emit (OpCodes.Ldloc, copy);
4564 IntLiteral.EmitInt (ig, dim);
4565 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4566 ig.Emit (OpCodes.Stloc, dim_len [dim]);
4569 for (dim = 0; dim < rank; dim++){
4570 ig.Emit (OpCodes.Ldc_I4_0);
4571 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4572 ig.Emit (OpCodes.Br, test [dim]);
4573 ig.MarkLabel (loop [dim]);
4576 ig.Emit (OpCodes.Ldloc, copy);
4577 for (dim = 0; dim < rank; dim++)
4578 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4581 // FIXME: Maybe we can cache the computation of `get'?
4583 Type [] args = new Type [rank];
4586 for (int i = 0; i < rank; i++)
4587 args [i] = TypeManager.int32_type;
4589 ModuleBuilder mb = CodeGen.ModuleBuilder;
4590 get = mb.GetArrayMethod (
4592 CallingConventions.HasThis| CallingConventions.Standard,
4594 ig.Emit (OpCodes.Call, get);
4595 variable.EmitAssign (ec, conv);
4596 statement.Emit (ec);
4597 ig.MarkLabel (ec.LoopBegin);
4598 for (dim = rank - 1; dim >= 0; dim--){
4599 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4600 ig.Emit (OpCodes.Ldc_I4_1);
4601 ig.Emit (OpCodes.Add);
4602 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4604 ig.MarkLabel (test [dim]);
4605 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4606 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
4607 ig.Emit (OpCodes.Blt, loop [dim]);
4610 ig.MarkLabel (ec.LoopEnd);
4615 public override bool Emit (EmitContext ec)
4619 ILGenerator ig = ec.ig;
4621 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4622 bool old_inloop = ec.InLoop;
4623 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4624 ec.LoopBegin = ig.DefineLabel ();
4625 ec.LoopEnd = ig.DefineLabel ();
4627 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4630 ret_val = EmitCollectionForeach (ec);
4632 ret_val = EmitArrayForeach (ec);
4634 ec.LoopBegin = old_begin;
4635 ec.LoopEnd = old_end;
4636 ec.InLoop = old_inloop;
4637 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;