Don't print null on exit
[mono.git] / mcs / mcs / codegen.cs
index d1b42da88e45de6fb8e60dc8248cfb901e626b1c..4a7835b617d3a49734997a00e9521969c5cc4328 100644 (file)
@@ -4,18 +4,23 @@
 // Author:
 //   Miguel de Icaza (miguel@ximian.com)
 //
-// (C) 2001, 2002, 2003 Ximian, Inc.
-// (C) 2004 Novell, Inc.
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2004 Novell, Inc.
 //
 
-#if !DEBUG
-       #define PRODUCTION
-#endif
+//
+// Please leave this defined on SVN: The idea is that when we ship the
+// compiler to end users, if the compiler crashes, they have a chance
+// to narrow down the problem.   
+//
+// Only remove it if you need to debug locally on your tree.
+//
+//#define PRODUCTION
 
 using System;
 using System.IO;
-using System.Collections;
-using System.Collections.Specialized;
+using System.Collections.Generic;
+using System.Globalization;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Runtime.InteropServices;
@@ -32,10 +37,8 @@ namespace Mono.CSharp {
        /// </summary>
        public class CodeGen {
                static AppDomain current_domain;
-               static public SymbolWriter SymbolWriter;
 
                public static AssemblyClass Assembly;
-               public static ModuleClass Module;
 
                static CodeGen ()
                {
@@ -45,7 +48,6 @@ namespace Mono.CSharp {
                public static void Reset ()
                {
                        Assembly = new AssemblyClass ();
-                       Module = new ModuleClass (RootContext.Unsafe);
                }
 
                public static string Basename (string name)
@@ -77,28 +79,25 @@ namespace Mono.CSharp {
                }
 
                static public string FileName;
-
+                               
                //
-               // Initializes the symbol writer
+               // Initializes the code generator variables for interactive use (repl)
                //
-               static void InitializeSymbolWriter (string filename)
+               static public void InitDynamic (CompilerContext ctx, string name)
                {
-                       SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
-
-                       //
-                       // If we got an ISymbolWriter instance, initialize it.
-                       //
-                       if (SymbolWriter == null) {
-                               Report.Warning (
-                                       -18, 1, "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.");
-                               return;
-                       }
+                       current_domain = AppDomain.CurrentDomain;
+                       AssemblyName an = Assembly.GetAssemblyName (name, name);
+                       
+                       Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
+                       RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
+                       RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
+                       Assembly.Name = Assembly.Builder.GetName ();
                }
 
                //
                // Initializes the code generator variables
                //
-               static public bool Init (string name, string output, bool want_debugging_support)
+               static public bool Init (string name, string output, bool want_debugging_support, CompilerContext ctx)
                {
                        FileName = output;
                        AssemblyName an = Assembly.GetAssemblyName (name, output);
@@ -108,11 +107,11 @@ namespace Mono.CSharp {
                        if (an.KeyPair != null) {
                                // If we are going to strong name our assembly make
                                // sure all its refs are strong named
-                               foreach (Assembly a in RootNamespace.Global.Assemblies) {
+                               foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
                                        AssemblyName ref_name = a.GetName ();
                                        byte [] b = ref_name.GetPublicKeyToken ();
                                        if (b == null || b.Length == 0) {
-                                               Report.Error (1577, "Assembly generation failed " +
+                                               ctx.Report.Error (1577, "Assembly generation failed " +
                                                                "-- Referenced assembly '" +
                                                                ref_name.Name +
                                                                "' does not have a strong name.");
@@ -125,25 +124,29 @@ namespace Mono.CSharp {
 
                        try {
                                Assembly.Builder = current_domain.DefineDynamicAssembly (an,
-                                       AssemblyBuilderAccess.Save, Dirname (name));
+                                       AssemblyBuilderAccess.RunAndSave, Dirname (name));
                        }
                        catch (ArgumentException) {
                                // specified key may not be exportable outside it's container
                                if (RootContext.StrongNameKeyContainer != null) {
-                                       Report.Error (1548, "Could not access the key inside the container `" +
+                                       ctx.Report.Error (1548, "Could not access the key inside the container `" +
                                                RootContext.StrongNameKeyContainer + "'.");
                                        Environment.Exit (1);
                                }
-                               return false;
+                               throw;
                        }
                        catch (CryptographicException) {
                                if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
-                                       Report.Error (1548, "Could not use the specified key to strongname the assembly.");
+                                       ctx.Report.Error (1548, "Could not use the specified key to strongname the assembly.");
                                        Environment.Exit (1);
                                }
                                return false;
                        }
 
+                       // Get the complete AssemblyName from the builder
+                       // (We need to get the public key and token)
+                       Assembly.Name = Assembly.Builder.GetName ();
+
                        //
                        // Pass a path-less name to DefineDynamicModule.  Wonder how
                        // this copes with output in different directories then.
@@ -152,19 +155,53 @@ namespace Mono.CSharp {
                        // If the third argument is true, the ModuleBuilder will dynamically
                        // load the default symbol writer.
                        //
-                       Module.Builder = Assembly.Builder.DefineDynamicModule (
-                               Basename (name), Basename (output), false);
-
-                       if (want_debugging_support)
-                               InitializeSymbolWriter (output);
+                       try {
+                               RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
+                                       Basename (name), Basename (output), want_debugging_support);
+
+#if !MS_COMPATIBLE
+                               // TODO: We should use SymbolWriter from DefineDynamicModule
+                               if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
+                                       ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
+                                               "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
+                                       return false;
+                               }
+#endif
+                       } catch (ExecutionEngineException e) {
+                               ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
+                                       e.Message);
+                               return false;
+                       }
 
                        return true;
                }
 
-               static public void Save (string name)
+               static public void Save (string name, bool saveDebugInfo, Report Report)
                {
+                       PortableExecutableKinds pekind;
+                       ImageFileMachine machine;
+
+                       switch (RootContext.Platform) {
+                       case Platform.X86:
+                               pekind = PortableExecutableKinds.Required32Bit;
+                               machine = ImageFileMachine.I386;
+                               break;
+                       case Platform.X64:
+                               pekind = PortableExecutableKinds.PE32Plus;
+                               machine = ImageFileMachine.AMD64;
+                               break;
+                       case Platform.IA64:
+                               pekind = PortableExecutableKinds.PE32Plus;
+                               machine = ImageFileMachine.IA64;
+                               break;
+                       case Platform.AnyCPU:
+                       default:
+                               pekind = PortableExecutableKinds.ILOnly;
+                               machine = ImageFileMachine.I386;
+                               break;
+                       }
                        try {
-                               Assembly.Builder.Save (Basename (name));
+                               Assembly.Builder.Save (Basename (name), pekind, machine);
                        }
                        catch (COMException) {
                                if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
@@ -177,116 +214,51 @@ namespace Mono.CSharp {
                        }
                        catch (System.IO.IOException io) {
                                Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
+                               return;
                        }
                        catch (System.UnauthorizedAccessException ua) {
                                Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
+                               return;
+                       }
+                       catch (System.NotImplementedException nie) {
+                               Report.RuntimeMissingSupport (Location.Null, nie.Message);
+                               return;
                        }
 
-                       if (SymbolWriter != null)
+                       //
+                       // Write debuger symbol file
+                       //
+                       if (saveDebugInfo)
                                SymbolWriter.WriteSymbolFile ();
-               }
-       }
-
-
-       public interface IResolveContext
-       {
-               DeclSpace DeclContainer { get; }
-               bool IsInObsoleteScope { get; }
-               bool IsInUnsafeScope { get; }
+                       }
        }
 
        /// <summary>
        ///   An Emit Context is created for each body of code (from methods,
        ///   properties bodies, indexer bodies or constructor bodies)
        /// </summary>
-       public class EmitContext : IResolveContext {
-
-               DeclSpace declSpace;
-               public DeclSpace TypeContainer;
-               public ILGenerator   ig;
-
-               /// <summary>
-               ///   This variable tracks the `checked' state of the compilation,
-               ///   it controls whether we should generate code that does overflow
-               ///   checking, or if we generate code that ignores overflows.
-               ///
-               ///   The default setting comes from the command line option to generate
-               ///   checked or unchecked code plus any source code changes using the
-               ///   checked/unchecked statements or expressions.   Contrast this with
-               ///   the ConstantCheckState flag.
-               /// </summary>
-               
-               public bool CheckState;
-
-               /// <summary>
-               ///   The constant check state is always set to `true' and cant be changed
-               ///   from the command line.  The source code can change this setting with
-               ///   the `checked' and `unchecked' statements and expressions. 
-               /// </summary>
-               public bool ConstantCheckState;
-
-               /// <summary>
-               ///   Whether we are emitting code inside a static or instance method
-               /// </summary>
-               public bool IsStatic;
-
-               /// <summary>
-               ///   Whether the actual created method is static or instance method.
-               ///   Althoug the method might be declared as `static', if an anonymous
-               ///   method is involved, we might turn this into an instance method.
-               ///
-               ///   So this reflects the low-level staticness of the method, while
-               ///   IsStatic represents the semantic, high-level staticness.
-               /// </summary>
-               public bool MethodIsStatic;
-
-               /// <summary>
-               ///   Whether we are emitting a field initializer
-               /// </summary>
-               public bool IsFieldInitializer;
+       public class EmitContext : BuilderContext
+       {
+               // TODO: Has to be private
+               public ILGenerator ig;
 
                /// <summary>
                ///   The value that is allowed to be returned or NULL if there is no
                ///   return type.
                /// </summary>
-               public Type ReturnType;
-
-               /// <summary>
-               ///   Points to the Type (extracted from the TypeContainer) that
-               ///   declares this body of code
-               /// </summary>
-               public Type ContainerType;
-               
-               /// <summary>
-               ///   Whether this is generating code for a constructor
-               /// </summary>
-               public bool IsConstructor;
-
-               /// <summary>
-               ///   Whether we're control flow analysis enabled
-               /// </summary>
-               public bool DoFlowAnalysis;
-
-               /// <summary>
-               ///   Whether we're control flow analysis disabled on struct
-               /// </summary>
-               public bool OmitStructFlowAnalysis;
+               TypeSpec return_type;
 
                /// <summary>
                ///   Keeps track of the Type to LocalBuilder temporary storage created
                ///   to store structures (used to compute the address of the structure
                ///   value on structure method invocations)
                /// </summary>
-               public Hashtable temporary_storage;
-
-               public Block CurrentBlock;
-
-               public int CurrentFile;
+               Dictionary<TypeSpec, object> temporary_storage;
 
                /// <summary>
                ///   The location where we store the return value.
                /// </summary>
-               LocalBuilder return_value;
+               public LocalBuilder return_value;
 
                /// <summary>
                ///   The location where return has to jump to return the
@@ -300,564 +272,537 @@ namespace Mono.CSharp {
                public bool HasReturnLabel;
 
                /// <summary>
-               ///   Whether we are inside an iterator block.
+               ///   Current loop begin and end labels.
                /// </summary>
-               public bool InIterator;
-
-               public bool IsLastStatement;
+               public Label LoopBegin, LoopEnd;
 
                /// <summary>
-               ///  Whether we are inside an unsafe block
+               ///   Default target in a switch statement.   Only valid if
+               ///   InSwitch is true
                /// </summary>
-               public bool InUnsafe;
+               public Label DefaultTarget;
 
                /// <summary>
-               ///  Whether we are in a `fixed' initialization
+               ///   If this is non-null, points to the current switch statement
                /// </summary>
-               public bool InFixedInitializer;
-
-               public bool InRefOutArgumentResolving;
-
-               public bool InCatch;
-               public bool InFinally;
+               public Switch Switch;
 
                /// <summary>
                ///  Whether we are inside an anonymous method.
                /// </summary>
-               public AnonymousContainer CurrentAnonymousMethod;
+               public AnonymousExpression CurrentAnonymousMethod;
                
-               /// <summary>
-               ///   Location for this EmitContext
-               /// </summary>
-               public Location loc;
-
-               /// <summary>
-               ///   Inside an enum definition, we do not resolve enumeration values
-               ///   to their enumerations, but rather to the underlying type/value
-               ///   This is so EnumVal + EnumValB can be evaluated.
-               ///
-               ///   There is no "E operator + (E x, E y)", so during an enum evaluation
-               ///   we relax the rules
-               /// </summary>
-               public bool InEnumContext;
+               public readonly IMemberContext MemberContext;
 
-               /// <summary>
-               ///   Anonymous methods can capture local variables and fields,
-               ///   this object tracks it.  It is copied from the TopLevelBlock
-               ///   field.
-               /// </summary>
-               public CaptureContext capture_context;
-
-               public readonly IResolveContext ResolveContext;
-
-               /// <summary>
-               ///    The current iterator
-               /// </summary>
-               public Iterator CurrentIterator;
+               public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
+               {
+                       this.MemberContext = rc;
+                       this.ig = ig;
 
-               /// <summary>
-               ///    Whether we are in the resolving stage or not
-               /// </summary>
-               enum Phase {
-                       Created,
-                       Resolving,
-                       Emitting
+                       this.return_type = return_type;
                }
-               
-               Phase current_phase;
-               FlowBranching current_flow_branching;
 
-               static int next_id = 0;
-               int id = ++next_id;
+#region Properties
 
-               public override string ToString ()
-               {
-                       return String.Format ("EmitContext ({0}:{1}:{2})", id,
-                                             CurrentIterator, capture_context, loc);
+               public TypeSpec CurrentType {
+                       get { return MemberContext.CurrentType; }
                }
-               
-               public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
-                                   Type return_type, int code_flags, bool is_constructor)
-               {
-                       this.ResolveContext = rc;
-                       this.ig = ig;
-
-                       TypeContainer = parent;
-                       this.declSpace = ds;
-                       CheckState = RootContext.Checked;
-                       ConstantCheckState = true;
-
-                       IsStatic = (code_flags & Modifiers.STATIC) != 0;
-                       MethodIsStatic = IsStatic;
-                       InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
-                       ReturnType = return_type;
-                       IsConstructor = is_constructor;
-                       CurrentBlock = null;
-                       CurrentFile = 0;
-                       current_phase = Phase.Created;
-                       
-                       if (parent != null){
-                               // Can only be null for the ResolveType contexts.
-                               ContainerType = parent.TypeBuilder;
-                               InUnsafe = rc.IsInUnsafeScope;
-                       }
-                       loc = l;
 
-                       if (ReturnType == TypeManager.void_type)
-                               ReturnType = null;
+               public TypeParameter[] CurrentTypeParameters {
+                       get { return MemberContext.CurrentTypeParameters; }
                }
 
-               public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
-                                   Type return_type, int code_flags, bool is_constructor)
-                       : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
-               {
+               public MemberCore CurrentTypeDefinition {
+                       get { return MemberContext.CurrentMemberDefinition; }
                }
 
-               public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
-                                   Type return_type, int code_flags)
-                       : this (rc, ds, ds, l, ig, return_type, code_flags, false)
-               {
+               public bool IsStatic {
+                       get { return MemberContext.IsStatic; }
                }
 
-               public DeclSpace DeclContainer { 
-                       get { return declSpace; }
-                       set { declSpace = value; }
+               bool IsAnonymousStoreyMutateRequired {
+                       get {
+                               return CurrentAnonymousMethod != null &&
+                                       CurrentAnonymousMethod.Storey != null &&
+                                       CurrentAnonymousMethod.Storey.Mutator != null;
+                       }
                }
 
-               public bool IsInObsoleteScope {
-                       get { return ResolveContext.IsInObsoleteScope; }
+               // Has to be used for emitter errors only
+               public Report Report {
+                       get { return MemberContext.Compiler.Report; }
                }
 
-               public bool IsInUnsafeScope {
-                       get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
+               public TypeSpec ReturnType {
+                       get {
+                               return return_type;
+                       }
                }
+#endregion
 
+               /// <summary>
+               ///   This is called immediately before emitting an IL opcode to tell the symbol
+               ///   writer to which source line this opcode belongs.
+               /// </summary>
+               public void Mark (Location loc)
+               {
+                       if (!SymbolWriter.HasSymbolWriter || HasSet (Options.OmitDebugInfo) || loc.IsNull)
+                               return;
 
-               public FlowBranching CurrentBranching {
-                       get { return current_flow_branching; }
+                       SymbolWriter.MarkSequencePoint (ig, loc);
                }
 
-               public bool HaveCaptureInfo {
-                       get { return capture_context != null; }
+               public void DefineLocalVariable (string name, LocalBuilder builder)
+               {
+                       SymbolWriter.DefineLocalVariable (name, builder);
                }
 
-               public void EmitScopeInitFromBlock (Block b)
+               public void BeginCatchBlock (TypeSpec type)
                {
-                       if (capture_context != null)
-                               capture_context.EmitScopeInitFromBlock (this, b);
+                       ig.BeginCatchBlock (type.GetMetaInfo ());
                }
 
-               // <summary>
-               //   Starts a new code branching.  This inherits the state of all local
-               //   variables and parameters from the current branching.
-               // </summary>
-               public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
+               public void BeginExceptionBlock ()
                {
-                       current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
-                       return current_flow_branching;
+                       ig.BeginExceptionBlock ();
                }
 
-               // <summary>
-               //   Starts a new code branching for block `block'.
-               // </summary>
-               public FlowBranching StartFlowBranching (Block block)
+               public void BeginFinallyBlock ()
                {
-                       FlowBranching.BranchingType type;
-
-                       if ((CurrentBranching != null) &&
-                           (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
-                               type = FlowBranching.BranchingType.SwitchSection;
-                       else
-                               type = FlowBranching.BranchingType.Block;
+                       ig.BeginFinallyBlock ();
+               }
 
-                       DoFlowAnalysis = true;
+               public void BeginScope ()
+               {
+                       ig.BeginScope();
+                       SymbolWriter.OpenScope(ig);
+               }
 
-                       current_flow_branching = FlowBranching.CreateBranching (
-                               CurrentBranching, type, block, block.StartLocation);
-                       return current_flow_branching;
+               public void EndExceptionBlock ()
+               {
+                       ig.EndExceptionBlock ();
                }
 
-               public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
+               public void EndScope ()
                {
-                       FlowBranchingException branching = new FlowBranchingException (
-                               CurrentBranching, stmt);
-                       current_flow_branching = branching;
-                       return branching;
+                       ig.EndScope();
+                       SymbolWriter.CloseScope(ig);
                }
 
-               // <summary>
-               //   Ends a code branching.  Merges the state of locals and parameters
-               //   from all the children of the ending branching.
-               // </summary>
-               public FlowBranching.UsageVector DoEndFlowBranching ()
+               public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
                {
-                       FlowBranching old = current_flow_branching;
-                       current_flow_branching = current_flow_branching.Parent;
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
 
-                       return current_flow_branching.MergeChild (old);
+                       return ig.DeclareLocal (type.GetMetaInfo (), pinned);
                }
 
-               // <summary>
-               //   Ends a code branching.  Merges the state of locals and parameters
-               //   from all the children of the ending branching.
-               // </summary>
-               public FlowBranching.Reachability EndFlowBranching ()
+               public Label DefineLabel ()
                {
-                       FlowBranching.UsageVector vector = DoEndFlowBranching ();
-
-                       return vector.Reachability;
+                       return ig.DefineLabel ();
                }
 
-               // <summary>
-               //   Kills the current code branching.  This throws away any changed state
-               //   information and should only be used in case of an error.
-               // </summary>
-               public void KillFlowBranching ()
+               public void MarkLabel (Label label)
                {
-                       current_flow_branching = current_flow_branching.Parent;
+                       ig.MarkLabel (label);
                }
 
-               public void CaptureVariable (LocalInfo li)
+               public void Emit (OpCode opcode)
                {
-                       capture_context.AddLocal (CurrentAnonymousMethod, li);
-                       li.IsCaptured = true;
+                       ig.Emit (opcode);
                }
 
-               public void CaptureParameter (string name, Type t, int idx)
+               public void Emit (OpCode opcode, LocalBuilder local)
                {
-                       capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
+                       ig.Emit (opcode, local);
                }
 
-               public void CaptureThis ()
+               public void Emit (OpCode opcode, string arg)
                {
-                       capture_context.CaptureThis (CurrentAnonymousMethod);
+                       ig.Emit (opcode, arg);
                }
-               
-               
-               //
-               // Use to register a field as captured
-               //
-               public void CaptureField (FieldExpr fe)
+
+               public void Emit (OpCode opcode, double arg)
                {
-                       capture_context.AddField (this, CurrentAnonymousMethod, fe);
+                       ig.Emit (opcode, arg);
                }
 
-               //
-               // Whether anonymous methods have captured variables
-               //
-               public bool HaveCapturedVariables ()
+               public void Emit (OpCode opcode, float arg)
                {
-                       if (capture_context != null)
-                               return capture_context.HaveCapturedVariables;
-                       return false;
+                       ig.Emit (opcode, arg);
                }
 
-               //
-               // Whether anonymous methods have captured fields or this.
-               //
-               public bool HaveCapturedFields ()
+               public void Emit (OpCode opcode, int arg)
                {
-                       if (capture_context != null)
-                               return capture_context.HaveCapturedFields;
-                       return false;
+                       ig.Emit (opcode, arg);
                }
 
-               //
-               // Emits the instance pointer for the host method
-               //
-               public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
+               public void Emit (OpCode opcode, byte arg)
                {
-                       if (capture_context != null)
-                               capture_context.EmitMethodHostInstance (target, am);
-                       else if (IsStatic)
-                               target.ig.Emit (OpCodes.Ldnull);
-                       else
-                               target.ig.Emit (OpCodes.Ldarg_0);
+                       ig.Emit (opcode, arg);
                }
 
-               //
-               // Returns whether the `local' variable has been captured by an anonymous
-               // method
-               //
-               public bool IsCaptured (LocalInfo local)
+               public void Emit (OpCode opcode, Label label)
                {
-                       return capture_context.IsCaptured (local);
+                       ig.Emit (opcode, label);
                }
 
-               public bool IsParameterCaptured (string name)
+               public void Emit (OpCode opcode, Label[] labels)
                {
-                       if (capture_context != null)
-                               return capture_context.IsParameterCaptured (name);
-                       return false;
+                       ig.Emit (opcode, labels);
                }
-               
-               public void EmitMeta (ToplevelBlock b)
+
+               public void Emit (OpCode opcode, TypeSpec type)
                {
-                       if (capture_context != null)
-                               capture_context.EmitAnonymousHelperClasses (this);
-                       b.EmitMeta (this);
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
 
-                       if (HasReturnLabel)
-                               ReturnLabel = ig.DefineLabel ();
+                       ig.Emit (opcode, type.GetMetaInfo ());
                }
 
-               //
-               // Here until we can fix the problem with Mono.CSharp.Switch, which
-               // currently can not cope with ig == null during resolve (which must
-               // be fixed for switch statements to work on anonymous methods).
-               //
-               public void EmitTopBlock (IMethodData md, ToplevelBlock block)
+               public void Emit (OpCode opcode, FieldSpec field)
                {
-                       if (block == null)
-                               return;
-                       
-                       bool unreachable;
-                       
-                       if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
-                               EmitMeta (block);
+                       if (IsAnonymousStoreyMutateRequired)
+                               field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                               current_phase = Phase.Emitting;
-                               EmitResolvedTopBlock (block, unreachable);
-                       }
+                       ig.Emit (opcode, field.GetMetaInfo ());
                }
 
-               bool resolved;
-
-               public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
-                                            Parameters ip, IMethodData md, out bool unreachable)
+               public void Emit (OpCode opcode, MethodSpec method)
                {
-                       current_phase = Phase.Resolving;
-                       
-                       unreachable = false;
-
-                       if (resolved)
-                               return true;
+                       if (IsAnonymousStoreyMutateRequired)
+                               method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                       capture_context = block.CaptureContext;
-                       
-                       if (!loc.IsNull)
-                               CurrentFile = loc.File;
+                       if (method.IsConstructor)
+                               ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
+                       else
+                               ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
+               }
 
-#if PRODUCTION
-                       try {
-#endif
-                               if (!block.ResolveMeta (this, ip))
-                                       return false;
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, MethodInfo method)
+               {
+                       ig.Emit (opcode, method);
+               }
 
-                               bool old_do_flow_analysis = DoFlowAnalysis;
-                               DoFlowAnalysis = true;
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, FieldBuilder field)
+               {
+                       ig.Emit (opcode, field);
+               }
 
-                               if (anonymous_method_host != null)
-                                       current_flow_branching = FlowBranching.CreateBranching (
-                                               anonymous_method_host.CurrentBranching,
-                                               FlowBranching.BranchingType.Block, block, loc);
-                               else 
-                                       current_flow_branching = block.TopLevelBranching;
+               public void Emit (OpCode opcode, MethodSpec method, Type[] vargs)
+               {
+                       // TODO MemberCache: This should mutate too
+                       ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
+               }
 
-                               if (!block.Resolve (this)) {
-                                       current_flow_branching = null;
-                                       DoFlowAnalysis = old_do_flow_analysis;
-                                       return false;
-                               }
+               public void EmitArrayNew (ArrayContainer ac)
+               {
+                       if (ac.Rank == 1) {
+                               Emit (OpCodes.Newarr, ac.Element);
+                       } else {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                               FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
-                               current_flow_branching = null;
+                               ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
+                       }
+               }
 
-                               DoFlowAnalysis = old_do_flow_analysis;
+               public void EmitArrayAddress (ArrayContainer ac)
+               {
+                       if (ac.Element.IsGenericParameter)
+                               ig.Emit (OpCodes.Readonly);
 
-                               if (reachability.AlwaysReturns ||
-                                   reachability.AlwaysThrows ||
-                                   reachability.IsUnreachable)
-                                       unreachable = true;
-#if PRODUCTION
-                       } catch (Exception e) {
-                                       Console.WriteLine ("Exception caught by the compiler while compiling:");
-                                       Console.WriteLine ("   Block that caused the problem begin at: " + loc);
-                                       
-                                       if (CurrentBlock != null){
-                                               Console.WriteLine ("                     Block being compiled: [{0},{1}]",
-                                                                  CurrentBlock.StartLocation, CurrentBlock.EndLocation);
-                                       }
-                                       Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
-                                       throw;
-                       }
-#endif
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                       if (ReturnType != null && !unreachable) {
-                               if (CurrentAnonymousMethod == null) {
-                                       Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
-                                       return false;
-                               } else if (!CurrentAnonymousMethod.IsIterator) {
-                                       Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
-                                               CurrentAnonymousMethod.GetSignatureForError ());
-                                       return false;
-                               }
+                               ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
+                       } else {
+                               Emit (OpCodes.Ldelema, ac.Element);
                        }
-
-                       block.CompleteContexts ();
-                       resolved = true;
-                       return true;
                }
 
-               public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
+               //
+               // Emits the right opcode to load from an array
+               //
+               public void EmitArrayLoad (ArrayContainer ac)
                {
-                       if (block != null)
-                               block.Emit (this);
-                       
-                       if (HasReturnLabel)
-                               ig.MarkLabel (ReturnLabel);
-                       
-                       if (return_value != null){
-                               ig.Emit (OpCodes.Ldloc, return_value);
-                               ig.Emit (OpCodes.Ret);
-                       } else {
-                               //
-                               // If `HasReturnLabel' is set, then we already emitted a
-                               // jump to the end of the method, so we must emit a `ret'
-                               // there.
-                               //
-                               // Unfortunately, System.Reflection.Emit automatically emits
-                               // a leave to the end of a finally block.  This is a problem
-                               // if no code is following the try/finally block since we may
-                               // jump to a point after the end of the method.
-                               // As a workaround, we're always creating a return label in
-                               // this case.
-                               //
-
-                               bool in_iterator = (CurrentAnonymousMethod != null) &&
-                                       CurrentAnonymousMethod.IsIterator && InIterator;
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                               if ((block != null) && block.IsDestructor) {
-                                       // Nothing to do; S.R.E automatically emits a leave.
-                               } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
-                                       if (ReturnType != null)
-                                               ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
-                                       ig.Emit (OpCodes.Ret);
-                               }
+                               ig.Emit (OpCodes.Call, ac.GetGetMethod ());
+                               return;
                        }
 
-                       //
-                       // Close pending helper classes if we are the toplevel
-                       //
-                       if (capture_context != null && capture_context.ParentToplevel == null)
-                               capture_context.CloseAnonymousHelperClasses ();
+                       var type = ac.Element;
+                       if (TypeManager.IsEnumType (type))
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.byte_type || type == TypeManager.bool_type)
+                               Emit (OpCodes.Ldelem_U1);
+                       else if (type == TypeManager.sbyte_type)
+                               Emit (OpCodes.Ldelem_I1);
+                       else if (type == TypeManager.short_type)
+                               Emit (OpCodes.Ldelem_I2);
+                       else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
+                               Emit (OpCodes.Ldelem_U2);
+                       else if (type == TypeManager.int32_type)
+                               Emit (OpCodes.Ldelem_I4);
+                       else if (type == TypeManager.uint32_type)
+                               Emit (OpCodes.Ldelem_U4);
+                       else if (type == TypeManager.uint64_type)
+                               Emit (OpCodes.Ldelem_I8);
+                       else if (type == TypeManager.int64_type)
+                               Emit (OpCodes.Ldelem_I8);
+                       else if (type == TypeManager.float_type)
+                               Emit (OpCodes.Ldelem_R4);
+                       else if (type == TypeManager.double_type)
+                               Emit (OpCodes.Ldelem_R8);
+                       else if (type == TypeManager.intptr_type)
+                               Emit (OpCodes.Ldelem_I);
+                       else if (TypeManager.IsStruct (type)) {
+                               Emit (OpCodes.Ldelema, type);
+                               Emit (OpCodes.Ldobj, type);
+                       } else if (type.IsGenericParameter) {
+                               Emit (OpCodes.Ldelem, type);
+                       } else if (type.IsPointer)
+                               Emit (OpCodes.Ldelem_I);
+                       else
+                               Emit (OpCodes.Ldelem_Ref);
                }
 
-               /// <summary>
-               ///   This is called immediately before emitting an IL opcode to tell the symbol
-               ///   writer to which source line this opcode belongs.
-               /// </summary>
-               public void Mark (Location loc, bool check_file)
+               //
+               // Emits the right opcode to store to an array
+               //
+               public void EmitArrayStore (ArrayContainer ac)
                {
-                       if ((CodeGen.SymbolWriter == null) || loc.IsNull)
-                               return;
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                       if (check_file && (CurrentFile != loc.File))
+                               ig.Emit (OpCodes.Call, ac.GetSetMethod ());
                                return;
+                       }
 
-                       CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
+                       var type = ac.Element;
+
+                       if (type.IsEnum)
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.byte_type || type == TypeManager.sbyte_type || type == TypeManager.bool_type)
+                               Emit (OpCodes.Stelem_I1);
+                       else if (type == TypeManager.short_type || type == TypeManager.ushort_type || type == TypeManager.char_type)
+                               Emit (OpCodes.Stelem_I2);
+                       else if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
+                               Emit (OpCodes.Stelem_I4);
+                       else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
+                               Emit (OpCodes.Stelem_I8);
+                       else if (type == TypeManager.float_type)
+                               Emit (OpCodes.Stelem_R4);
+                       else if (type == TypeManager.double_type)
+                               Emit (OpCodes.Stelem_R8);
+                       else if (type == TypeManager.intptr_type)
+                               Emit (OpCodes.Stobj, type);
+                       else if (TypeManager.IsStruct (type))
+                               Emit (OpCodes.Stobj, type);
+                       else if (type.IsGenericParameter)
+                               Emit (OpCodes.Stelem, type);
+                       else if (type.IsPointer)
+                               Emit (OpCodes.Stelem_I);
+                       else
+                               Emit (OpCodes.Stelem_Ref);
                }
 
-               public void DefineLocalVariable (string name, LocalBuilder builder)
+               public void EmitInt (int i)
                {
-                       if (CodeGen.SymbolWriter == null)
-                               return;
-
-                       CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
+                       switch (i) {
+                       case -1:
+                               ig.Emit (OpCodes.Ldc_I4_M1);
+                               break;
+
+                       case 0:
+                               ig.Emit (OpCodes.Ldc_I4_0);
+                               break;
+
+                       case 1:
+                               ig.Emit (OpCodes.Ldc_I4_1);
+                               break;
+
+                       case 2:
+                               ig.Emit (OpCodes.Ldc_I4_2);
+                               break;
+
+                       case 3:
+                               ig.Emit (OpCodes.Ldc_I4_3);
+                               break;
+
+                       case 4:
+                               ig.Emit (OpCodes.Ldc_I4_4);
+                               break;
+
+                       case 5:
+                               ig.Emit (OpCodes.Ldc_I4_5);
+                               break;
+
+                       case 6:
+                               ig.Emit (OpCodes.Ldc_I4_6);
+                               break;
+
+                       case 7:
+                               ig.Emit (OpCodes.Ldc_I4_7);
+                               break;
+
+                       case 8:
+                               ig.Emit (OpCodes.Ldc_I4_8);
+                               break;
+
+                       default:
+                               if (i >= -128 && i <= 127) {
+                                       ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
+                               } else
+                                       ig.Emit (OpCodes.Ldc_I4, i);
+                               break;
+                       }
                }
 
-               public void BeginScope ()
+               public void EmitLong (long l)
                {
-                       ig.BeginScope();
+                       if (l >= int.MinValue && l <= int.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_I8);
+                               return;
+                       }
 
-                       if (CodeGen.SymbolWriter != null)
-                               CodeGen.SymbolWriter.OpenScope(ig);
+                       if (l >= 0 && l <= uint.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_U8);
+                               return;
+                       }
+
+                       ig.Emit (OpCodes.Ldc_I8, l);
                }
 
-               public void EndScope ()
+               //
+               // Load the object from the pointer.  
+               //
+               public void EmitLoadFromPtr (TypeSpec t)
                {
-                       ig.EndScope();
+                       if (t == TypeManager.int32_type)
+                               ig.Emit (OpCodes.Ldind_I4);
+                       else if (t == TypeManager.uint32_type)
+                               ig.Emit (OpCodes.Ldind_U4);
+                       else if (t == TypeManager.short_type)
+                               ig.Emit (OpCodes.Ldind_I2);
+                       else if (t == TypeManager.ushort_type)
+                               ig.Emit (OpCodes.Ldind_U2);
+                       else if (t == TypeManager.char_type)
+                               ig.Emit (OpCodes.Ldind_U2);
+                       else if (t == TypeManager.byte_type)
+                               ig.Emit (OpCodes.Ldind_U1);
+                       else if (t == TypeManager.sbyte_type)
+                               ig.Emit (OpCodes.Ldind_I1);
+                       else if (t == TypeManager.uint64_type)
+                               ig.Emit (OpCodes.Ldind_I8);
+                       else if (t == TypeManager.int64_type)
+                               ig.Emit (OpCodes.Ldind_I8);
+                       else if (t == TypeManager.float_type)
+                               ig.Emit (OpCodes.Ldind_R4);
+                       else if (t == TypeManager.double_type)
+                               ig.Emit (OpCodes.Ldind_R8);
+                       else if (t == TypeManager.bool_type)
+                               ig.Emit (OpCodes.Ldind_I1);
+                       else if (t == TypeManager.intptr_type)
+                               ig.Emit (OpCodes.Ldind_I);
+                       else if (t.IsEnum) {
+                               if (t == TypeManager.enum_type)
+                                       ig.Emit (OpCodes.Ldind_Ref);
+                               else
+                                       EmitLoadFromPtr (EnumSpec.GetUnderlyingType (t));
+                       } else if (TypeManager.IsStruct (t) || TypeManager.IsGenericParameter (t))
+                               Emit (OpCodes.Ldobj, t);
+                       else if (t.IsPointer)
+                               ig.Emit (OpCodes.Ldind_I);
+                       else
+                               ig.Emit (OpCodes.Ldind_Ref);
+               }
 
-                       if (CodeGen.SymbolWriter != null)
-                               CodeGen.SymbolWriter.CloseScope(ig);
+               //
+               // The stack contains the pointer and the value of type `type'
+               //
+               public void EmitStoreFromPtr (TypeSpec type)
+               {
+                       if (type.IsEnum)
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
+                               ig.Emit (OpCodes.Stind_I4);
+                       else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
+                               ig.Emit (OpCodes.Stind_I8);
+                       else if (type == TypeManager.char_type || type == TypeManager.short_type ||
+                                type == TypeManager.ushort_type)
+                               ig.Emit (OpCodes.Stind_I2);
+                       else if (type == TypeManager.float_type)
+                               ig.Emit (OpCodes.Stind_R4);
+                       else if (type == TypeManager.double_type)
+                               ig.Emit (OpCodes.Stind_R8);
+                       else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
+                                type == TypeManager.bool_type)
+                               ig.Emit (OpCodes.Stind_I1);
+                       else if (type == TypeManager.intptr_type)
+                               ig.Emit (OpCodes.Stind_I);
+                       else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
+                               ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
+                       else
+                               ig.Emit (OpCodes.Stind_Ref);
                }
 
                /// <summary>
                ///   Returns a temporary storage for a variable of type t as 
                ///   a local variable in the current body.
                /// </summary>
-               public LocalBuilder GetTemporaryLocal (Type t)
+               public LocalBuilder GetTemporaryLocal (TypeSpec t)
                {
-                       LocalBuilder location = null;
-                       
-                       if (temporary_storage != null){
-                               object o = temporary_storage [t];
-                               if (o != null){
-                                       if (o is ArrayList){
-                                               ArrayList al = (ArrayList) o;
-                                               
-                                               for (int i = 0; i < al.Count; i++){
-                                                       if (al [i] != null){
-                                                               location = (LocalBuilder) al [i];
-                                                               al [i] = null;
-                                                               break;
-                                                       }
-                                               }
-                                       } else
-                                               location = (LocalBuilder) o;
-                                       if (location != null)
-                                               return location;
+                       if (temporary_storage != null) {
+                               object o;
+                               if (temporary_storage.TryGetValue (t, out o)) {
+                                       if (o is Stack<LocalBuilder>) {
+                                               var s = (Stack<LocalBuilder>) o;
+                                               o = s.Count == 0 ? null : s.Pop ();
+                                       } else {
+                                               temporary_storage.Remove (t);
+                                       }
                                }
+                               if (o != null)
+                                       return (LocalBuilder) o;
                        }
-                       
-                       return ig.DeclareLocal (t);
+                       return DeclareLocal (t, false);
                }
 
-               public void FreeTemporaryLocal (LocalBuilder b, Type t)
+               public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
                {
-                       if (temporary_storage == null){
-                               temporary_storage = new Hashtable ();
-                               temporary_storage [t] = b;
+                       if (temporary_storage == null) {
+                               temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
+                               temporary_storage.Add (t, b);
                                return;
                        }
-                       object o = temporary_storage [t];
-                       if (o == null){
-                               temporary_storage [t] = b;
+                       object o;
+                       
+                       if (!temporary_storage.TryGetValue (t, out o)) {
+                               temporary_storage.Add (t, b);
                                return;
                        }
-                       if (o is ArrayList){
-                               ArrayList al = (ArrayList) o;
-                               for (int i = 0; i < al.Count; i++){
-                                       if (al [i] == null){
-                                               al [i] = b;
-                                               return;
-                                       }
-                               }
-                               al.Add (b);
-                               return;
+                       var s = o as Stack<LocalBuilder>;
+                       if (s == null) {
+                               s = new Stack<LocalBuilder> ();
+                               s.Push ((LocalBuilder)o);
+                               temporary_storage [t] = s;
                        }
-                       ArrayList replacement = new ArrayList ();
-                       replacement.Add (o);
-                       temporary_storage.Remove (t);
-                       temporary_storage [t] = replacement;
+                       s.Push (b);
                }
 
-               /// <summary>
-               ///   Current loop begin and end labels.
-               /// </summary>
-               public Label LoopBegin, LoopEnd;
-
-               /// <summary>
-               ///   Default target in a switch statement.   Only valid if
-               ///   InSwitch is true
-               /// </summary>
-               public Label DefaultTarget;
-
-               /// <summary>
-               ///   If this is non-null, points to the current switch statement
-               /// </summary>
-               public Switch Switch;
-
                /// <summary>
                ///   ReturnValue creates on demand the LocalBuilder for the
                ///   return value from the function.  By default this is not
@@ -873,112 +818,23 @@ namespace Mono.CSharp {
                public LocalBuilder TemporaryReturn ()
                {
                        if (return_value == null){
-                               return_value = ig.DeclareLocal (ReturnType);
+                               return_value = DeclareLocal (return_type, false);
                                if (!HasReturnLabel){
-                                       ReturnLabel = ig.DefineLabel ();
+                                       ReturnLabel = DefineLabel ();
                                        HasReturnLabel = true;
                                }
                        }
 
                        return return_value;
                }
-
-               /// <summary>
-               ///   This method is used during the Resolution phase to flag the
-               ///   need to define the ReturnLabel
-               /// </summary>
-               public void NeedReturnLabel ()
-               {
-                       if (current_phase != Phase.Resolving){
-                               //
-                               // The reason is that the `ReturnLabel' is declared between
-                               // resolution and emission
-                               // 
-                               throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
-                       }
-                       
-                       if (!InIterator && !HasReturnLabel) 
-                               HasReturnLabel = true;
-               }
-
-               //
-               // Emits the proper object to address fields on a remapped
-               // variable/parameter to field in anonymous-method/iterator proxy classes.
-               //
-               public void EmitThis (bool need_address)
-               {
-                       ig.Emit (OpCodes.Ldarg_0);
-                       if (capture_context != null && CurrentAnonymousMethod != null){
-                               ScopeInfo si = CurrentAnonymousMethod.Scope;
-                               while (si != null){
-                                       if (si.ParentLink != null)
-                                               ig.Emit (OpCodes.Ldfld, si.ParentLink);
-                                       if (si.THIS != null){
-                                               if (need_address && TypeManager.IsValueType (si.THIS.FieldType))
-                                                       ig.Emit (OpCodes.Ldflda, si.THIS);
-                                               else
-                                                       ig.Emit (OpCodes.Ldfld, si.THIS);
-                                               break;
-                                       }
-                                       si = si.ParentScope;
-                               }
-                       } 
-               }
-
-               //
-               // Emits the code necessary to load the instance required
-               // to access the captured LocalInfo
-               //
-               public void EmitCapturedVariableInstance (LocalInfo li)
-               {
-                       if (capture_context == null)
-                               throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
-                       
-                       capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
-               }
-
-               public void EmitParameter (string name, bool leave_copy, bool prepared, ref LocalTemporary temp)
-               {
-                       capture_context.EmitParameter (this, name, leave_copy, prepared, ref temp);
-               }
-
-               public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load, ref LocalTemporary  temp)
-               {
-                       capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load, ref temp);
-               }
-
-               public void EmitAddressOfParameter (string name)
-               {
-                       capture_context.EmitAddressOfParameter (this, name);
-               }
-               
-               public Expression GetThis (Location loc)
-               {
-                       This my_this;
-                       if (CurrentBlock != null)
-                               my_this = new This (CurrentBlock, loc);
-                       else
-                               my_this = new This (loc);
-
-                       if (!my_this.ResolveBase (this))
-                               my_this = null;
-
-                       return my_this;
-               }
        }
 
-
-       public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
-
-               protected CommonAssemblyModulClass ():
-                       base (null)
-               {
-               }
-
-               public void AddAttributes (ArrayList attrs)
+       public abstract class CommonAssemblyModulClass : Attributable, IMemberContext
+       {
+               public void AddAttributes (List<Attribute> attrs, IMemberContext context)
                {
                        foreach (Attribute a in attrs)
-                               a.AttachTo (this);
+                               a.AttachTo (this, context);
 
                        if (attributes == null) {
                                attributes = new Attributes (attrs);
@@ -994,16 +850,9 @@ namespace Mono.CSharp {
 
                        OptAttributes.Emit ();
                }
-                
-               protected Attribute ResolveAttribute (Type a_type)
-               {
-                       if (OptAttributes == null)
-                               return null;
-
-                       // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
-                       if (!OptAttributes.CheckTargets ())
-                               return null;
 
+               protected Attribute ResolveAttribute (PredefinedAttribute a_type)
+               {
                        Attribute a = OptAttributes.Search (a_type);
                        if (a != null) {
                                a.Resolve ();
@@ -1011,30 +860,58 @@ namespace Mono.CSharp {
                        return a;
                }
 
-               public override IResolveContext ResolveContext {
-                       get {
-                               return this;
-                       }
+               #region IMemberContext Members
+
+               public CompilerContext Compiler {
+                       get { return RootContext.ToplevelTypes.Compiler; }
                }
 
-               #region IResolveContext Members
+               public TypeSpec CurrentType {
+                       get { return null; }
+               }
 
-               public DeclSpace DeclContainer {
-                       get {
-                               return RootContext.Tree.Types;
-                       }
+               public TypeParameter[] CurrentTypeParameters {
+                       get { return null; }
                }
 
-               public bool IsInObsoleteScope {
-                       get {
-                               return false;
-                       }
+               public MemberCore CurrentMemberDefinition {
+                       get { return RootContext.ToplevelTypes; }
                }
 
-               public bool IsInUnsafeScope {
-                       get {
-                               return false;
-                       }
+               public string GetSignatureForError ()
+               {
+                       return "<module>";
+               }
+
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
+               public bool IsObsolete {
+                       get { return false; }
+               }
+
+               public bool IsUnsafe {
+                       get { return false; }
+               }
+
+               public bool IsStatic {
+                       get { return false; }
+               }
+
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
+               {
+                       return RootContext.ToplevelTypes.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
+               }
+
+               public FullNamedExpression LookupNamespaceAlias (string name)
+               {
+                       return null;
                }
 
                #endregion
@@ -1048,16 +925,26 @@ namespace Mono.CSharp {
 
                public Attribute ClsCompliantAttribute;
 
-               ListDictionary declarative_security;
+               Dictionary<SecurityAction, PermissionSet> declarative_security;
+               bool has_extension_method;              
+               public AssemblyName Name;
+               MethodInfo add_type_forwarder;
+               Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
 
                // Module is here just because of error messages
                static string[] attribute_targets = new string [] { "assembly", "module" };
 
-               public AssemblyClass (): base ()
+               public AssemblyClass ()
                {
                        wrap_non_exception_throws = true;
                }
 
+               public bool HasExtensionMethods {
+                       set {
+                               has_extension_method = value;
+                       }
+               }
+
                public bool IsClsCompliant {
                        get {
                                return is_cls_compliant;
@@ -1081,21 +968,59 @@ namespace Mono.CSharp {
                        return is_cls_compliant;
                }
 
+               Report Report {
+                       get { return Compiler.Report; }
+               }
+
                public void Resolve ()
                {
-                       ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
+                       if (RootContext.Unsafe) {
+                               //
+                               // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
+                               // when -unsafe option was specified
+                               //
+                               
+                               Location loc = Location.Null;
+
+                               MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
+                                       new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
+
+                               Arguments pos = new Arguments (1);
+                               pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
+
+                               Arguments named = new Arguments (1);
+                               named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (true, loc)));
+
+                               GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
+                                       new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
+                                       new Arguments[] { pos, named }, loc, false);
+                               g.AttachTo (this, this);
+
+                               if (g.Resolve () != null) {
+                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
+                                       g.ExtractSecurityPermissionSet (declarative_security);
+                               }
+                       }
+
+                       if (OptAttributes == null)
+                               return;
+
+                       // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
+                       if (!OptAttributes.CheckTargets())
+                               return;
+
+                       ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
+
                        if (ClsCompliantAttribute != null) {
                                is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
                        }
 
-#if NET_2_0
-                       Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
+                       Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
                        if (a != null) {
-                               object val = a.GetPropertyValue ("WrapNonExceptionThrows");
+                               var val = a.GetPropertyValue ("WrapNonExceptionThrows") as BoolConstant;
                                if (val != null)
-                                       wrap_non_exception_throws = (bool)val;
+                                       wrap_non_exception_throws = val.Value;
                        }
-#endif
                }
 
                // fix bug #56621
@@ -1142,43 +1067,41 @@ namespace Mono.CSharp {
                                        //       are loaded yet.
                                        // TODO: Does not handle quoted attributes properly
                                        switch (a.Name) {
-                                               case "AssemblyKeyFile":
-                                               case "AssemblyKeyFileAttribute":
-                                               case "System.Reflection.AssemblyKeyFileAttribute":
-                                                       if (RootContext.StrongNameKeyFile != null) {
-                                                               Report.SymbolRelatedToPreviousError (a.Location, a.Name);
-                                                               Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
-                                    "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
-                                                       }
-                                                       else {
-                                                               string value = a.GetString ();
-                                                               if (value.Length != 0)
-                                                                       RootContext.StrongNameKeyFile = value;
-                                                       }
-                                                       break;
-                                               case "AssemblyKeyName":
-                                               case "AssemblyKeyNameAttribute":
-                                               case "System.Reflection.AssemblyKeyNameAttribute":
-                                                       if (RootContext.StrongNameKeyContainer != null) {
-                                                               Report.SymbolRelatedToPreviousError (a.Location, a.Name);
-                                                               Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+                                       case "AssemblyKeyFile":
+                                       case "AssemblyKeyFileAttribute":
+                                       case "System.Reflection.AssemblyKeyFileAttribute":
+                                               if (RootContext.StrongNameKeyFile != null) {
+                                                       Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
+                                                       Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+                                                                       "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
+                                               } else {
+                                                       string value = a.GetString ();
+                                                       if (value != null && value.Length != 0)
+                                                               RootContext.StrongNameKeyFile = value;
+                                               }
+                                               break;
+                                       case "AssemblyKeyName":
+                                       case "AssemblyKeyNameAttribute":
+                                       case "System.Reflection.AssemblyKeyNameAttribute":
+                                               if (RootContext.StrongNameKeyContainer != null) {
+                                                       Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
+                                                       Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
                                                                        "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
-                                                       }
-                                                       else {
-                                                               string value = a.GetString ();
-                                                               if (value.Length != 0)
-                                                                       RootContext.StrongNameKeyContainer = value;
-                                                       }
-                                                       break;
-                                               case "AssemblyDelaySign":
-                                               case "AssemblyDelaySignAttribute":
-                                               case "System.Reflection.AssemblyDelaySignAttribute":
-                                                       RootContext.StrongNameDelaySign = a.GetBoolean ();
-                                                       break;
+                                               } else {
+                                                       string value = a.GetString ();
+                                                       if (value != null && value.Length != 0)
+                                                               RootContext.StrongNameKeyContainer = value;
+                                               }
+                                               break;
+                                       case "AssemblyDelaySign":
+                                       case "AssemblyDelaySignAttribute":
+                                       case "System.Reflection.AssemblyDelaySignAttribute":
+                                               RootContext.StrongNameDelaySign = a.GetBoolean ();
+                                               break;
                                        }
                                }
                        }
-
+                       
                        AssemblyName an = new AssemblyName ();
                        an.Name = Path.GetFileNameWithoutExtension (name);
 
@@ -1248,17 +1171,68 @@ namespace Mono.CSharp {
                        Report.Error (1548, "Error during assembly signing. " + text);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
+               bool CheckInternalsVisibleAttribute (Attribute a)
                {
-                       if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
+                       string assembly_name = a.GetString ();
+                       if (assembly_name.Length == 0)
+                               return false;
+                               
+                       AssemblyName aname = null;
+                       try {
+                               aname = new AssemblyName (assembly_name);
+                       } catch (FileLoadException) {
+                       } catch (ArgumentException) {
+                       }
+                               
+                       // Bad assembly name format
+                       if (aname == null)
+                               Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
+                       // Report error if we have defined Version or Culture
+                       else if (aname.Version != null || aname.CultureInfo != null)
+                               throw new Exception ("Friend assembly `" + a.GetString () + 
+                                               "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
+                       else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
+                               Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
+                                               " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
+                               return false;
+                       }
+
+                       return true;
+               }
+
+               static string IsValidAssemblyVersion (string version)
+               {
+                       Version v;
+                       try {
+                               v = new Version (version);
+                       } catch {
+                               try {
+                                       int major = int.Parse (version, CultureInfo.InvariantCulture);
+                                       v = new Version (major, 0);
+                               } catch {
+                                       return null;
+                               }
+                       }
+
+                       foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
+                               if (candidate > ushort.MaxValue)
+                                       return null;
+                       }
+
+                       return new Version (v.Major, System.Math.Max (0, v.Minor), System.Math.Max (0, v.Build), System.Math.Max (0, v.Revision)).ToString (4);
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+               {
+                       if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null)
-                                       declarative_security = new ListDictionary ();
+                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
 
                                a.ExtractSecurityPermissionSet (declarative_security);
                                return;
                        }
 
-                       if (a.Type == TypeManager.assembly_culture_attribute_type) {
+                       if (a.Type == pa.AssemblyCulture) {
                                string value = a.GetString ();
                                if (value == null || value.Length == 0)
                                        return;
@@ -1267,15 +1241,151 @@ namespace Mono.CSharp {
                                        a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
                                        return;
                                }
+
+                               try {
+                                       var fi = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+                                       fi.SetValue (CodeGen.Assembly.Builder, value == "neutral" ? "" : value);
+                               } catch {
+                                       Report.RuntimeMissingSupport (a.Location, "AssemblyCultureAttribute setting");
+                               }
+
+                               return;
+                       }
+
+                       if (a.Type == pa.AssemblyVersion) {
+                               string value = a.GetString ();
+                               if (value == null || value.Length == 0)
+                                       return;
+
+                               var vinfo = IsValidAssemblyVersion (value.Replace ('*', '0'));
+                               if (vinfo == null) {
+                                       a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
+                                       return;
+                               }
+
+                               try {
+                                       var fi = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+                                       fi.SetValue (CodeGen.Assembly.Builder, vinfo);
+                               } catch {
+                                       Report.RuntimeMissingSupport (a.Location, "AssemblyVersionAttribute setting");
+                               }
+
+                               return;
+                       }
+
+                       if (a.Type == pa.AssemblyAlgorithmId) {
+                               const int pos = 2; // skip CA header
+                               uint alg = (uint) cdata [pos];
+                               alg |= ((uint) cdata [pos + 1]) << 8;
+                               alg |= ((uint) cdata [pos + 2]) << 16;
+                               alg |= ((uint) cdata [pos + 3]) << 24;
+
+                               try {
+                                       var fi = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+                                       fi.SetValue (CodeGen.Assembly.Builder, alg);
+                               } catch {
+                                       Report.RuntimeMissingSupport (a.Location, "AssemblyAlgorithmIdAttribute setting");
+                               }
+
+                               return;
+                       }
+
+                       if (a.Type == pa.AssemblyFlags) {
+                               const int pos = 2; // skip CA header
+                               uint flags = (uint) cdata[pos];
+                               flags |= ((uint) cdata[pos + 1]) << 8;
+                               flags |= ((uint) cdata[pos + 2]) << 16;
+                               flags |= ((uint) cdata[pos + 3]) << 24;
+
+                               // Ignore set PublicKey flag if assembly is not strongnamed
+                               if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && (CodeGen.Assembly.Builder.GetName ().KeyPair == null))
+                                       flags &= ~(uint)AssemblyNameFlags.PublicKey;
+
+                               try {
+                                       var fi = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+                                       fi.SetValue (CodeGen.Assembly.Builder, flags);
+                               } catch {
+                                       Report.RuntimeMissingSupport (a.Location, "AssemblyFlagsAttribute setting");
+                               }
+
+                               return;
+                       }
+
+                       if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
+                               return;
+
+                       if (a.Type == pa.TypeForwarder) {
+                               TypeSpec t = a.GetArgumentType ();
+                               if (t == null || TypeManager.HasElementType (t)) {
+                                       Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
+                                       return;
+                               }
+
+                               if (emitted_forwarders == null) {
+                                       emitted_forwarders = new Dictionary<ITypeDefinition, Attribute>  ();
+                               } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
+                                       Report.SymbolRelatedToPreviousError(emitted_forwarders[t.MemberDefinition].Location, null);
+                                       Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
+                                               TypeManager.CSharpName(t));
+                                       return;
+                               }
+
+                               emitted_forwarders.Add(t.MemberDefinition, a);
+
+                               if (t.Assembly == Builder) {
+                                       Report.SymbolRelatedToPreviousError (t);
+                                       Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
+                                               TypeManager.CSharpName (t));
+                                       return;
+                               }
+
+                               if (t.IsNested) {
+                                       Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
+                                               TypeManager.CSharpName (t));
+                                       return;
+                               }
+
+                               if (add_type_forwarder == null) {
+                                       add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
+                                               BindingFlags.NonPublic | BindingFlags.Instance);
+
+                                       if (add_type_forwarder == null) {
+                                               Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
+                                               return;
+                                       }
+                               }
+
+                               add_type_forwarder.Invoke (Builder, new object[] { t.GetMetaInfo () });
+                               return;
+                       }
+                       
+                       if (a.Type == pa.Extension) {
+                               a.Error_MisusedExtensionAttribute ();
+                               return;
                        }
 
-                       Builder.SetCustomAttribute (customBuilder);
+                       Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override void Emit (TypeContainer tc)
                {
                        base.Emit (tc);
 
+                       if (has_extension_method)
+                               PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
+
+                       // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
+                       PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
+                       if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
+                               var ci = TypeManager.GetPredefinedConstructor (pa.Type, Location.Null, TypeSpec.EmptyTypes);
+                               PropertyInfo [] pis = new PropertyInfo [1];
+                               pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
+                                       "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type).MetaInfo;
+                               object [] pargs = new object [1];
+                               pargs [0] = true;
+                               Builder.SetCustomAttribute (new CustomAttributeBuilder ((ConstructorInfo) ci.GetMetaInfo (), new object[0], pis, pargs));
+                       }
+
                        if (declarative_security != null) {
 
                                MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
@@ -1284,16 +1394,17 @@ namespace Mono.CSharp {
                                try {
                                        // Microsoft runtime hacking
                                        if (add_permission == null) {
-                                               Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
+                                               var assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
                                                add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
 
                                                FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                                                builder_instance = fi.GetValue (Builder);
                                        }
 
-                                       object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
-                                                                                                 declarative_security [SecurityAction.RequestOptional],
-                                                                                                 declarative_security [SecurityAction.RequestRefuse] };
+                                       var args = new PermissionSet [3];
+                                       declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args [0]);
+                                       declarative_security.TryGetValue (SecurityAction.RequestOptional, out args [1]);
+                                       declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args [2]);
                                        add_permission.Invoke (builder_instance, args);
                                }
                                catch {
@@ -1307,96 +1418,29 @@ namespace Mono.CSharp {
                                return attribute_targets;
                        }
                }
-       }
-
-       public class ModuleClass : CommonAssemblyModulClass {
-               // TODO: make it private and move all builder based methods here
-               public ModuleBuilder Builder;
-               bool m_module_is_unsafe;
-
-               public CharSet DefaultCharSet = CharSet.Ansi;
-               public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
-
-               static string[] attribute_targets = new string [] { "module" };
-
-               public ModuleClass (bool is_unsafe)
-               {
-                       m_module_is_unsafe = is_unsafe;
-               }
-
-               public override AttributeTargets AttributeTargets {
-                       get {
-                               return AttributeTargets.Module;
-                       }
-               }
-
-               public override bool IsClsComplianceRequired ()
-               {
-                       return CodeGen.Assembly.IsClsCompliant;
-               }
-
-               public override void Emit (TypeContainer tc) 
-               {
-                       base.Emit (tc);
-
-                       if (!m_module_is_unsafe)
-                               return;
 
-                       if (TypeManager.unverifiable_code_ctor == null) {
-                               Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
-                               return;
+               // Wrapper for AssemblyBuilder.AddModule
+               static MethodInfo adder_method;
+               static public MethodInfo AddModule_Method {
+                       get {
+                               if (adder_method == null)
+                                       adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
+                               return adder_method;
                        }
-                               
-                       Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
                }
-                
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
+               public Module AddModule (string module)
                {
-                       if (a.Type == TypeManager.cls_compliant_attribute_type) {
-                               if (CodeGen.Assembly.ClsCompliantAttribute == null) {
-                                       Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
-                               }
-                               else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
-                                       Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
-                                       Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
-                                       return;
-                               }
-                       }
-
-                       Builder.SetCustomAttribute (customBuilder);
-               }
-
-               /// <summary>
-               /// It is called very early therefore can resolve only predefined attributes
-               /// </summary>
-               public void ResolveAttributes ()
-               {
-#if NET_2_0
-                       Attribute a = ResolveAttribute (TypeManager.default_charset_type);
-                       if (a != null) {
-                               DefaultCharSet = a.GetCharSetValue ();
-                               switch (DefaultCharSet) {
-                                       case CharSet.Ansi:
-                                       case CharSet.None:
-                                               break;
-                                       case CharSet.Auto:
-                                               DefaultCharSetType = TypeAttributes.AutoClass;
-                                               break;
-                                       case CharSet.Unicode:
-                                               DefaultCharSetType = TypeAttributes.UnicodeClass;
-                                               break;
-                                       default:
-                                               Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
-                                               break;
-                               }
+                       MethodInfo m = AddModule_Method;
+                       if (m == null) {
+                               Report.RuntimeMissingSupport (Location.Null, "/addmodule");
+                               Environment.Exit (1);
                        }
-#endif
-               }
 
-               public override string[] ValidAttributeTargets {
-                       get {
-                               return attribute_targets;
+                       try {
+                               return (Module) m.Invoke (Builder, new object [] { module });
+                       } catch (TargetInvocationException ex) {
+                               throw ex.InnerException;
                        }
-               }
+               }               
        }
 }