- Fixed pointer type
[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, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10 //#define PRODUCTION
11 using System;
12 using System.IO;
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
21
22 using Mono.Security.Cryptography;
23
24 namespace Mono.CSharp {
25
26         /// <summary>
27         ///    Code generator class.
28         /// </summary>
29         public class CodeGen {
30                 static AppDomain current_domain;
31                 static public SymbolWriter SymbolWriter;
32
33                 public static AssemblyClass Assembly;
34                 public static ModuleClass Module;
35
36                 static CodeGen ()
37                 {
38                         Assembly = new AssemblyClass ();
39                         Module = new ModuleClass (RootContext.Unsafe);
40                 }
41
42                 public static string Basename (string name)
43                 {
44                         int pos = name.LastIndexOf ('/');
45
46                         if (pos != -1)
47                                 return name.Substring (pos + 1);
48
49                         pos = name.LastIndexOf ('\\');
50                         if (pos != -1)
51                                 return name.Substring (pos + 1);
52
53                         return name;
54                 }
55
56                 public static string Dirname (string name)
57                 {
58                         int pos = name.LastIndexOf ('/');
59
60                         if (pos != -1)
61                                 return name.Substring (0, pos);
62
63                         pos = name.LastIndexOf ('\\');
64                         if (pos != -1)
65                                 return name.Substring (0, pos);
66
67                         return ".";
68                 }
69
70                 static string TrimExt (string name)
71                 {
72                         int pos = name.LastIndexOf ('.');
73
74                         return name.Substring (0, pos);
75                 }
76
77                 static public string FileName;
78
79                 //
80                 // Initializes the symbol writer
81                 //
82                 static void InitializeSymbolWriter (string filename)
83                 {
84                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
85
86                         //
87                         // If we got an ISymbolWriter instance, initialize it.
88                         //
89                         if (SymbolWriter == null) {
90                                 Report.Warning (
91                                         -18, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
92                                 return;
93                         }
94                 }
95
96                 //
97                 // Initializes the code generator variables
98                 //
99                 static public void Init (string name, string output, bool want_debugging_support)
100                 {
101                         FileName = output;
102                         AssemblyName an = Assembly.GetAssemblyName (name, output);
103
104                         if (an.KeyPair != null) {
105                                 // If we are going to strong name our assembly make
106                                 // sure all its refs are strong named
107                                 foreach (Assembly a in TypeManager.GetAssemblies ()) {
108                                         AssemblyName ref_name = a.GetName ();
109                                         byte [] b = ref_name.GetPublicKeyToken ();
110                                         if (b == null || b.Length == 0) {
111                                                 Report.Warning (1577, "Assembly generation failed " +
112                                                                 "-- Referenced assembly '" +
113                                                                 ref_name.Name +
114                                                                 "' does not have a strong name.");
115                                                 //Environment.Exit (1);
116                                         }
117                                 }
118                         }
119                         
120                         current_domain = AppDomain.CurrentDomain;
121
122                         try {
123                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
124                                         AssemblyBuilderAccess.Save, Dirname (name));
125                         }
126                         catch (ArgumentException) {
127                                 // specified key may not be exportable outside it's container
128                                 if (RootContext.StrongNameKeyContainer != null) {
129                                         Report.Error (1548, "Could not access the key inside the container `" +
130                                                 RootContext.StrongNameKeyContainer + "'.");
131                                         Environment.Exit (1);
132                                 }
133                                 throw;
134                         }
135                         catch (CryptographicException) {
136                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
137                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
138                                         Environment.Exit (1);
139                                 }
140                                 throw;
141                         }
142
143                         //
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
147                         //
148                         // If the third argument is true, the ModuleBuilder will dynamically
149                         // load the default symbol writer.
150                         //
151                         Module.Builder = Assembly.Builder.DefineDynamicModule (
152                                 Basename (name), Basename (output), false);
153
154                         if (want_debugging_support)
155                                 InitializeSymbolWriter (output);
156                 }
157
158                 static public void Save (string name)
159                 {
160                         try {
161                                 Assembly.Builder.Save (Basename (name));
162                         }
163                         catch (COMException) {
164                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
165                                         throw;
166
167                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
168                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
169                                         RootContext.StrongNameKeyFile +
170                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
171                         }
172                         catch (System.IO.IOException io) {
173                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
174                         }
175
176                         if (SymbolWriter != null)
177                                 SymbolWriter.WriteSymbolFile ();
178                 }
179         }
180
181         //
182         // Provides "local" store across code that can yield: locals
183         // or fields, notice that this should not be used by anonymous
184         // methods to create local storage, those only require
185         // variable mapping.
186         //
187         public class VariableStorage {
188                 FieldBuilder fb;
189                 LocalBuilder local;
190                 
191                 static int count;
192                 
193                 public VariableStorage (EmitContext ec, Type t)
194                 {
195                         count++;
196                         if (ec.InIterator)
197                                 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
198                         else
199                                 local = ec.ig.DeclareLocal (t);
200                 }
201
202                 public void EmitThis (ILGenerator ig)
203                 {
204                         if (fb != null)
205                                 ig.Emit (OpCodes.Ldarg_0);
206                 }
207
208                 public void EmitStore (ILGenerator ig)
209                 {
210                         if (fb == null)
211                                 ig.Emit (OpCodes.Stloc, local);
212                         else
213                                 ig.Emit (OpCodes.Stfld, fb);
214                 }
215
216                 public void EmitLoad (ILGenerator ig)
217                 {
218                         if (fb == null)
219                                 ig.Emit (OpCodes.Ldloc, local);
220                         else 
221                                 ig.Emit (OpCodes.Ldfld, fb);
222                 }
223
224                 public void EmitLoadAddress (ILGenerator ig)
225                 {
226                         if (fb == null)
227                                 ig.Emit (OpCodes.Ldloca, local);
228                         else 
229                                 ig.Emit (OpCodes.Ldflda, fb);
230                 }
231                 
232                 public void EmitCall (ILGenerator ig, MethodInfo mi)
233                 {
234                         // FIXME : we should handle a call like tostring
235                         // here, where boxing is needed. However, we will
236                         // never encounter that with the current usage.
237                         
238                         bool value_type_call;
239                         EmitThis (ig);
240                         if (fb == null) {
241                                 value_type_call = local.LocalType.IsValueType;
242                                 
243                                 if (value_type_call)
244                                         ig.Emit (OpCodes.Ldloca, local);
245                                 else
246                                         ig.Emit (OpCodes.Ldloc, local);
247                         } else {
248                                 value_type_call = fb.FieldType.IsValueType;
249                                 
250                                 if (value_type_call)
251                                         ig.Emit (OpCodes.Ldflda, fb);
252                                 else
253                                         ig.Emit (OpCodes.Ldfld, fb);
254                         }
255                         
256                         ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
257                 }
258         }
259         
260         /// <summary>
261         ///   An Emit Context is created for each body of code (from methods,
262         ///   properties bodies, indexer bodies or constructor bodies)
263         /// </summary>
264         public class EmitContext {
265                 public DeclSpace DeclSpace;
266                 public DeclSpace TypeContainer;
267                 public ILGenerator   ig;
268
269                 /// <summary>
270                 ///   This variable tracks the `checked' state of the compilation,
271                 ///   it controls whether we should generate code that does overflow
272                 ///   checking, or if we generate code that ignores overflows.
273                 ///
274                 ///   The default setting comes from the command line option to generate
275                 ///   checked or unchecked code plus any source code changes using the
276                 ///   checked/unchecked statements or expressions.   Contrast this with
277                 ///   the ConstantCheckState flag.
278                 /// </summary>
279                 
280                 public bool CheckState;
281
282                 /// <summary>
283                 ///   The constant check state is always set to `true' and cant be changed
284                 ///   from the command line.  The source code can change this setting with
285                 ///   the `checked' and `unchecked' statements and expressions. 
286                 /// </summary>
287                 public bool ConstantCheckState;
288
289                 /// <summary>
290                 ///   Whether we are emitting code inside a static or instance method
291                 /// </summary>
292                 public bool IsStatic;
293
294                 /// <summary>
295                 ///   Whether we are emitting a field initializer
296                 /// </summary>
297                 public bool IsFieldInitializer;
298
299                 /// <summary>
300                 ///   The value that is allowed to be returned or NULL if there is no
301                 ///   return type.
302                 /// </summary>
303                 public Type ReturnType;
304
305                 /// <summary>
306                 ///   Points to the Type (extracted from the TypeContainer) that
307                 ///   declares this body of code
308                 /// </summary>
309                 public Type ContainerType;
310                 
311                 /// <summary>
312                 ///   Whether this is generating code for a constructor
313                 /// </summary>
314                 public bool IsConstructor;
315
316                 /// <summary>
317                 ///   Whether we're control flow analysis enabled
318                 /// </summary>
319                 public bool DoFlowAnalysis;
320                 
321                 /// <summary>
322                 ///   Keeps track of the Type to LocalBuilder temporary storage created
323                 ///   to store structures (used to compute the address of the structure
324                 ///   value on structure method invocations)
325                 /// </summary>
326                 public Hashtable temporary_storage;
327
328                 public Block CurrentBlock;
329
330                 public int CurrentFile;
331
332                 /// <summary>
333                 ///   The location where we store the return value.
334                 /// </summary>
335                 LocalBuilder return_value;
336
337                 /// <summary>
338                 ///   The location where return has to jump to return the
339                 ///   value
340                 /// </summary>
341                 public Label ReturnLabel;
342
343                 /// <summary>
344                 ///   If we already defined the ReturnLabel
345                 /// </summary>
346                 public bool HasReturnLabel;
347
348                 /// <summary>
349                 ///   Whether we are inside an iterator block.
350                 /// </summary>
351                 public bool InIterator;
352
353                 public bool IsLastStatement;
354                 
355                 /// <summary>
356                 ///   Whether remapping of locals, parameters and fields is turned on.
357                 ///   Used by iterators and anonymous methods.
358                 /// </summary>
359                 public bool RemapToProxy;
360
361                 /// <summary>
362                 ///  Whether we are inside an unsafe block
363                 /// </summary>
364                 public bool InUnsafe;
365
366                 /// <summary>
367                 ///  Whether we are in a `fixed' initialization
368                 /// </summary>
369                 public bool InFixedInitializer;
370
371                 /// <summary>
372                 ///  Whether we are inside an anonymous method.
373                 /// </summary>
374                 public AnonymousMethod CurrentAnonymousMethod;
375                 
376                 /// <summary>
377                 ///   Location for this EmitContext
378                 /// </summary>
379                 public Location loc;
380
381                 /// <summary>
382                 ///   Used to flag that it is ok to define types recursively, as the
383                 ///   expressions are being evaluated as part of the type lookup
384                 ///   during the type resolution process
385                 /// </summary>
386                 public bool ResolvingTypeTree;
387                 
388                 /// <summary>
389                 ///   Inside an enum definition, we do not resolve enumeration values
390                 ///   to their enumerations, but rather to the underlying type/value
391                 ///   This is so EnumVal + EnumValB can be evaluated.
392                 ///
393                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
394                 ///   we relax the rules
395                 /// </summary>
396                 public bool InEnumContext;
397
398                 /// <summary>
399                 ///   Anonymous methods can capture local variables and fields,
400                 ///   this object tracks it.  It is copied from the TopLevelBlock
401                 ///   field.
402                 /// </summary>
403                 public CaptureContext capture_context;
404
405                 /// <summary>
406                 /// Trace when method is called and is obsolete then this member suppress message
407                 /// when call is inside next [Obsolete] method or type.
408                 /// </summary>
409                 public bool TestObsoleteMethodUsage = true;
410
411                 /// <summary>
412                 ///    The current iterator
413                 /// </summary>
414                 public Iterator CurrentIterator;
415
416                 /// <summary>
417                 ///    Whether we are in the resolving stage or not
418                 /// </summary>
419                 enum Phase {
420                         Created,
421                         Resolving,
422                         Emitting
423                 }
424                 
425                 Phase current_phase;
426                 
427                 FlowBranching current_flow_branching;
428                 
429                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
430                                     Type return_type, int code_flags, bool is_constructor)
431                 {
432                         this.ig = ig;
433
434                         TypeContainer = parent;
435                         DeclSpace = ds;
436                         CheckState = RootContext.Checked;
437                         ConstantCheckState = true;
438
439                         if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
440                                 throw new Exception ("FUCK");
441                         
442                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
443                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
444                         RemapToProxy = InIterator;
445                         ReturnType = return_type;
446                         IsConstructor = is_constructor;
447                         CurrentBlock = null;
448                         CurrentFile = 0;
449                         current_phase = Phase.Created;
450                         
451                         if (parent != null){
452                                 // Can only be null for the ResolveType contexts.
453                                 ContainerType = parent.TypeBuilder;
454                                 if (parent.UnsafeContext)
455                                         InUnsafe = true;
456                                 else
457                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
458                         }
459                         loc = l;
460
461                         if (ReturnType == TypeManager.void_type)
462                                 ReturnType = null;
463                 }
464
465                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
466                                     Type return_type, int code_flags, bool is_constructor)
467                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
468                 {
469                 }
470
471                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
472                                     Type return_type, int code_flags)
473                         : this (tc, tc, l, ig, return_type, code_flags, false)
474                 {
475                 }
476
477                 public FlowBranching CurrentBranching {
478                         get {
479                                 return current_flow_branching;
480                         }
481                 }
482
483                 public bool HaveCaptureInfo {
484                         get {
485                                 return capture_context != null;
486                         }
487                 }
488
489                 // <summary>
490                 //   Starts a new code branching.  This inherits the state of all local
491                 //   variables and parameters from the current branching.
492                 // </summary>
493                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
494                 {
495                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
496                         return current_flow_branching;
497                 }
498
499                 // <summary>
500                 //   Starts a new code branching for block `block'.
501                 // </summary>
502                 public FlowBranching StartFlowBranching (Block block)
503                 {
504                         FlowBranching.BranchingType type;
505
506                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
507                                 type = FlowBranching.BranchingType.SwitchSection;
508                         else
509                                 type = FlowBranching.BranchingType.Block;
510
511                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
512                         return current_flow_branching;
513                 }
514
515                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
516                 {
517                         FlowBranchingException branching = new FlowBranchingException (
518                                 CurrentBranching, stmt);
519                         current_flow_branching = branching;
520                         return branching;
521                 }
522
523                 // <summary>
524                 //   Ends a code branching.  Merges the state of locals and parameters
525                 //   from all the children of the ending branching.
526                 // </summary>
527                 public FlowBranching.UsageVector DoEndFlowBranching ()
528                 {
529                         FlowBranching old = current_flow_branching;
530                         current_flow_branching = current_flow_branching.Parent;
531
532                         return current_flow_branching.MergeChild (old);
533                 }
534
535                 // <summary>
536                 //   Ends a code branching.  Merges the state of locals and parameters
537                 //   from all the children of the ending branching.
538                 // </summary>
539                 public FlowBranching.Reachability EndFlowBranching ()
540                 {
541                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
542
543                         return vector.Reachability;
544                 }
545
546                 // <summary>
547                 //   Kills the current code branching.  This throws away any changed state
548                 //   information and should only be used in case of an error.
549                 // </summary>
550                 public void KillFlowBranching ()
551                 {
552                         current_flow_branching = current_flow_branching.Parent;
553                 }
554
555                 public void CaptureVariable (LocalInfo li)
556                 {
557                         capture_context.AddLocal (CurrentAnonymousMethod, li);
558                         li.IsCaptured = true;
559                 }
560
561                 public void CaptureParameter (string name, Type t, int idx)
562                 {
563                         
564                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
565                 }
566                 
567                 //
568                 // Use to register a field as captured
569                 //
570                 public void CaptureField (FieldExpr fe)
571                 {
572                         capture_context.AddField (fe);
573                 }
574
575                 //
576                 // Whether anonymous methods have captured variables
577                 //
578                 public bool HaveCapturedVariables ()
579                 {
580                         if (capture_context != null)
581                                 return capture_context.HaveCapturedVariables;
582                         return false;
583                 }
584
585                 //
586                 // Whether anonymous methods have captured fields or this.
587                 //
588                 public bool HaveCapturedFields ()
589                 {
590                         if (capture_context != null)
591                                 return capture_context.HaveCapturedFields;
592                         return false;
593                 }
594
595                 //
596                 // Emits the instance pointer for the host method
597                 //
598                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
599                 {
600                         if (capture_context != null)
601                                 capture_context.EmitMethodHostInstance (target, am);
602                         else if (IsStatic)
603                                 target.ig.Emit (OpCodes.Ldnull);
604                         else
605                                 target.ig.Emit (OpCodes.Ldarg_0);
606                 }
607
608                 //
609                 // Returns whether the `local' variable has been captured by an anonymous
610                 // method
611                 //
612                 public bool IsCaptured (LocalInfo local)
613                 {
614                         return capture_context.IsCaptured (local);
615                 }
616
617                 public bool IsParameterCaptured (string name)
618                 {
619                         if (capture_context != null)
620                                 return capture_context.IsParameterCaptured (name);
621                         return false;
622                 }
623                 
624                 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
625                 {
626                         if (capture_context != null)
627                                 capture_context.EmitHelperClasses (this);
628                         b.EmitMeta (this);
629
630                         if (HasReturnLabel)
631                                 ReturnLabel = ig.DefineLabel ();
632                 }
633
634                 //
635                 // Here until we can fix the problem with Mono.CSharp.Switch, which
636                 // currently can not cope with ig == null during resolve (which must
637                 // be fixed for switch statements to work on anonymous methods).
638                 //
639                 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
640                 {
641                         if (block == null)
642                                 return;
643                         
644                         bool unreachable;
645                         
646                         if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
647                                 EmitMeta (block, ip);
648
649                                 current_phase = Phase.Emitting;
650                                 EmitResolvedTopBlock (block, unreachable);
651                         }
652                 }
653
654                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
655                                              InternalParameters ip, Location loc, out bool unreachable)
656                 {
657                         current_phase = Phase.Resolving;
658                         
659                         unreachable = false;
660
661                         capture_context = block.CaptureContext;
662
663                         if (!Location.IsNull (loc))
664                                 CurrentFile = loc.File;
665
666 #if PRODUCTION
667                             try {
668 #endif
669                                 int errors = Report.Errors;
670
671                                 block.ResolveMeta (block, this, ip);
672
673
674                                 if (Report.Errors == errors){
675                                         bool old_do_flow_analysis = DoFlowAnalysis;
676                                         DoFlowAnalysis = true;
677
678                                         if (anonymous_method_host != null)
679                                                 current_flow_branching = FlowBranching.CreateBranching (
680                                                 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
681                                                 block, loc);
682                                         else 
683                                         current_flow_branching = FlowBranching.CreateBranching (
684                                                 null, FlowBranching.BranchingType.Block, block, loc);
685
686                                         if (!block.Resolve (this)) {
687                                                 current_flow_branching = null;
688                                                 DoFlowAnalysis = old_do_flow_analysis;
689                                                 return false;
690                                         }
691
692                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
693                                         current_flow_branching = null;
694
695                                         DoFlowAnalysis = old_do_flow_analysis;
696
697                                         if (reachability.AlwaysReturns ||
698                                             reachability.AlwaysThrows ||
699                                             reachability.IsUnreachable)
700                                                 unreachable = true;
701                                         }
702 #if PRODUCTION
703                             } catch (Exception e) {
704                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
705                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
706                                         
707                                         if (CurrentBlock != null){
708                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
709                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
710                                         }
711                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
712                                 throw;
713                         }
714 #endif
715
716                         if (ReturnType != null && !unreachable){
717                                 if (!InIterator){
718                                         if (CurrentAnonymousMethod != null){
719                                                 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
720                                                               CurrentAnonymousMethod.Type);
721                                         } else {
722                                         Report.Error (161, loc, "Not all code paths return a value");
723                                         }
724
725                                         return false;
726                                 }
727                         }
728                         block.CompleteContexts ();
729
730                         return true;
731                 }
732
733                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
734                 {
735                         if (block != null)
736                                 block.Emit (this);
737
738                         if (HasReturnLabel)
739                                 ig.MarkLabel (ReturnLabel);
740
741                         if (return_value != null){
742                                 ig.Emit (OpCodes.Ldloc, return_value);
743                                 ig.Emit (OpCodes.Ret);
744                         } else {
745                                 //
746                                 // If `HasReturnLabel' is set, then we already emitted a
747                                 // jump to the end of the method, so we must emit a `ret'
748                                 // there.
749                                 //
750                                 // Unfortunately, System.Reflection.Emit automatically emits
751                                 // a leave to the end of a finally block.  This is a problem
752                                 // if no code is following the try/finally block since we may
753                                 // jump to a point after the end of the method.
754                                 // As a workaround, we're always creating a return label in
755                                 // this case.
756                                 //
757
758                                 if ((block != null) && block.IsDestructor) {
759                                         // Nothing to do; S.R.E automatically emits a leave.
760                                 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
761                                         if (ReturnType != null)
762                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
763                                         ig.Emit (OpCodes.Ret);
764                                 }
765                         }
766
767                         //
768                         // Close pending helper classes if we are the toplevel
769                         //
770                         if (capture_context != null && capture_context.ParentToplevel == null)
771                                 capture_context.CloseHelperClasses ();
772                 }
773
774                 /// <summary>
775                 ///   This is called immediately before emitting an IL opcode to tell the symbol
776                 ///   writer to which source line this opcode belongs.
777                 /// </summary>
778                 public void Mark (Location loc, bool check_file)
779                 {
780                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
781                                 return;
782
783                         if (check_file && (CurrentFile != loc.File))
784                                 return;
785
786                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
787                 }
788
789                 public void DefineLocalVariable (string name, LocalBuilder builder)
790                 {
791                         if (CodeGen.SymbolWriter == null)
792                                 return;
793
794                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
795                 }
796
797                 /// <summary>
798                 ///   Returns a temporary storage for a variable of type t as 
799                 ///   a local variable in the current body.
800                 /// </summary>
801                 public LocalBuilder GetTemporaryLocal (Type t)
802                 {
803                         LocalBuilder location = null;
804                         
805                         if (temporary_storage != null){
806                                 object o = temporary_storage [t];
807                                 if (o != null){
808                                         if (o is ArrayList){
809                                                 ArrayList al = (ArrayList) o;
810                                                 
811                                                 for (int i = 0; i < al.Count; i++){
812                                                         if (al [i] != null){
813                                                                 location = (LocalBuilder) al [i];
814                                                                 al [i] = null;
815                                                                 break;
816                                                         }
817                                                 }
818                                         } else
819                                                 location = (LocalBuilder) o;
820                                         if (location != null)
821                                                 return location;
822                                 }
823                         }
824                         
825                         return ig.DeclareLocal (t);
826                 }
827
828                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
829                 {
830                         if (temporary_storage == null){
831                                 temporary_storage = new Hashtable ();
832                                 temporary_storage [t] = b;
833                                 return;
834                         }
835                         object o = temporary_storage [t];
836                         if (o == null){
837                                 temporary_storage [t] = b;
838                                 return;
839                         }
840                         if (o is ArrayList){
841                                 ArrayList al = (ArrayList) o;
842                                 for (int i = 0; i < al.Count; i++){
843                                         if (al [i] == null){
844                                                 al [i] = b;
845                                                 return;
846                                         }
847                                 }
848                                 al.Add (b);
849                                 return;
850                         }
851                         ArrayList replacement = new ArrayList ();
852                         replacement.Add (o);
853                         temporary_storage.Remove (t);
854                         temporary_storage [t] = replacement;
855                 }
856
857                 /// <summary>
858                 ///   Current loop begin and end labels.
859                 /// </summary>
860                 public Label LoopBegin, LoopEnd;
861
862                 /// <summary>
863                 ///   Default target in a switch statement.   Only valid if
864                 ///   InSwitch is true
865                 /// </summary>
866                 public Label DefaultTarget;
867
868                 /// <summary>
869                 ///   If this is non-null, points to the current switch statement
870                 /// </summary>
871                 public Switch Switch;
872
873                 /// <summary>
874                 ///   ReturnValue creates on demand the LocalBuilder for the
875                 ///   return value from the function.  By default this is not
876                 ///   used.  This is only required when returns are found inside
877                 ///   Try or Catch statements.
878                 ///
879                 ///   This method is typically invoked from the Emit phase, so
880                 ///   we allow the creation of a return label if it was not
881                 ///   requested during the resolution phase.   Could be cleaned
882                 ///   up, but it would replicate a lot of logic in the Emit phase
883                 ///   of the code that uses it.
884                 /// </summary>
885                 public LocalBuilder TemporaryReturn ()
886                 {
887                         if (return_value == null){
888                                 return_value = ig.DeclareLocal (ReturnType);
889                                 if (!HasReturnLabel){
890                                 ReturnLabel = ig.DefineLabel ();
891                                 HasReturnLabel = true;
892                         }
893                         }
894
895                         return return_value;
896                 }
897
898                 /// <summary>
899                 ///   This method is used during the Resolution phase to flag the
900                 ///   need to define the ReturnLabel
901                 /// </summary>
902                 public void NeedReturnLabel ()
903                 {
904                         if (current_phase != Phase.Resolving){
905                                 //
906                                 // The reason is that the `ReturnLabel' is declared between
907                                 // resolution and emission
908                                 // 
909                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
910                         }
911                         
912                         if (!InIterator && !HasReturnLabel) 
913                                 HasReturnLabel = true;
914                         }
915
916                 //
917                 // Creates a field `name' with the type `t' on the proxy class
918                 //
919                 public FieldBuilder MapVariable (string name, Type t)
920                 {
921                         if (InIterator)
922                                 return CurrentIterator.MapVariable ("v_", name, t);
923
924                         throw new Exception ("MapVariable for an unknown state");
925                 }
926
927                 public Expression RemapParameter (int idx)
928                 {
929                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
930                         fe.InstanceExpression = new ProxyInstance ();
931                         return fe.DoResolve (this);
932                 }
933
934                 public Expression RemapParameterLValue (int idx, Expression right_side)
935                 {
936                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
937                         fe.InstanceExpression = new ProxyInstance ();
938                         return fe.DoResolveLValue (this, right_side);
939                 }
940                 
941                 //
942                 // Emits the proper object to address fields on a remapped
943                 // variable/parameter to field in anonymous-method/iterator proxy classes.
944                 //
945                 public void EmitThis ()
946                 {
947                         ig.Emit (OpCodes.Ldarg_0);
948                         if (InIterator){
949                                 if (!IsStatic){
950                                 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
951                                 if (TypeManager.IsValueType (this_field.FieldType))
952                                         ig.Emit (OpCodes.Ldflda, this_field);
953                                 else
954                                         ig.Emit (OpCodes.Ldfld, this_field);
955                         }
956                         } else if (capture_context != null && CurrentAnonymousMethod != null){
957                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
958                                 while (si != null){
959                                         if (si.ParentLink != null)
960                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
961                                         if (si.THIS != null){
962                                                 ig.Emit (OpCodes.Ldfld, si.THIS);
963                                                 break;
964                                         }
965                                         si = si.ParentScope;
966                                 }
967                         } 
968                 }
969
970                 //
971                 // Emits the code necessary to load the instance required
972                 // to access the captured LocalInfo
973                 //
974                 public void EmitCapturedVariableInstance (LocalInfo li)
975                 {
976                         if (RemapToProxy){
977                                 ig.Emit (OpCodes.Ldarg_0);
978                                 return;
979                         }
980                         
981                         if (capture_context == null)
982                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
983                         
984                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
985                 }
986
987                 public void EmitParameter (string name)
988                 {
989                         capture_context.EmitParameter (this, name);
990                 }
991
992                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
993                 {
994                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
995                 }
996
997                 public void EmitAddressOfParameter (string name)
998                 {
999                         capture_context.EmitAddressOfParameter (this, name);
1000                 }
1001
1002                 public Expression GetThis (Location loc)
1003                 {
1004                         This my_this;
1005                         if (CurrentBlock != null)
1006                                 my_this = new This (CurrentBlock, loc);
1007                         else
1008                                 my_this = new This (loc);
1009
1010                         if (!my_this.ResolveBase (this))
1011                                 my_this = null;
1012
1013                         return my_this;
1014                 }
1015         }
1016
1017
1018         public abstract class CommonAssemblyModulClass: Attributable {
1019                 protected CommonAssemblyModulClass ():
1020                         base (null)
1021                 {
1022                 }
1023
1024                 public void AddAttributes (ArrayList attrs)
1025                 {
1026                         if (OptAttributes == null) {
1027                                 OptAttributes = new Attributes (attrs);
1028                                 return;
1029                         }
1030                         OptAttributes.AddAttributes (attrs);
1031                 }
1032
1033                 public virtual void Emit (TypeContainer tc) 
1034                 {
1035                         if (OptAttributes == null)
1036                                 return;
1037
1038                         EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1039                         OptAttributes.Emit (ec, this);
1040                 }
1041
1042                 protected Attribute GetClsCompliantAttribute ()
1043                 {
1044                         if (OptAttributes == null)
1045                                 return null;
1046
1047                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1048                         if (!OptAttributes.CheckTargets (this))
1049                                 return null;
1050
1051                         EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1052                         Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1053                         if (a != null) {
1054                                 a.Resolve (temp_ec);
1055                         }
1056                         return a;
1057                 }
1058         }
1059
1060         public class AssemblyClass: CommonAssemblyModulClass {
1061                 // TODO: make it private and move all builder based methods here
1062                 public AssemblyBuilder Builder;
1063                     
1064                 bool is_cls_compliant;
1065                 public Attribute ClsCompliantAttribute;
1066
1067                 ListDictionary declarative_security;
1068
1069                 static string[] attribute_targets = new string [] { "assembly" };
1070
1071                 public AssemblyClass (): base ()
1072                 {
1073                         is_cls_compliant = false;
1074                 }
1075
1076                 public bool IsClsCompliant {
1077                         get {
1078                                 return is_cls_compliant;
1079                         }
1080                         }
1081
1082                 public override AttributeTargets AttributeTargets {
1083                         get {
1084                                 return AttributeTargets.Assembly;
1085                         }
1086                 }
1087
1088                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1089                 {
1090                         return is_cls_compliant;
1091                 }
1092
1093                 public void ResolveClsCompliance ()
1094                 {
1095                         ClsCompliantAttribute = GetClsCompliantAttribute ();
1096                         if (ClsCompliantAttribute == null)
1097                                 return;
1098
1099                         is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1100                 }
1101
1102                 // fix bug #56621
1103                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1104                 {
1105                         try {
1106                                 // check for possible ECMA key
1107                                 if (strongNameBlob.Length == 16) {
1108                                         // will be rejected if not "the" ECMA key
1109                                         an.SetPublicKey (strongNameBlob);
1110                                 }
1111                                 else {
1112                                         // take it, with or without, a private key
1113                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1114                                         // and make sure we only feed the public part to Sys.Ref
1115                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1116                                         
1117                                         // AssemblyName.SetPublicKey requires an additional header
1118                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1119
1120                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1121                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1122                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1123                                         an.SetPublicKey (encodedPublicKey);
1124                                 }
1125                         }
1126                         catch (Exception) {
1127                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1128                                         RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1129                                 Environment.Exit (1);
1130                         }
1131                 }
1132
1133                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1134                 public AssemblyName GetAssemblyName (string name, string output) 
1135                 {
1136                         if (OptAttributes != null) {
1137                                foreach (Attribute a in OptAttributes.Attrs) {
1138                                        // cannot rely on any resolve-based members before you call Resolve
1139                                        if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1140                                                continue;
1141
1142                                        // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1143                                        //       However, this is invoked by CodeGen.Init, at which time none of the namespaces
1144                                        //       are loaded yet.
1145                                         switch (a.Name) {
1146                                                 case "AssemblyKeyFile":
1147                                                case "AssemblyKeyFileAttribute":
1148                                                case "System.Reflection.AssemblyKeyFileAttribute":
1149                                                         if (RootContext.StrongNameKeyFile != null) {
1150                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1151                                                                 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1152                                                         }
1153                                                         else {
1154                                                                 string value = a.GetString ();
1155                                                                 if (value != String.Empty)
1156                                                                         RootContext.StrongNameKeyFile = value;
1157                                                         }
1158                                                         break;
1159                                                 case "AssemblyKeyName":
1160                                                case "AssemblyKeyNameAttribute":
1161                                                case "System.Reflection.AssemblyKeyNameAttribute":
1162                                                         if (RootContext.StrongNameKeyContainer != null) {
1163                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1164                                                                 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1165                                                         }
1166                                                         else {
1167                                                                 string value = a.GetString ();
1168                                                                 if (value != String.Empty)
1169                                                                         RootContext.StrongNameKeyContainer = value;
1170                                                         }
1171                                                         break;
1172                                                 case "AssemblyDelaySign":
1173                                                case "AssemblyDelaySignAttribute":
1174                                                case "System.Reflection.AssemblyDelaySignAttribute":
1175                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1176                                                         break;
1177                                         }
1178                                 }
1179                         }
1180
1181                         AssemblyName an = new AssemblyName ();
1182                         an.Name = Path.GetFileNameWithoutExtension (name);
1183
1184                         // note: delay doesn't apply when using a key container
1185                         if (RootContext.StrongNameKeyContainer != null) {
1186                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1187                                 return an;
1188                         }
1189
1190                         // strongname is optional
1191                         if (RootContext.StrongNameKeyFile == null)
1192                                 return an;
1193
1194                         string AssemblyDir = Path.GetDirectoryName (output);
1195
1196                         // the StrongName key file may be relative to (a) the compiled
1197                         // file or (b) to the output assembly. See bugzilla #55320
1198                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1199
1200                         // (a) relative to the compiled file
1201                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1202                         bool exist = File.Exists (filename);
1203                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1204                                 // (b) relative to the outputed assembly
1205                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1206                                 exist = File.Exists (filename);
1207                         }
1208
1209                         if (exist) {
1210                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1211                                         byte[] snkeypair = new byte [fs.Length];
1212                                         fs.Read (snkeypair, 0, snkeypair.Length);
1213
1214                                         if (RootContext.StrongNameDelaySign) {
1215                                                 // delayed signing - DO NOT include private key
1216                                                 SetPublicKey (an, snkeypair);
1217                                         }
1218                                         else {
1219                                                 // no delay so we make sure we have the private key
1220                                                 try {
1221                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1222                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1223                                                 }
1224                                                 catch (CryptographicException) {
1225                                                         if (snkeypair.Length == 16) {
1226                                                                 // error # is different for ECMA key
1227                                                                 Report.Error (1606, "Could not strongname the assembly. " + 
1228                                                                         "ECMA key can only be used to delay-sign assemblies");
1229                                                         }
1230                                                         else {
1231                                                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1232                                                                         RootContext.StrongNameKeyFile +
1233                                                                         "' doesn't have a private key.");
1234                                                         }
1235                                                         Environment.Exit (1);
1236                                                 }
1237                                         }
1238                                 }
1239                         }
1240                         else {
1241                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1242                                         RootContext.StrongNameKeyFile + "' not found.");
1243                                 Environment.Exit (1);
1244                         }
1245                         return an;
1246                 }
1247
1248                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1249                 {
1250                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1251                                 if (declarative_security == null)
1252                                         declarative_security = new ListDictionary ();
1253
1254                                 a.ExtractSecurityPermissionSet (declarative_security);
1255                                 return;
1256                         }
1257
1258                         Builder.SetCustomAttribute (customBuilder);
1259                 }
1260
1261                 public override void Emit (TypeContainer tc)
1262                 {
1263                         base.Emit (tc);
1264
1265                         if (declarative_security != null) {
1266
1267                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1268                                 object builder_instance = Builder;
1269
1270                                 try {
1271                                         // Microsoft runtime hacking
1272                                         if (add_permission == null) {
1273                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1274                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1275
1276                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1277                                                 builder_instance = fi.GetValue (Builder);
1278                                         }
1279
1280                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1281                                                                                                   declarative_security [SecurityAction.RequestOptional],
1282                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1283                                         add_permission.Invoke (builder_instance, args);
1284                                 }
1285                                 catch {
1286                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1287                                 }
1288                         }
1289                 }
1290
1291                 public override string[] ValidAttributeTargets {
1292                         get {
1293                                 return attribute_targets;
1294                         }
1295                 }
1296         }
1297
1298         public class ModuleClass: CommonAssemblyModulClass {
1299                 // TODO: make it private and move all builder based methods here
1300                 public ModuleBuilder Builder;
1301                 bool m_module_is_unsafe;
1302
1303                 static string[] attribute_targets = new string [] { "module" };
1304
1305                 public ModuleClass (bool is_unsafe)
1306                 {
1307                         m_module_is_unsafe = is_unsafe;
1308                 }
1309
1310                 public override AttributeTargets AttributeTargets {
1311                         get {
1312                                 return AttributeTargets.Module;
1313                         }
1314                 }
1315
1316                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1317                 {
1318                         return CodeGen.Assembly.IsClsCompliant;
1319                         }
1320
1321                 public override void Emit (TypeContainer tc) 
1322                 {
1323                         base.Emit (tc);
1324
1325                         if (!m_module_is_unsafe)
1326                                 return;
1327
1328                         if (TypeManager.unverifiable_code_ctor == null) {
1329                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1330                                 return;
1331                         }
1332                                 
1333                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1334                 }
1335                 
1336                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1337                 {
1338                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1339                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1340                                         Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1341                                 }
1342                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1343                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1344                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1345                                         return;
1346                                 }
1347                         }
1348
1349                         Builder.SetCustomAttribute (customBuilder);
1350                 }
1351
1352                 public override string[] ValidAttributeTargets {
1353                         get {
1354                                 return attribute_targets;
1355                         }
1356                 }
1357         }
1358 }