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 = Path.GetFileNameWithoutExtension (name);
150 current_domain = AppDomain.CurrentDomain;
151 AssemblyBuilder = current_domain.DefineDynamicAssembly (
152 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
155 // Pass a path-less name to DefineDynamicModule. Wonder how
156 // this copes with output in different directories then.
157 // FIXME: figure out how this copes with --output /tmp/blah
159 // If the third argument is true, the ModuleBuilder will dynamically
160 // load the default symbol writer.
162 ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
163 Basename (name), Basename (output), want_debugging_support);
165 int pos = output.LastIndexOf (".");
169 basename = output.Substring (0, pos);
173 string symbol_output = basename + ".dbg";
175 if (want_debugging_support)
176 InitializeSymbolWriter (basename, symbol_output, output, debug_args);
179 File.Delete (symbol_output);
186 static public void Save (string name)
189 AssemblyBuilder.Save (Basename (name));
190 } catch (System.IO.IOException io){
191 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
195 static public void SaveSymbols ()
197 if (SymbolWriter != null) {
198 // If we have a symbol writer, call its Close() method to write
199 // the symbol file to disk.
201 // When using Mono's default symbol writer, the Close() method must
202 // be called after the assembly has already been written to disk since
203 // it opens the assembly and reads its metadata.
204 SymbolWriter.Close ();
210 /// An Emit Context is created for each body of code (from methods,
211 /// properties bodies, indexer bodies or constructor bodies)
213 public class EmitContext {
214 public DeclSpace DeclSpace;
215 public DeclSpace TypeContainer;
216 public ILGenerator ig;
219 /// This variable tracks the `checked' state of the compilation,
220 /// it controls whether we should generate code that does overflow
221 /// checking, or if we generate code that ignores overflows.
223 /// The default setting comes from the command line option to generate
224 /// checked or unchecked code plus any source code changes using the
225 /// checked/unchecked statements or expressions. Contrast this with
226 /// the ConstantCheckState flag.
229 public bool CheckState;
232 /// The constant check state is always set to `true' and cant be changed
233 /// from the command line. The source code can change this setting with
234 /// the `checked' and `unchecked' statements and expressions.
236 public bool ConstantCheckState;
239 /// Whether we are emitting code inside a static or instance method
241 public bool IsStatic;
244 /// Whether we are emitting a field initializer
246 public bool IsFieldInitializer;
249 /// The value that is allowed to be returned or NULL if there is no
252 public Type ReturnType;
255 /// Points to the Type (extracted from the TypeContainer) that
256 /// declares this body of code
258 public Type ContainerType;
261 /// Whether this is generating code for a constructor
263 public bool IsConstructor;
266 /// Whether we're control flow analysis enabled
268 public bool DoFlowAnalysis;
271 /// Keeps track of the Type to LocalBuilder temporary storage created
272 /// to store structures (used to compute the address of the structure
273 /// value on structure method invocations)
275 public Hashtable temporary_storage;
277 public Block CurrentBlock;
280 /// The location where we store the return value.
282 LocalBuilder return_value;
285 /// The location where return has to jump to return the
288 public Label ReturnLabel;
291 /// If we already defined the ReturnLabel
293 public bool HasReturnLabel;
296 /// Whether we are in a Finally block
298 public bool InFinally;
301 /// Whether we are in a Try block
306 /// Whether we are in a Catch block
311 /// Whether we are inside an unsafe block
313 public bool InUnsafe;
316 /// Location for this EmitContext
321 /// Used to flag that it is ok to define types recursively, as the
322 /// expressions are being evaluated as part of the type lookup
323 /// during the type resolution process
325 public bool ResolvingTypeTree;
328 /// Inside an enum definition, we do not resolve enumeration values
329 /// to their enumerations, but rather to the underlying type/value
330 /// This is so EnumVal + EnumValB can be evaluated.
332 /// There is no "E operator + (E x, E y)", so during an enum evaluation
333 /// we relax the rules
335 public bool InEnumContext;
337 protected Stack FlowStack;
339 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
340 Type return_type, int code_flags, bool is_constructor)
344 TypeContainer = parent;
346 CheckState = RootContext.Checked;
347 ConstantCheckState = true;
349 IsStatic = (code_flags & Modifiers.STATIC) != 0;
350 ReturnType = return_type;
351 IsConstructor = is_constructor;
355 // Can only be null for the ResolveType contexts.
356 ContainerType = parent.TypeBuilder;
357 if (parent.UnsafeContext)
360 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
364 FlowStack = new Stack ();
366 if (ReturnType == TypeManager.void_type)
370 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
371 Type return_type, int code_flags, bool is_constructor)
372 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
376 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
377 Type return_type, int code_flags)
378 : this (tc, tc, l, ig, return_type, code_flags, false)
382 public FlowBranching CurrentBranching {
384 return (FlowBranching) FlowStack.Peek ();
389 // Starts a new code branching. This inherits the state of all local
390 // variables and parameters from the current branching.
392 public FlowBranching StartFlowBranching (FlowBranchingType type, Location loc)
394 FlowBranching cfb = new FlowBranching (CurrentBranching, type, null, loc);
396 FlowStack.Push (cfb);
402 // Starts a new code branching for block `block'.
404 public FlowBranching StartFlowBranching (Block block)
407 FlowBranchingType type;
409 if (CurrentBranching.Type == FlowBranchingType.SWITCH)
410 type = FlowBranchingType.SWITCH_SECTION;
412 type = FlowBranchingType.BLOCK;
414 cfb = new FlowBranching (CurrentBranching, type, block, block.StartLocation);
416 FlowStack.Push (cfb);
422 // Ends a code branching. Merges the state of locals and parameters
423 // from all the children of the ending branching.
425 public FlowReturns EndFlowBranching ()
427 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
429 return CurrentBranching.MergeChild (cfb);
433 // Kills the current code branching. This throws away any changed state
434 // information and should only be used in case of an error.
436 public void KillFlowBranching ()
438 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
442 // Checks whether the local variable `vi' is already initialized
443 // at the current point of the method's control flow.
444 // If this method returns false, the caller must report an
447 public bool IsVariableAssigned (VariableInfo vi)
450 return CurrentBranching.IsVariableAssigned (vi);
456 // Marks the local variable `vi' as being initialized at the current
457 // current point of the method's control flow.
459 public void SetVariableAssigned (VariableInfo vi)
462 CurrentBranching.SetVariableAssigned (vi);
466 // Checks whether the parameter `number' is already initialized
467 // at the current point of the method's control flow.
468 // If this method returns false, the caller must report an
469 // error 165. This is only necessary for `out' parameters and the
470 // call will always succeed for non-`out' parameters.
472 public bool IsParameterAssigned (int number)
475 return CurrentBranching.IsParameterAssigned (number);
481 // Marks the parameter `number' as being initialized at the current
482 // current point of the method's control flow. This is only necessary
483 // for `out' parameters.
485 public void SetParameterAssigned (int number)
488 CurrentBranching.SetParameterAssigned (number);
491 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
493 bool has_ret = false;
495 // Console.WriteLine ("Emitting: " + loc);
497 if (CodeGen.SymbolWriter != null)
502 int errors = Report.Errors;
504 block.EmitMeta (this, block);
506 if (Report.Errors == errors){
507 bool old_do_flow_analysis = DoFlowAnalysis;
508 DoFlowAnalysis = true;
510 FlowBranching cfb = new FlowBranching (block, ip, loc);
511 FlowStack.Push (cfb);
513 if (!block.Resolve (this)) {
515 DoFlowAnalysis = old_do_flow_analysis;
519 cfb = (FlowBranching) FlowStack.Pop ();
520 FlowReturns returns = cfb.MergeTopBlock ();
522 DoFlowAnalysis = old_do_flow_analysis;
524 has_ret = block.Emit (this);
526 if ((returns == FlowReturns.ALWAYS) ||
527 (returns == FlowReturns.EXCEPTION) ||
528 (returns == FlowReturns.UNREACHABLE))
531 if (Report.Errors == errors){
532 if (RootContext.WarningLevel >= 3)
533 block.UsageWarning ();
537 Console.WriteLine ("Exception caught by the compiler while compiling:");
538 Console.WriteLine (" Block that caused the problem begin at: " + loc);
539 Console.WriteLine (" Block being compiled: [{0},{1}]",
540 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
545 if (ReturnType != null && !has_ret){
547 // FIXME: we need full flow analysis to implement this
548 // correctly and emit an error instead of a warning.
551 Report.Error (161, loc, "Not all code paths return a value");
556 ig.MarkLabel (ReturnLabel);
557 if (return_value != null){
558 ig.Emit (OpCodes.Ldloc, return_value);
559 ig.Emit (OpCodes.Ret);
562 if (!has_ret || HasReturnLabel)
563 ig.Emit (OpCodes.Ret);
569 /// This is called immediately before emitting an IL opcode to tell the symbol
570 /// writer to which source line this opcode belongs.
572 public void Mark (Location loc)
574 if ((CodeGen.SymbolWriter != null) && !Location.IsNull (loc)) {
575 ISymbolDocumentWriter doc = loc.SymbolDocument;
578 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
583 /// Returns a temporary storage for a variable of type t as
584 /// a local variable in the current body.
586 public LocalBuilder GetTemporaryStorage (Type t)
588 LocalBuilder location;
590 if (temporary_storage != null){
591 location = (LocalBuilder) temporary_storage [t];
592 if (location != null)
596 location = ig.DeclareLocal (t);
601 public void FreeTemporaryStorage (LocalBuilder b)
607 /// Current loop begin and end labels.
609 public Label LoopBegin, LoopEnd;
612 /// Whether we are inside a loop and break/continue are possible.
617 /// This is incremented each time we enter a try/catch block and
618 /// decremented if we leave it.
620 public int TryCatchLevel;
623 /// The TryCatchLevel at the begin of the current loop.
625 public int LoopBeginTryCatchLevel;
628 /// Default target in a switch statement. Only valid if
631 public Label DefaultTarget;
634 /// If this is non-null, points to the current switch statement
636 public Switch Switch;
639 /// ReturnValue creates on demand the LocalBuilder for the
640 /// return value from the function. By default this is not
641 /// used. This is only required when returns are found inside
642 /// Try or Catch statements.
644 public LocalBuilder TemporaryReturn ()
646 if (return_value == null){
647 return_value = ig.DeclareLocal (ReturnType);
648 ReturnLabel = ig.DefineLabel ();
649 HasReturnLabel = true;
656 /// A dynamic This that is shared by all variables in a emitcontext.
657 /// Created on demand.
659 public Expression my_this;
660 public Expression This {
662 if (my_this == null) {
663 if (CurrentBlock != null)
664 my_this = new This (CurrentBlock, loc);
666 my_this = new This (loc);
668 my_this = my_this.Resolve (this);