2004-02-14 Francisco Figueiredo Jr. <fxjrlists@yahoo.com.br>
[mono.git] / mcs / gmcs / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9
10 using System;
11 using System.IO;
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15
16 namespace Mono.CSharp {
17
18         /// <summary>
19         ///    Code generator class.
20         /// </summary>
21         public class CodeGen {
22                 static AppDomain current_domain;
23                 public static AssemblyBuilder AssemblyBuilder;
24                 public static ModuleBuilder   ModuleBuilder;
25
26                 static public SymbolWriter SymbolWriter;
27
28                 public static string Basename (string name)
29                 {
30                         int pos = name.LastIndexOf ('/');
31
32                         if (pos != -1)
33                                 return name.Substring (pos + 1);
34
35                         pos = name.LastIndexOf ('\\');
36                         if (pos != -1)
37                                 return name.Substring (pos + 1);
38
39                         return name;
40                 }
41
42                 public static string Dirname (string name)
43                 {
44                         int pos = name.LastIndexOf ('/');
45
46                         if (pos != -1)
47                                 return name.Substring (0, pos);
48
49                         pos = name.LastIndexOf ('\\');
50                         if (pos != -1)
51                                 return name.Substring (0, pos);
52
53                         return ".";
54                 }
55
56                 static string TrimExt (string name)
57                 {
58                         int pos = name.LastIndexOf ('.');
59
60                         return name.Substring (0, pos);
61                 }
62
63                 static public string FileName;
64
65                 //
66                 // Initializes the symbol writer
67                 //
68                 static void InitializeSymbolWriter ()
69                 {
70                         SymbolWriter = SymbolWriter.GetSymbolWriter (ModuleBuilder);
71
72                         //
73                         // If we got an ISymbolWriter instance, initialize it.
74                         //
75                         if (SymbolWriter == null) {
76                                 Report.Warning (
77                                         -18, "Could not find the symbol writer assembly (Mono.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger directory.");
78                                 return;
79                         }
80                 }
81
82                 //
83                 // Initializes the code generator variables
84                 //
85                 static public void Init (string name, string output, bool want_debugging_support)
86                 {
87                         AssemblyName an;
88
89                         FileName = output;
90                         an = new AssemblyName ();
91                         an.Name = Path.GetFileNameWithoutExtension (name);
92                         
93                         current_domain = AppDomain.CurrentDomain;
94                         AssemblyBuilder = current_domain.DefineDynamicAssembly (
95                                 an, AssemblyBuilderAccess.Save, Dirname (name));
96
97                         //
98                         // Pass a path-less name to DefineDynamicModule.  Wonder how
99                         // this copes with output in different directories then.
100                         // FIXME: figure out how this copes with --output /tmp/blah
101                         //
102                         // If the third argument is true, the ModuleBuilder will dynamically
103                         // load the default symbol writer.
104                         //
105                         ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
106                                 Basename (name), Basename (output), want_debugging_support);
107
108                         if (want_debugging_support)
109                                 InitializeSymbolWriter ();
110                 }
111
112                 static public void Save (string name)
113                 {
114                         try {
115                                 AssemblyBuilder.Save (Basename (name));
116                         } catch (System.IO.IOException io){
117                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
118                         }
119                 }
120         }
121
122         //
123         // Provides "local" store across code that can yield: locals
124         // or fields, notice that this should not be used by anonymous
125         // methods to create local storage, those only require
126         // variable mapping.
127         //
128         public class VariableStorage {
129                 ILGenerator ig;
130                 FieldBuilder fb;
131                 LocalBuilder local;
132                 
133                 static int count;
134                 
135                 public VariableStorage (EmitContext ec, Type t)
136                 {
137                         count++;
138                         if (ec.InIterator)
139                                 fb = IteratorHandler.Current.MapVariable ("s_", count.ToString (), t);
140                         else
141                                 local = ec.ig.DeclareLocal (t);
142                         ig = ec.ig;
143                 }
144
145                 public void EmitThis ()
146                 {
147                         if (fb != null)
148                                 ig.Emit (OpCodes.Ldarg_0);
149                 }
150
151                 public void EmitStore ()
152                 {
153                         if (fb == null)
154                                 ig.Emit (OpCodes.Stloc, local);
155                         else
156                                 ig.Emit (OpCodes.Stfld, fb);
157                 }
158
159                 public void EmitLoad ()
160                 {
161                         if (fb == null)
162                                 ig.Emit (OpCodes.Ldloc, local);
163                         else 
164                                 ig.Emit (OpCodes.Ldfld, fb);
165                 }
166         }
167         
168         /// <summary>
169         ///   An Emit Context is created for each body of code (from methods,
170         ///   properties bodies, indexer bodies or constructor bodies)
171         /// </summary>
172         public class EmitContext {
173                 public DeclSpace DeclSpace;
174                 public DeclSpace TypeContainer;
175                 public ILGenerator   ig;
176
177                 /// <summary>
178                 ///   This variable tracks the `checked' state of the compilation,
179                 ///   it controls whether we should generate code that does overflow
180                 ///   checking, or if we generate code that ignores overflows.
181                 ///
182                 ///   The default setting comes from the command line option to generate
183                 ///   checked or unchecked code plus any source code changes using the
184                 ///   checked/unchecked statements or expressions.   Contrast this with
185                 ///   the ConstantCheckState flag.
186                 /// </summary>
187                 
188                 public bool CheckState;
189
190                 /// <summary>
191                 ///   The constant check state is always set to `true' and cant be changed
192                 ///   from the command line.  The source code can change this setting with
193                 ///   the `checked' and `unchecked' statements and expressions. 
194                 /// </summary>
195                 public bool ConstantCheckState;
196
197                 /// <summary>
198                 ///   Whether we are emitting code inside a static or instance method
199                 /// </summary>
200                 public bool IsStatic;
201
202                 /// <summary>
203                 ///   Whether we are emitting a field initializer
204                 /// </summary>
205                 public bool IsFieldInitializer;
206
207                 /// <summary>
208                 ///   The value that is allowed to be returned or NULL if there is no
209                 ///   return type.
210                 /// </summary>
211                 public Type ReturnType;
212
213                 /// <summary>
214                 ///   Points to the Type (extracted from the TypeContainer) that
215                 ///   declares this body of code
216                 /// </summary>
217                 public Type ContainerType;
218                 
219                 /// <summary>
220                 ///   Whether this is generating code for a constructor
221                 /// </summary>
222                 public bool IsConstructor;
223
224                 /// <summary>
225                 ///   Whether we're control flow analysis enabled
226                 /// </summary>
227                 public bool DoFlowAnalysis;
228                 
229                 /// <summary>
230                 ///   Keeps track of the Type to LocalBuilder temporary storage created
231                 ///   to store structures (used to compute the address of the structure
232                 ///   value on structure method invocations)
233                 /// </summary>
234                 public Hashtable temporary_storage;
235
236                 public Block CurrentBlock;
237
238                 public int CurrentFile;
239
240                 /// <summary>
241                 ///   The location where we store the return value.
242                 /// </summary>
243                 LocalBuilder return_value;
244
245                 /// <summary>
246                 ///   The location where return has to jump to return the
247                 ///   value
248                 /// </summary>
249                 public Label ReturnLabel;
250
251                 /// <summary>
252                 ///   If we already defined the ReturnLabel
253                 /// </summary>
254                 public bool HasReturnLabel;
255
256                 /// <summary>
257                 ///   Whether we are inside an iterator block.
258                 /// </summary>
259                 public bool InIterator;
260
261                 public bool IsLastStatement;
262                 
263                 /// <summary>
264                 ///   Whether remapping of locals, parameters and fields is turned on.
265                 ///   Used by iterators and anonymous methods.
266                 /// </summary>
267                 public bool RemapToProxy;
268
269                 /// <summary>
270                 ///  Whether we are inside an unsafe block
271                 /// </summary>
272                 public bool InUnsafe;
273
274                 /// <summary>
275                 ///  Whether we are in a `fixed' initialization
276                 /// </summary>
277                 public bool InFixedInitializer;
278
279                 /// <summary>
280                 ///  Whether we are inside an anonymous method.
281                 /// </summary>
282                 public bool InAnonymousMethod;
283                 
284                 /// <summary>
285                 ///   Location for this EmitContext
286                 /// </summary>
287                 public Location loc;
288
289                 /// <summary>
290                 ///   Used to flag that it is ok to define types recursively, as the
291                 ///   expressions are being evaluated as part of the type lookup
292                 ///   during the type resolution process
293                 /// </summary>
294                 public bool ResolvingTypeTree;
295                 
296                 /// <summary>
297                 ///   Inside an enum definition, we do not resolve enumeration values
298                 ///   to their enumerations, but rather to the underlying type/value
299                 ///   This is so EnumVal + EnumValB can be evaluated.
300                 ///
301                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
302                 ///   we relax the rules
303                 /// </summary>
304                 public bool InEnumContext;
305
306                 FlowBranching current_flow_branching;
307                 
308                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
309                                     Type return_type, int code_flags, bool is_constructor)
310                 {
311                         this.ig = ig;
312
313                         TypeContainer = parent;
314                         DeclSpace = ds;
315                         CheckState = RootContext.Checked;
316                         ConstantCheckState = true;
317                         
318                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
319                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
320                         RemapToProxy = InIterator;
321                         ReturnType = return_type;
322                         IsConstructor = is_constructor;
323                         CurrentBlock = null;
324                         CurrentFile = 0;
325                         
326                         if (parent != null){
327                                 // Can only be null for the ResolveType contexts.
328                                 ContainerType = parent.TypeBuilder;
329                                 if (parent.UnsafeContext)
330                                         InUnsafe = true;
331                                 else
332                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
333                         }
334                         loc = l;
335
336                         if (ReturnType == TypeManager.void_type)
337                                 ReturnType = null;
338                 }
339
340                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
341                                     Type return_type, int code_flags, bool is_constructor)
342                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
343                 {
344                 }
345
346                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
347                                     Type return_type, int code_flags)
348                         : this (tc, tc, l, ig, return_type, code_flags, false)
349                 {
350                 }
351
352                 public FlowBranching CurrentBranching {
353                         get {
354                                 return current_flow_branching;
355                         }
356                 }
357
358                 // <summary>
359                 //   Starts a new code branching.  This inherits the state of all local
360                 //   variables and parameters from the current branching.
361                 // </summary>
362                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
363                 {
364                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
365                         return current_flow_branching;
366                 }
367
368                 // <summary>
369                 //   Starts a new code branching for block `block'.
370                 // </summary>
371                 public FlowBranching StartFlowBranching (Block block)
372                 {
373                         FlowBranching.BranchingType type;
374
375                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
376                                 type = FlowBranching.BranchingType.SwitchSection;
377                         else
378                                 type = FlowBranching.BranchingType.Block;
379
380                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
381                         return current_flow_branching;
382                 }
383
384                 // <summary>
385                 //   Ends a code branching.  Merges the state of locals and parameters
386                 //   from all the children of the ending branching.
387                 // </summary>
388                 public FlowBranching.UsageVector DoEndFlowBranching ()
389                 {
390                         FlowBranching old = current_flow_branching;
391                         current_flow_branching = current_flow_branching.Parent;
392
393                         return current_flow_branching.MergeChild (old);
394                 }
395
396                 // <summary>
397                 //   Ends a code branching.  Merges the state of locals and parameters
398                 //   from all the children of the ending branching.
399                 // </summary>
400                 public FlowBranching.Reachability EndFlowBranching ()
401                 {
402                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
403
404                         return vector.Reachability;
405                 }
406
407                 // <summary>
408                 //   Kills the current code branching.  This throws away any changed state
409                 //   information and should only be used in case of an error.
410                 // </summary>
411                 public void KillFlowBranching ()
412                 {
413                         current_flow_branching = current_flow_branching.Parent;
414                 }
415
416                 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
417                 {
418                         bool unreachable = false;
419
420                         if (!Location.IsNull (loc))
421                                 CurrentFile = loc.File;
422
423                         if (block != null){
424                             try {
425                                 int errors = Report.Errors;
426
427                                 block.EmitMeta (this, ip);
428
429                                 if (Report.Errors == errors){
430                                         bool old_do_flow_analysis = DoFlowAnalysis;
431                                         DoFlowAnalysis = true;
432
433                                         current_flow_branching = FlowBranching.CreateBranching (
434                                                 null, FlowBranching.BranchingType.Block, block, loc);
435
436                                         if (!block.Resolve (this)) {
437                                                 current_flow_branching = null;
438                                                 DoFlowAnalysis = old_do_flow_analysis;
439                                                 return;
440                                         }
441
442                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
443                                         current_flow_branching = null;
444
445                                         DoFlowAnalysis = old_do_flow_analysis;
446
447                                         block.Emit (this);
448
449                                         if (reachability.AlwaysReturns ||
450                                             reachability.AlwaysThrows ||
451                                             reachability.IsUnreachable)
452                                                 unreachable = true;
453                                         }
454                             } catch (Exception e) {
455                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
456                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
457                                         
458                                         if (CurrentBlock != null){
459                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
460                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
461                                         }
462                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
463                                         Console.WriteLine (Report.FriendlyStackTrace (e));
464                                         
465                                         Environment.Exit (1);
466                             }
467                         }
468
469                         if (ReturnType != null && !unreachable){
470                                 if (!InIterator){
471                                         Report.Error (161, loc, "Not all code paths return a value");
472                                         return;
473                                 }
474                         }
475
476                         if (HasReturnLabel)
477                                 ig.MarkLabel (ReturnLabel);
478                         if (return_value != null){
479                                 ig.Emit (OpCodes.Ldloc, return_value);
480                                 ig.Emit (OpCodes.Ret);
481                         } else {
482                                 //
483                                 // If `HasReturnLabel' is set, then we already emitted a
484                                 // jump to the end of the method, so we must emit a `ret'
485                                 // there.
486                                 //
487                                 // Unfortunately, System.Reflection.Emit automatically emits
488                                 // a leave to the end of a finally block.  This is a problem
489                                 // if no code is following the try/finally block since we may
490                                 // jump to a point after the end of the method.
491                                 // As a workaround, we're always creating a return label in
492                                 // this case.
493                                 //
494
495                                 if ((block != null) && block.IsDestructor) {
496                                         // Nothing to do; S.R.E automatically emits a leave.
497                                 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
498                                         if (ReturnType != null)
499                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
500                                         ig.Emit (OpCodes.Ret);
501                                 }
502                         }
503                 }
504
505                 /// <summary>
506                 ///   This is called immediately before emitting an IL opcode to tell the symbol
507                 ///   writer to which source line this opcode belongs.
508                 /// </summary>
509                 public void Mark (Location loc, bool check_file)
510                 {
511                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
512                                 return;
513
514                         if (check_file && (CurrentFile != loc.File))
515                                 return;
516
517                         ig.MarkSequencePoint (null, loc.Row, 0, 0, 0);
518                 }
519
520                 /// <summary>
521                 ///   Returns a temporary storage for a variable of type t as 
522                 ///   a local variable in the current body.
523                 /// </summary>
524                 public LocalBuilder GetTemporaryLocal (Type t)
525                 {
526                         LocalBuilder location = null;
527                         
528                         if (temporary_storage != null){
529                                 object o = temporary_storage [t];
530                                 if (o != null){
531                                         if (o is ArrayList){
532                                                 ArrayList al = (ArrayList) o;
533                                                 
534                                                 for (int i = 0; i < al.Count; i++){
535                                                         if (al [i] != null){
536                                                                 location = (LocalBuilder) al [i];
537                                                                 al [i] = null;
538                                                                 break;
539                                                         }
540                                                 }
541                                         } else
542                                                 location = (LocalBuilder) o;
543                                         if (location != null)
544                                                 return location;
545                                 }
546                         }
547                         
548                         return ig.DeclareLocal (t);
549                 }
550
551                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
552                 {
553                         if (temporary_storage == null){
554                                 temporary_storage = new Hashtable ();
555                                 temporary_storage [t] = b;
556                                 return;
557                         }
558                         object o = temporary_storage [t];
559                         if (o == null){
560                                 temporary_storage [t] = b;
561                                 return;
562                         }
563                         if (o is ArrayList){
564                                 ArrayList al = (ArrayList) o;
565                                 for (int i = 0; i < al.Count; i++){
566                                         if (al [i] == null){
567                                                 al [i] = b;
568                                                 return;
569                                         }
570                                 }
571                                 al.Add (b);
572                                 return;
573                         }
574                         ArrayList replacement = new ArrayList ();
575                         replacement.Add (o);
576                         temporary_storage.Remove (t);
577                         temporary_storage [t] = replacement;
578                 }
579
580                 /// <summary>
581                 ///   Current loop begin and end labels.
582                 /// </summary>
583                 public Label LoopBegin, LoopEnd;
584
585                 /// <summary>
586                 ///   Default target in a switch statement.   Only valid if
587                 ///   InSwitch is true
588                 /// </summary>
589                 public Label DefaultTarget;
590
591                 /// <summary>
592                 ///   If this is non-null, points to the current switch statement
593                 /// </summary>
594                 public Switch Switch;
595
596                 /// <summary>
597                 ///   ReturnValue creates on demand the LocalBuilder for the
598                 ///   return value from the function.  By default this is not
599                 ///   used.  This is only required when returns are found inside
600                 ///   Try or Catch statements.
601                 /// </summary>
602                 public LocalBuilder TemporaryReturn ()
603                 {
604                         if (return_value == null){
605                                 return_value = ig.DeclareLocal (ReturnType);
606                                 ReturnLabel = ig.DefineLabel ();
607                                 HasReturnLabel = true;
608                         }
609
610                         return return_value;
611                 }
612
613                 public void NeedReturnLabel ()
614                 {
615                         if (!HasReturnLabel) {
616                                 ReturnLabel = ig.DefineLabel ();
617                                 HasReturnLabel = true;
618                         }
619                 }
620
621                 //
622                 // Creates a field `name' with the type `t' on the proxy class
623                 //
624                 public FieldBuilder MapVariable (string name, Type t)
625                 {
626                         if (InIterator){
627                                 return IteratorHandler.Current.MapVariable ("v_", name, t);
628                         }
629
630                         throw new Exception ("MapVariable for an unknown state");
631                 }
632
633                 //
634                 // Invoke this routine to remap a VariableInfo into the
635                 // proper MemberAccess expression
636                 //
637                 public Expression RemapLocal (LocalInfo local_info)
638                 {
639                         FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
640                         fe.InstanceExpression = new ProxyInstance ();
641                         return fe.DoResolve (this);
642                 }
643
644                 public Expression RemapLocalLValue (LocalInfo local_info, Expression right_side)
645                 {
646                         FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
647                         fe.InstanceExpression = new ProxyInstance ();
648                         return fe.DoResolveLValue (this, right_side);
649                 }
650
651                 public Expression RemapParameter (int idx)
652                 {
653                         FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
654                         fe.InstanceExpression = new ProxyInstance ();
655                         return fe.DoResolve (this);
656                 }
657
658                 public Expression RemapParameterLValue (int idx, Expression right_side)
659                 {
660                         FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
661                         fe.InstanceExpression = new ProxyInstance ();
662                         return fe.DoResolveLValue (this, right_side);
663                 }
664                 
665                 //
666                 // Emits the proper object to address fields on a remapped
667                 // variable/parameter to field in anonymous-method/iterator proxy classes.
668                 //
669                 public void EmitThis ()
670                 {
671                         ig.Emit (OpCodes.Ldarg_0);
672
673                         if (!IsStatic){
674                                 if (InIterator)
675                                         ig.Emit (OpCodes.Ldfld, IteratorHandler.Current.this_field);
676                                 else
677                                         throw new Exception ("EmitThis for an unknown state");
678                         }
679                 }
680
681                 public Expression GetThis (Location loc)
682                 {
683                         This my_this;
684                         if (CurrentBlock != null)
685                                 my_this = new This (CurrentBlock, loc);
686                         else
687                                 my_this = new This (loc);
688
689                         if (!my_this.ResolveBase (this))
690                                 my_this = null;
691
692                         return my_this;
693                 }
694         }
695 }