2003-11-16 Martin Baulig <martin@ximian.com>
[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.RunAndSave, 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 in a Finally block
258                 /// </summary>
259                 public bool InFinally;
260
261                 /// <summary>
262                 ///   Whether we are in a Try block
263                 /// </summary>
264                 public bool InTry;
265
266                 /// <summary>
267                 ///   Whether we are inside an iterator block.
268                 /// </summary>
269                 public bool InIterator;
270
271                 /// <summary>
272                 ///   Whether we need an explicit return statement at the end of the method.
273                 /// </summary>
274                 public bool NeedExplicitReturn;
275                 
276                 /// <summary>
277                 ///   Whether remapping of locals, parameters and fields is turned on.
278                 ///   Used by iterators and anonymous methods.
279                 /// </summary>
280                 public bool RemapToProxy;
281
282                 /// <summary>
283                 ///   Whether we are in a Catch block
284                 /// </summary>
285                 public bool InCatch;
286
287                 /// <summary>
288                 ///  Whether we are inside an unsafe block
289                 /// </summary>
290                 public bool InUnsafe;
291
292                 /// <summary>
293                 ///  Whether we are in a `fixed' initialization
294                 /// </summary>
295                 public bool InFixedInitializer;
296
297                 /// <summary>
298                 ///  Whether we are inside an anonymous method.
299                 /// </summary>
300                 public bool InAnonymousMethod;
301                 
302                 /// <summary>
303                 ///   Location for this EmitContext
304                 /// </summary>
305                 public Location loc;
306
307                 /// <summary>
308                 ///   Used to flag that it is ok to define types recursively, as the
309                 ///   expressions are being evaluated as part of the type lookup
310                 ///   during the type resolution process
311                 /// </summary>
312                 public bool ResolvingTypeTree;
313                 
314                 /// <summary>
315                 ///   Inside an enum definition, we do not resolve enumeration values
316                 ///   to their enumerations, but rather to the underlying type/value
317                 ///   This is so EnumVal + EnumValB can be evaluated.
318                 ///
319                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
320                 ///   we relax the rules
321                 /// </summary>
322                 public bool InEnumContext;
323
324                 protected Stack FlowStack;
325                 
326                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
327                                     Type return_type, int code_flags, bool is_constructor)
328                 {
329                         this.ig = ig;
330
331                         TypeContainer = parent;
332                         DeclSpace = ds;
333                         CheckState = RootContext.Checked;
334                         ConstantCheckState = true;
335                         
336                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
337                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
338                         RemapToProxy = InIterator;
339                         ReturnType = return_type;
340                         IsConstructor = is_constructor;
341                         CurrentBlock = null;
342                         CurrentFile = 0;
343                         
344                         if (parent != null){
345                                 // Can only be null for the ResolveType contexts.
346                                 ContainerType = parent.TypeBuilder;
347                                 if (parent.UnsafeContext)
348                                         InUnsafe = true;
349                                 else
350                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
351                         }
352                         loc = l;
353
354                         FlowStack = new Stack ();
355                         
356                         if (ReturnType == TypeManager.void_type)
357                                 ReturnType = null;
358                 }
359
360                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
361                                     Type return_type, int code_flags, bool is_constructor)
362                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
363                 {
364                 }
365
366                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
367                                     Type return_type, int code_flags)
368                         : this (tc, tc, l, ig, return_type, code_flags, false)
369                 {
370                 }
371
372                 public FlowBranching CurrentBranching {
373                         get {
374                                 return (FlowBranching) FlowStack.Peek ();
375                         }
376                 }
377
378                 // <summary>
379                 //   Starts a new code branching.  This inherits the state of all local
380                 //   variables and parameters from the current branching.
381                 // </summary>
382                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
383                 {
384                         FlowBranching cfb = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
385
386                         FlowStack.Push (cfb);
387
388                         return cfb;
389                 }
390
391                 // <summary>
392                 //   Starts a new code branching for block `block'.
393                 // </summary>
394                 public FlowBranching StartFlowBranching (Block block)
395                 {
396                         FlowBranching cfb;
397                         FlowBranching.BranchingType type;
398
399                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
400                                 type = FlowBranching.BranchingType.SwitchSection;
401                         else
402                                 type = FlowBranching.BranchingType.Block;
403
404                         cfb = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
405
406                         FlowStack.Push (cfb);
407
408                         return cfb;
409                 }
410
411                 // <summary>
412                 //   Ends a code branching.  Merges the state of locals and parameters
413                 //   from all the children of the ending branching.
414                 // </summary>
415                 public FlowBranching.FlowReturns EndFlowBranching ()
416                 {
417                         FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
418
419                         return CurrentBranching.MergeChild (cfb);
420                 }
421
422                 // <summary>
423                 //   Kills the current code branching.  This throws away any changed state
424                 //   information and should only be used in case of an error.
425                 // </summary>
426                 public void KillFlowBranching ()
427                 {
428                         FlowBranching cfb = (FlowBranching) FlowStack.Pop ();
429                 }
430
431                 public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
432                 {
433                         bool has_ret = false;
434
435                         if (!Location.IsNull (loc))
436                                 CurrentFile = loc.File;
437
438                         if (block != null){
439                             try {
440                                 int errors = Report.Errors;
441
442                                 block.EmitMeta (this, ip);
443
444                                 if (Report.Errors == errors){
445                                         bool old_do_flow_analysis = DoFlowAnalysis;
446                                         DoFlowAnalysis = true;
447
448                                         FlowBranching cfb = FlowBranching.CreateBranching (
449                                                 null, FlowBranching.BranchingType.Block, block, loc);
450                                         FlowStack.Push (cfb);
451
452                                         if (!block.Resolve (this)) {
453                                                 FlowStack.Pop ();
454                                                 DoFlowAnalysis = old_do_flow_analysis;
455                                                 return;
456                                         }
457
458                                         cfb = (FlowBranching) FlowStack.Pop ();
459                                         FlowBranching.FlowReturns returns = cfb.MergeTopBlock ();
460
461                                         DoFlowAnalysis = old_do_flow_analysis;
462
463                                         has_ret = block.Emit (this);
464
465                                         if ((returns == FlowBranching.FlowReturns.Always) ||
466                                             (returns == FlowBranching.FlowReturns.Exception) ||
467                                             (returns == FlowBranching.FlowReturns.Unreachable))
468                                                 has_ret = true;
469
470                                         if (Report.Errors == errors){
471                                                 if (RootContext.WarningLevel >= 3)
472                                                         block.UsageWarning ();
473                                         }
474                                 }
475                             } catch {
476                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
477                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
478                                         
479                                         if (CurrentBlock != null){
480                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
481                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
482                                         }
483                                         throw;
484                             }
485                         }
486
487                         if (ReturnType != null && !has_ret){
488                                 //
489                                 // FIXME: we need full flow analysis to implement this
490                                 // correctly and emit an error instead of a warning.
491                                 //
492                                 //
493                                 if (!InIterator){
494                                         Report.Error (161, loc, "Not all code paths return a value");
495                                         return;
496                                 }
497                         }
498
499                         if (HasReturnLabel)
500                                 ig.MarkLabel (ReturnLabel);
501                         if (return_value != null){
502                                 ig.Emit (OpCodes.Ldloc, return_value);
503                                 ig.Emit (OpCodes.Ret);
504                         } else {
505                                 if (!InTry){
506                                         if (InIterator)
507                                                 has_ret = true;
508                                         
509                                         if (!has_ret || HasReturnLabel) {
510                                                 ig.Emit (OpCodes.Ret);
511                                                 NeedExplicitReturn = false;
512                                         }
513                                 }
514
515                                 // Unfortunately, System.Reflection.Emit automatically emits a leave
516                                 // to the end of a finally block.  This is a problem if no code is
517                                 // following the try/finally block since we may jump to a point after
518                                 // the end of the method. As a workaround, emit an explicit ret here.
519
520                                 if (NeedExplicitReturn) {
521                                         if (ReturnType != null)
522                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
523                                         ig.Emit (OpCodes.Ret);
524                                 }
525                         }
526                 }
527
528                 /// <summary>
529                 ///   This is called immediately before emitting an IL opcode to tell the symbol
530                 ///   writer to which source line this opcode belongs.
531                 /// </summary>
532                 public void Mark (Location loc, bool check_file)
533                 {
534                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
535                                 return;
536
537                         if (check_file && (CurrentFile != loc.File))
538                                 return;
539
540                         ig.MarkSequencePoint (null, loc.Row, 0, 0, 0);
541                 }
542
543                 /// <summary>
544                 ///   Returns a temporary storage for a variable of type t as 
545                 ///   a local variable in the current body.
546                 /// </summary>
547                 public LocalBuilder GetTemporaryLocal (Type t)
548                 {
549                         LocalBuilder location = null;
550                         
551                         if (temporary_storage != null){
552                                 object o = temporary_storage [t];
553                                 if (o != null){
554                                         if (o is ArrayList){
555                                                 ArrayList al = (ArrayList) o;
556                                                 
557                                                 for (int i = 0; i < al.Count; i++){
558                                                         if (al [i] != null){
559                                                                 location = (LocalBuilder) al [i];
560                                                                 al [i] = null;
561                                                                 break;
562                                                         }
563                                                 }
564                                         } else
565                                                 location = (LocalBuilder) o;
566                                         if (location != null)
567                                                 return location;
568                                 }
569                         }
570                         
571                         return ig.DeclareLocal (t);
572                 }
573
574                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
575                 {
576                         if (temporary_storage == null){
577                                 temporary_storage = new Hashtable ();
578                                 temporary_storage [t] = b;
579                                 return;
580                         }
581                         object o = temporary_storage [t];
582                         if (o == null){
583                                 temporary_storage [t] = b;
584                                 return;
585                         }
586                         if (o is ArrayList){
587                                 ArrayList al = (ArrayList) o;
588                                 for (int i = 0; i < al.Count; i++){
589                                         if (al [i] == null){
590                                                 al [i] = b;
591                                                 return;
592                                         }
593                                 }
594                                 al.Add (b);
595                                 return;
596                         }
597                         ArrayList replacement = new ArrayList ();
598                         replacement.Add (o);
599                         temporary_storage.Remove (t);
600                         temporary_storage [t] = replacement;
601                 }
602
603                 /// <summary>
604                 ///   Current loop begin and end labels.
605                 /// </summary>
606                 public Label LoopBegin, LoopEnd;
607
608                 /// <summary>
609                 ///   Whether we are inside a loop and break/continue are possible.
610                 /// </summary>
611                 public bool  InLoop;
612
613                 /// <summary>
614                 ///   This is incremented each time we enter a try/catch block and
615                 ///   decremented if we leave it.
616                 /// </summary>
617                 public int   TryCatchLevel;
618
619                 /// <summary>
620                 ///   The TryCatchLevel at the begin of the current loop.
621                 /// </summary>
622                 public int   LoopBeginTryCatchLevel;
623
624                 /// <summary>
625                 ///   Default target in a switch statement.   Only valid if
626                 ///   InSwitch is true
627                 /// </summary>
628                 public Label DefaultTarget;
629
630                 /// <summary>
631                 ///   If this is non-null, points to the current switch statement
632                 /// </summary>
633                 public Switch Switch;
634
635                 /// <summary>
636                 ///   ReturnValue creates on demand the LocalBuilder for the
637                 ///   return value from the function.  By default this is not
638                 ///   used.  This is only required when returns are found inside
639                 ///   Try or Catch statements.
640                 /// </summary>
641                 public LocalBuilder TemporaryReturn ()
642                 {
643                         if (return_value == null){
644                                 return_value = ig.DeclareLocal (ReturnType);
645                                 ReturnLabel = ig.DefineLabel ();
646                                 HasReturnLabel = true;
647                         }
648
649                         return return_value;
650                 }
651
652                 //
653                 // Creates a field `name' with the type `t' on the proxy class
654                 //
655                 public FieldBuilder MapVariable (string name, Type t)
656                 {
657                         if (InIterator){
658                                 return IteratorHandler.Current.MapVariable ("v_", name, t);
659                         }
660
661                         throw new Exception ("MapVariable for an unknown state");
662                 }
663
664                 //
665                 // Invoke this routine to remap a VariableInfo into the
666                 // proper MemberAccess expression
667                 //
668                 public Expression RemapLocal (LocalInfo local_info)
669                 {
670                         FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
671                         fe.InstanceExpression = new ProxyInstance ();
672                         return fe.DoResolve (this);
673                 }
674
675                 public Expression RemapLocalLValue (LocalInfo local_info, Expression right_side)
676                 {
677                         FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
678                         fe.InstanceExpression = new ProxyInstance ();
679                         return fe.DoResolveLValue (this, right_side);
680                 }
681
682                 public Expression RemapParameter (int idx)
683                 {
684                         FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
685                         fe.InstanceExpression = new ProxyInstance ();
686                         return fe.DoResolve (this);
687                 }
688
689                 public Expression RemapParameterLValue (int idx, Expression right_side)
690                 {
691                         FieldExpr fe = new FieldExprNoAddress (IteratorHandler.Current.parameter_fields [idx], loc);
692                         fe.InstanceExpression = new ProxyInstance ();
693                         return fe.DoResolveLValue (this, right_side);
694                 }
695                 
696                 //
697                 // Emits the proper object to address fields on a remapped
698                 // variable/parameter to field in anonymous-method/iterator proxy classes.
699                 //
700                 public void EmitThis ()
701                 {
702                         ig.Emit (OpCodes.Ldarg_0);
703
704                         if (!IsStatic){
705                                 if (InIterator)
706                                         ig.Emit (OpCodes.Ldfld, IteratorHandler.Current.this_field);
707                                 else
708                                         throw new Exception ("EmitThis for an unknown state");
709                         }
710                 }
711
712                 public Expression GetThis (Location loc)
713                 {
714                         This my_this;
715                         if (CurrentBlock != null)
716                                 my_this = new This (CurrentBlock, loc);
717                         else
718                                 my_this = new This (loc);
719
720                         if (!my_this.ResolveBase (this))
721                                 my_this = null;
722
723                         return my_this;
724                 }
725         }
726 }