2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics.SymbolStore;
17 namespace Mono.CSharp {
20 /// Code generator class.
22 public class CodeGen {
23 static AppDomain current_domain;
24 public static AssemblyBuilder AssemblyBuilder;
25 public static ModuleBuilder ModuleBuilder;
27 static public ISymbolWriter SymbolWriter;
29 public static string Basename (string name)
31 int pos = name.LastIndexOf ("/");
34 return name.Substring (pos + 1);
36 pos = name.LastIndexOf ("\\");
38 return name.Substring (pos + 1);
43 public static string Dirname (string name)
45 int pos = name.LastIndexOf ("/");
48 return name.Substring (0, pos);
50 pos = name.LastIndexOf ("\\");
52 return name.Substring (0, pos);
57 static string TrimExt (string name)
59 int pos = name.LastIndexOf (".");
61 return name.Substring (0, pos);
64 static public string FileName;
67 // This routine initializes the Mono runtime SymbolWriter.
69 static bool InitMonoSymbolWriter (string basename, string symbol_output,
70 string exe_output_file, string[] debug_args)
72 Type itype = SymbolWriter.GetType ();
76 Type[] arg_types = new Type [3];
77 arg_types [0] = typeof (string);
78 arg_types [1] = typeof (string);
79 arg_types [2] = typeof (string[]);
81 MethodInfo initialize = itype.GetMethod ("Initialize", arg_types);
82 if (initialize == null)
85 object[] args = new object [3];
86 args [0] = exe_output_file;
87 args [1] = symbol_output;
88 args [2] = debug_args;
90 initialize.Invoke (SymbolWriter, args);
95 // Initializes the symbol writer
97 static void InitializeSymbolWriter (string basename, string symbol_output,
98 string exe_output_file, string[] args)
100 SymbolWriter = ModuleBuilder.GetSymWriter ();
103 // If we got an ISymbolWriter instance, initialize it.
105 if (SymbolWriter == null) {
107 -18, "Cannot find any symbol writer");
112 // Due to lacking documentation about the first argument of the
113 // Initialize method, we cannot use Microsoft's default symbol
116 // If we're using the mono symbol writer, the SymbolWriter object
117 // is of type MonoSymbolWriter - but that's defined in a dynamically
118 // loaded DLL - that's why we're doing a comparision based on the type
119 // name here instead of using `SymbolWriter is MonoSymbolWriter'.
121 Type sym_type = ((object) SymbolWriter).GetType ();
123 switch (sym_type.Name){
124 case "MonoSymbolWriter":
125 if (!InitMonoSymbolWriter (basename, symbol_output,
126 exe_output_file, args))
128 -18, "Cannot initialize the symbol writer");
133 -18, "Cannot generate debugging information on this platform");
139 // Initializes the code generator variables
141 static public void Init (string name, string output, bool want_debugging_support,
147 an = new AssemblyName ();
148 an.Name = TrimExt (Basename (name));
149 current_domain = AppDomain.CurrentDomain;
150 AssemblyBuilder = current_domain.DefineDynamicAssembly (
151 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
154 // Pass a path-less name to DefineDynamicModule. Wonder how
155 // this copes with output in different directories then.
156 // FIXME: figure out how this copes with --output /tmp/blah
158 // If the third argument is true, the ModuleBuilder will dynamically
159 // load the default symbol writer.
161 ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
162 Basename (name), Basename (output), want_debugging_support);
164 int pos = output.LastIndexOf (".");
168 basename = output.Substring (0, pos);
172 string symbol_output = basename + ".dbg";
174 if (want_debugging_support)
175 InitializeSymbolWriter (basename, symbol_output, output, debug_args);
178 File.Delete (symbol_output);
185 static public void Save (string name)
188 AssemblyBuilder.Save (Basename (name));
189 } catch (System.IO.IOException io){
190 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
194 static public void SaveSymbols ()
196 if (SymbolWriter != null) {
197 // If we have a symbol writer, call its Close() method to write
198 // the symbol file to disk.
200 // When using Mono's default symbol writer, the Close() method must
201 // be called after the assembly has already been written to disk since
202 // it opens the assembly and reads its metadata.
203 SymbolWriter.Close ();
209 /// An Emit Context is created for each body of code (from methods,
210 /// properties bodies, indexer bodies or constructor bodies)
212 public class EmitContext {
213 public DeclSpace DeclSpace;
214 public TypeContainer TypeContainer;
215 public ILGenerator ig;
218 /// This variable tracks the `checked' state of the compilation,
219 /// it controls whether we should generate code that does overflow
220 /// checking, or if we generate code that ignores overflows.
222 /// The default setting comes from the command line option to generate
223 /// checked or unchecked code plus any source code changes using the
224 /// checked/unchecked statements or expressions. Contrast this with
225 /// the ConstantCheckState flag.
228 public bool CheckState;
231 /// The constant check state is always set to `true' and cant be changed
232 /// from the command line. The source code can change this setting with
233 /// the `checked' and `unchecked' statements and expressions.
235 public bool ConstantCheckState;
238 /// Whether we are emitting code inside a static or instance method
240 public bool IsStatic;
243 /// Whether we are emitting a field initializer
245 public bool IsFieldInitializer;
248 /// The value that is allowed to be returned or NULL if there is no
251 public Type ReturnType;
254 /// Points to the Type (extracted from the TypeContainer) that
255 /// declares this body of code
257 public Type ContainerType;
260 /// Whether this is generating code for a constructor
262 public bool IsConstructor;
265 /// Whether we're control flow analysis enabled
267 public bool DoFlowAnalysis;
270 /// Keeps track of the Type to LocalBuilder temporary storage created
271 /// to store structures (used to compute the address of the structure
272 /// value on structure method invocations)
274 public Hashtable temporary_storage;
276 public Block CurrentBlock;
279 /// The location where we store the return value.
281 LocalBuilder return_value;
284 /// The location where return has to jump to return the
287 public Label ReturnLabel;
290 /// If we already defined the ReturnLabel
292 public bool HasReturnLabel;
295 /// Whether we are in a Finally block
297 public bool InFinally;
300 /// Whether we are in a Try block
305 /// Whether we are in a Catch block
310 /// Whether we are inside an unsafe block
312 public bool InUnsafe;
315 /// Location for this EmitContext
320 /// Used to flag that it is ok to define types recursively, as the
321 /// expressions are being evaluated as part of the type lookup
322 /// during the type resolution process
324 public bool ResolvingTypeTree;
327 /// Inside an enum definition, we do not resolve enumeration values
328 /// to their enumerations, but rather to the underlying type/value
329 /// This is so EnumVal + EnumValB can be evaluated.
331 /// There is no "E operator + (E x, E y)", so during an enum evaluation
332 /// we relax the rules
334 public bool InEnumContext;
336 protected Stack FlowStack;
338 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
339 Type return_type, int code_flags, bool is_constructor)
343 TypeContainer = parent;
345 CheckState = RootContext.Checked;
346 ConstantCheckState = true;
348 IsStatic = (code_flags & Modifiers.STATIC) != 0;
349 ReturnType = return_type;
350 IsConstructor = is_constructor;
354 // Can only be null for the ResolveType contexts.
355 ContainerType = parent.TypeBuilder;
356 if (parent.UnsafeContext)
359 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
363 FlowStack = new Stack ();
365 if (ReturnType == TypeManager.void_type)
369 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
370 Type return_type, int code_flags, bool is_constructor)
371 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
375 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
376 Type return_type, int code_flags)
377 : this (tc, tc, l, ig, return_type, code_flags, false)
381 public FlowBranching CurrentBranching {
383 return (FlowBranching) FlowStack.Peek ();
388 // Starts a new code branching. This inherits the state of all local
389 // variables and parameters from the current branching.
391 public FlowBranching StartFlowBranching (FlowBranchingType type, Location loc)
393 FlowBranching cfb = new FlowBranching (CurrentBranching, type, null, loc);
395 FlowStack.Push (cfb);
401 // Starts a new code branching for block `block'.
403 public FlowBranching StartFlowBranching (Block block)
406 FlowBranchingType type;
408 if (CurrentBranching.Type == FlowBranchingType.SWITCH)
409 type = FlowBranchingType.SWITCH_SECTION;
411 type = FlowBranchingType.BLOCK;
413 cfb = new FlowBranching (CurrentBranching, type, block, block.StartLocation);
415 FlowStack.Push (cfb);
421 // Ends a code branching. Merges the state of locals and parameters
422 // from all the children of the ending branching.
424 public FlowReturns EndFlowBranching ()
426 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
428 return CurrentBranching.MergeChild (cfb);
432 // Kills the current code branching. This throws away any changed state
433 // information and should only be used in case of an error.
435 public void KillFlowBranching ()
437 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
441 // Checks whether the local variable `vi' is already initialized
442 // at the current point of the method's control flow.
443 // If this method returns false, the caller must report an
446 public bool IsVariableAssigned (VariableInfo vi)
449 return CurrentBranching.IsVariableAssigned (vi);
455 // Marks the local variable `vi' as being initialized at the current
456 // current point of the method's control flow.
458 public void SetVariableAssigned (VariableInfo vi)
461 CurrentBranching.SetVariableAssigned (vi);
465 // Checks whether the parameter `number' is already initialized
466 // at the current point of the method's control flow.
467 // If this method returns false, the caller must report an
468 // error 165. This is only necessary for `out' parameters and the
469 // call will always succeed for non-`out' parameters.
471 public bool IsParameterAssigned (int number)
474 return CurrentBranching.IsParameterAssigned (number);
480 // Marks the parameter `number' as being initialized at the current
481 // current point of the method's control flow. This is only necessary
482 // for `out' parameters.
484 public void SetParameterAssigned (int number)
487 CurrentBranching.SetParameterAssigned (number);
490 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
492 bool has_ret = false;
494 // Console.WriteLine ("Emitting: " + loc);
496 if (CodeGen.SymbolWriter != null)
500 int errors = Report.Errors;
502 block.EmitMeta (this, block);
504 if (Report.Errors == errors){
505 bool old_do_flow_analysis = DoFlowAnalysis;
506 DoFlowAnalysis = true;
508 FlowBranching cfb = new FlowBranching (block, ip, loc);
509 FlowStack.Push (cfb);
511 if (!block.Resolve (this)) {
513 DoFlowAnalysis = old_do_flow_analysis;
517 cfb = (FlowBranching) FlowStack.Pop ();
518 FlowReturns returns = cfb.MergeTopBlock ();
520 DoFlowAnalysis = old_do_flow_analysis;
522 has_ret = block.Emit (this);
524 if ((returns == FlowReturns.ALWAYS) ||
525 (returns == FlowReturns.EXCEPTION) ||
526 (returns == FlowReturns.UNREACHABLE))
529 if (Report.Errors == errors){
530 if (RootContext.WarningLevel >= 3)
531 block.UsageWarning ();
536 if (ReturnType != null && !has_ret){
538 // FIXME: we need full flow analysis to implement this
539 // correctly and emit an error instead of a warning.
542 Report.Error (161, loc, "Not all code paths return a value");
547 ig.MarkLabel (ReturnLabel);
548 if (return_value != null){
549 ig.Emit (OpCodes.Ldloc, return_value);
550 ig.Emit (OpCodes.Ret);
553 if (!has_ret || HasReturnLabel)
554 ig.Emit (OpCodes.Ret);
560 /// This is called immediately before emitting an IL opcode to tell the symbol
561 /// writer to which source line this opcode belongs.
563 public void Mark (Location loc)
565 if ((CodeGen.SymbolWriter != null) && !Location.IsNull (loc)) {
566 ISymbolDocumentWriter doc = loc.SymbolDocument;
569 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
574 /// Returns a temporary storage for a variable of type t as
575 /// a local variable in the current body.
577 public LocalBuilder GetTemporaryStorage (Type t)
579 LocalBuilder location;
581 if (temporary_storage != null){
582 location = (LocalBuilder) temporary_storage [t];
583 if (location != null)
587 location = ig.DeclareLocal (t);
592 public void FreeTemporaryStorage (LocalBuilder b)
598 /// Current loop begin and end labels.
600 public Label LoopBegin, LoopEnd;
603 /// Whether we are inside a loop and break/continue are possible.
608 /// This is incremented each time we enter a try/catch block and
609 /// decremented if we leave it.
611 public int TryCatchLevel;
614 /// The TryCatchLevel at the begin of the current loop.
616 public int LoopBeginTryCatchLevel;
619 /// Default target in a switch statement. Only valid if
622 public Label DefaultTarget;
625 /// If this is non-null, points to the current switch statement
627 public Switch Switch;
630 /// ReturnValue creates on demand the LocalBuilder for the
631 /// return value from the function. By default this is not
632 /// used. This is only required when returns are found inside
633 /// Try or Catch statements.
635 public LocalBuilder TemporaryReturn ()
637 if (return_value == null){
638 return_value = ig.DeclareLocal (ReturnType);
639 ReturnLabel = ig.DefineLabel ();
640 HasReturnLabel = true;
647 /// A dynamic This that is shared by all variables in a emitcontext.
648 /// Created on demand.
650 public Expression my_this;
651 public Expression This {
653 if (my_this == null) {
654 if (CurrentBlock != null)
655 my_this = new This (CurrentBlock, loc);
657 my_this = new This (loc);
659 my_this = my_this.Resolve (this);