2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 using System.Collections;
12 using System.Reflection;
13 using System.Reflection.Emit;
14 using System.Diagnostics.SymbolStore;
16 namespace Mono.CSharp {
19 /// Code generator class.
21 public class CodeGen {
22 static AppDomain current_domain;
23 public static AssemblyBuilder AssemblyBuilder;
24 public static ModuleBuilder ModuleBuilder;
26 static public ISymbolWriter SymbolWriter;
28 public static string Basename (string name)
30 int pos = name.LastIndexOf ("/");
33 return name.Substring (pos + 1);
35 pos = name.LastIndexOf ("\\");
37 return name.Substring (pos + 1);
42 public static string Dirname (string name)
44 int pos = name.LastIndexOf ("/");
47 return name.Substring (0, pos);
49 pos = name.LastIndexOf ("\\");
51 return name.Substring (0, pos);
56 static string TrimExt (string name)
58 int pos = name.LastIndexOf (".");
60 return name.Substring (0, pos);
63 static public string FileName;
66 // This routine initializes the Mono runtime SymbolWriter.
68 static void InitMonoSymbolWriter (string basename, string[] debug_args)
70 string symbol_output = basename + "-debug.s";
72 Type itype = SymbolWriter.GetType ();
76 Type[] arg_types = new Type [2];
77 arg_types [0] = typeof (string);
78 arg_types [1] = typeof (string[]);
80 MethodInfo initialize = itype.GetMethod ("Initialize", arg_types);
81 if (initialize == null)
84 object[] args = new object [2];
85 args [0] = symbol_output;
86 args [1] = debug_args;
88 initialize.Invoke (SymbolWriter, args);
92 // Initializes the symbol writer
94 static void InitializeSymbolWriter (string basename, string[] args)
96 SymbolWriter = ModuleBuilder.GetSymWriter ();
99 // If we got an ISymbolWriter instance, initialize it.
101 if (SymbolWriter == null)
105 // Due to lacking documentation about the first argument of the
106 // Initialize method, we cannot use Microsoft's default symbol
109 // If we're using the mono symbol writer, the SymbolWriter object
110 // is of type MonoSymbolWriter - but that's defined in a dynamically
111 // loaded DLL - that's why we're doing a comparision based on the type
112 // name here instead of using `SymbolWriter is MonoSymbolWriter'.
114 Type sym_type = ((object) SymbolWriter).GetType ();
116 switch (sym_type.Name){
117 case "MonoSymbolWriter":
118 InitMonoSymbolWriter (basename, args);
123 -18, "Cannot generate debugging information on this platform");
129 // Initializes the code generator variables
131 static public void Init (string name, string output, bool want_debugging_support,
137 an = new AssemblyName ();
138 an.Name = TrimExt (Basename (name));
139 current_domain = AppDomain.CurrentDomain;
140 AssemblyBuilder = current_domain.DefineDynamicAssembly (
141 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
144 // Pass a path-less name to DefineDynamicModule. Wonder how
145 // this copes with output in different directories then.
146 // FIXME: figure out how this copes with --output /tmp/blah
148 // If the third argument is true, the ModuleBuilder will dynamically
149 // load the default symbol writer.
151 ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
152 Basename (name), Basename (output), want_debugging_support);
154 if (want_debugging_support)
155 InitializeSymbolWriter (an.Name, debug_args);
158 static public void Save (string name)
161 AssemblyBuilder.Save (Basename (name));
162 } catch (System.IO.IOException io){
163 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
167 static public void SaveSymbols ()
169 if (SymbolWriter != null) {
170 // If we have a symbol writer, call its Close() method to write
171 // the symbol file to disk.
173 // When using Mono's default symbol writer, the Close() method must
174 // be called after the assembly has already been written to disk since
175 // it opens the assembly and reads its metadata.
176 SymbolWriter.Close ();
182 /// An Emit Context is created for each body of code (from methods,
183 /// properties bodies, indexer bodies or constructor bodies)
185 public class EmitContext {
186 public DeclSpace DeclSpace;
187 public TypeContainer TypeContainer;
188 public ILGenerator ig;
191 /// This variable tracks the `checked' state of the compilation,
192 /// it controls whether we should generate code that does overflow
193 /// checking, or if we generate code that ignores overflows.
195 /// The default setting comes from the command line option to generate
196 /// checked or unchecked code plus any source code changes using the
197 /// checked/unchecked statements or expressions. Contrast this with
198 /// the ConstantCheckState flag.
201 public bool CheckState;
204 /// The constant check state is always set to `true' and cant be changed
205 /// from the command line. The source code can change this setting with
206 /// the `checked' and `unchecked' statements and expressions.
208 public bool ConstantCheckState;
211 /// Whether we are emitting code inside a static or instance method
213 public bool IsStatic;
216 /// The value that is allowed to be returned or NULL if there is no
219 public Type ReturnType;
222 /// Points to the Type (extracted from the TypeContainer) that
223 /// declares this body of code
225 public Type ContainerType;
228 /// Whether this is generating code for a constructor
230 public bool IsConstructor;
233 /// Whether we're control flow analysis enabled
235 public bool DoFlowAnalysis;
238 /// Keeps track of the Type to LocalBuilder temporary storage created
239 /// to store structures (used to compute the address of the structure
240 /// value on structure method invocations)
242 public Hashtable temporary_storage;
244 public Block CurrentBlock;
247 /// The location where we store the return value.
249 LocalBuilder return_value;
252 /// The location where return has to jump to return the
255 public Label ReturnLabel;
258 /// If we already defined the ReturnLabel
260 public bool HasReturnLabel;
263 /// Whether we are in a Finally block
265 public bool InFinally;
268 /// Whether we are in a Try block
273 /// Whether we are in a Catch block
278 /// Whether we are inside an unsafe block
280 public bool InUnsafe;
283 /// Whether we break from a loop or not
288 /// Location for this EmitContext
293 /// Used to "flag" the resolution process to only lookup types,
294 /// and nothing else. This is an out-of-band communication
295 /// path to SimpleName from the cast operation.
297 public bool OnlyLookupTypes;
300 /// Used to flag that it is ok to define types recursively, as the
301 /// expressions are being evaluated as part of the type lookup
302 /// during the type resolution process
304 public bool ResolvingTypeTree;
307 /// Inside an enum definition, we do not resolve enumeration values
308 /// to their enumerations, but rather to the underlying type/value
309 /// This is so EnumVal + EnumValB can be evaluated.
311 /// There is no "E operator + (E x, E y)", so during an enum evaluation
312 /// we relax the rules
314 public bool InEnumContext;
316 protected Stack FlowStack;
318 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
319 Type return_type, int code_flags, bool is_constructor)
323 TypeContainer = parent;
325 CheckState = RootContext.Checked;
326 ConstantCheckState = true;
328 IsStatic = (code_flags & Modifiers.STATIC) != 0;
329 ReturnType = return_type;
330 IsConstructor = is_constructor;
334 // Can only be null for the ResolveType contexts.
335 ContainerType = parent.TypeBuilder;
336 InUnsafe = ((parent.ModFlags | code_flags) & Modifiers.UNSAFE) != 0;
338 OnlyLookupTypes = false;
341 FlowStack = new Stack ();
343 if (ReturnType == TypeManager.void_type)
347 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
348 Type return_type, int code_flags, bool is_constructor)
349 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
353 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
354 Type return_type, int code_flags)
355 : this (tc, tc, l, ig, return_type, code_flags, false)
359 public FlowBranching CurrentBranching {
361 return (FlowBranching) FlowStack.Peek ();
366 // Starts a new code branching. This inherits the state of all local
367 // variables and parameters from the current branching.
369 public FlowBranching StartFlowBranching (FlowBranchingType type, Location loc)
371 FlowBranching cfb = new FlowBranching (CurrentBranching, type, null, loc);
373 FlowStack.Push (cfb);
379 // Starts a new code branching for block `block'.
381 public FlowBranching StartFlowBranching (Block block)
384 FlowBranchingType type;
386 if (CurrentBranching.Type == FlowBranchingType.SWITCH)
387 type = FlowBranchingType.SWITCH_SECTION;
389 type = FlowBranchingType.BLOCK;
391 cfb = new FlowBranching (CurrentBranching, type, block, block.StartLocation);
393 FlowStack.Push (cfb);
399 // Ends a code branching. Merges the state of locals and parameters
400 // from all the children of the ending branching.
402 public FlowReturns EndFlowBranching ()
404 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
406 return CurrentBranching.MergeChild (cfb);
410 // Kills the current code branching. This throws away any changed state
411 // information and should only be used in case of an error.
413 public void KillFlowBranching ()
415 FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
419 // Checks whether the local variable `vi' is already initialized
420 // at the current point of the method's control flow.
421 // If this method returns false, the caller must report an
424 public bool IsVariableAssigned (VariableInfo vi)
427 return CurrentBranching.IsVariableAssigned (vi);
433 // Marks the local variable `vi' as being initialized at the current
434 // current point of the method's control flow.
436 public void SetVariableAssigned (VariableInfo vi)
439 CurrentBranching.SetVariableAssigned (vi);
443 // Checks whether the parameter `number' is already initialized
444 // at the current point of the method's control flow.
445 // If this method returns false, the caller must report an
446 // error 165. This is only necessary for `out' parameters and the
447 // call will always succeed for non-`out' parameters.
449 public bool IsParameterAssigned (int number)
452 return CurrentBranching.IsParameterAssigned (number);
458 // Marks the parameter `number' as being initialized at the current
459 // current point of the method's control flow. This is only necessary
460 // for `out' parameters.
462 public void SetParameterAssigned (int number)
465 CurrentBranching.SetParameterAssigned (number);
468 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
470 bool has_ret = false;
472 // Console.WriteLine ("Emitting: " + loc);
474 if (CodeGen.SymbolWriter != null)
478 int errors = Report.Errors;
480 block.EmitMeta (this, block);
482 if (Report.Errors == errors){
483 bool old_do_flow_analysis = DoFlowAnalysis;
484 DoFlowAnalysis = true;
486 FlowBranching cfb = new FlowBranching (block, ip, loc);
487 FlowStack.Push (cfb);
489 if (!block.Resolve (this)) {
491 DoFlowAnalysis = old_do_flow_analysis;
495 cfb = (FlowBranching) FlowStack.Pop ();
496 cfb.MergeTopBlock ();
498 DoFlowAnalysis = old_do_flow_analysis;
500 has_ret = block.Emit (this);
502 if (Report.Errors == errors){
503 if (RootContext.WarningLevel >= 3)
504 block.UsageWarning ();
509 if (ReturnType != null && !has_ret){
511 // FIXME: we need full flow analysis to implement this
512 // correctly and emit an error instead of a warning.
515 Report.Error (161, loc, "Not all code paths return a value");
520 ig.MarkLabel (ReturnLabel);
521 if (return_value != null){
522 ig.Emit (OpCodes.Ldloc, return_value);
523 ig.Emit (OpCodes.Ret);
526 if (!has_ret || HasReturnLabel)
527 ig.Emit (OpCodes.Ret);
533 /// This is called immediately before emitting an IL opcode to tell the symbol
534 /// writer to which source line this opcode belongs.
536 public void Mark (Location loc)
538 if (!Location.IsNull (loc)) {
539 ISymbolDocumentWriter doc = loc.SymbolDocument;
542 ig.MarkSequencePoint (doc, loc.Row, 0, loc.Row, 0);
547 /// Returns a temporary storage for a variable of type t as
548 /// a local variable in the current body.
550 public LocalBuilder GetTemporaryStorage (Type t)
552 LocalBuilder location;
554 if (temporary_storage != null){
555 location = (LocalBuilder) temporary_storage [t];
556 if (location != null)
560 location = ig.DeclareLocal (t);
565 public void FreeTemporaryStorage (LocalBuilder b)
571 /// Current loop begin and end labels.
573 public Label LoopBegin, LoopEnd;
576 /// Whether we are inside a loop and break/continue are possible.
581 /// This is incremented each time we enter a try/catch block and
582 /// decremented if we leave it.
584 public int TryCatchLevel;
587 /// The TryCatchLevel at the begin of the current loop.
589 public int LoopBeginTryCatchLevel;
592 /// Default target in a switch statement. Only valid if
595 public Label DefaultTarget;
598 /// If this is non-null, points to the current switch statement
600 public Switch Switch;
603 /// ReturnValue creates on demand the LocalBuilder for the
604 /// return value from the function. By default this is not
605 /// used. This is only required when returns are found inside
606 /// Try or Catch statements.
608 public LocalBuilder TemporaryReturn ()
610 if (return_value == null){
611 return_value = ig.DeclareLocal (ReturnType);
612 ReturnLabel = ig.DefineLabel ();
613 HasReturnLabel = true;
620 /// A dynamic This that is shared by all variables in a emitcontext.
621 /// Created on demand.
623 public Expression my_this;
624 public Expression This {
627 my_this = new This (loc).Resolve (this);