New tests.
[mono.git] / mcs / mcs / codegen.cs
index c1f988ab1b69da6d8d3dd34bd6f00c6084ef59c3..d7c7233499ce1be5c8e656c96c8d2a4aeece2624 100644 (file)
@@ -19,8 +19,7 @@
 
 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;
@@ -91,13 +90,13 @@ namespace Mono.CSharp {
                //
                // Initializes the code generator variables for interactive use (repl)
                //
-               static public void InitDynamic (string name)
+               static public void InitDynamic (CompilerContext ctx, string name)
                {
                        current_domain = AppDomain.CurrentDomain;
                        AssemblyName an = Assembly.GetAssemblyName (name, name);
                        
                        Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
-                       RootContext.ToplevelTypes = new ModuleContainer (true);
+                       RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
                        RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
                        Assembly.Name = Assembly.Builder.GetName ();
                }
@@ -105,7 +104,7 @@ namespace Mono.CSharp {
                //
                // 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);
@@ -119,7 +118,7 @@ namespace Mono.CSharp {
                                        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.");
@@ -137,7 +136,7 @@ namespace Mono.CSharp {
                        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);
                                }
@@ -145,7 +144,7 @@ namespace Mono.CSharp {
                        }
                        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;
@@ -170,13 +169,13 @@ namespace Mono.CSharp {
 #if !MS_COMPATIBLE
                                // TODO: We should use SymbolWriter from DefineDynamicModule
                                if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
-                                       Report.Error (40, "Unexpected debug information initialization error `{0}'",
+                                       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) {
-                               Report.Error (40, "Unexpected debug information initialization error `{0}'",
+                               ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
                                        e.Message);
                                return false;
                        }
@@ -184,9 +183,8 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static public void Save (string name, bool saveDebugInfo)
+               static public void Save (string name, bool saveDebugInfo, Report Report)
                {
-#if GMCS_SOURCE
                        PortableExecutableKinds pekind;
                        ImageFileMachine machine;
 
@@ -209,13 +207,8 @@ namespace Mono.CSharp {
                                machine = ImageFileMachine.I386;
                                break;
                        }
-#endif
                        try {
-#if GMCS_SOURCE
                                Assembly.Builder.Save (Basename (name), pekind, machine);
-#else
-                               Assembly.Builder.Save (Basename (name));
-#endif
                        }
                        catch (COMException) {
                                if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
@@ -247,249 +240,27 @@ namespace Mono.CSharp {
                        }
        }
 
-
-       /// <summary>
-       /// An interface to hold all the information needed in the resolving phase.
-       /// </summary>
-       public interface IMemberContext
-       {
-               //
-               // A scope type context, it can be inflated for generic types
-               //
-               Type CurrentType { get; }
-
-               //
-               // A scope type parameters either VAR or MVAR
-               //
-               TypeParameter[] CurrentTypeParameters { get; }
-
-               //
-               // A type definition of the type context. For partial types definition use
-               // CurrentTypeDefinition.PartialContainer otherwise the context is local
-               //
-               // TODO: CurrentType.Definition
-               //
-               TypeContainer CurrentTypeDefinition { get; }
-
-               bool IsObsolete { get; }
-               bool IsUnsafe { get; }
-               bool IsStatic { get; }
-
-               ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
-               FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
-               FullNamedExpression LookupNamespaceAlias (string name);
-       }
-
-       //
-       // Block or statement resolving context
-       //
-       public class BlockContext : ResolveContext
-       {
-               FlowBranching current_flow_branching;
-
-               public TypeInferenceContext ReturnTypeInference;
-
-               Type return_type;
-
-               /// <summary>
-               ///   The location where return has to jump to return the
-               ///   value
-               /// </summary>
-               public Label ReturnLabel;
-
-               /// <summary>
-               ///   If we already defined the ReturnLabel
-               /// </summary>
-               public bool HasReturnLabel;
-
-               public BlockContext (IMemberContext mc, ExplicitBlock block, Type returnType)
-                       : base (mc)
-               {
-                       if (returnType == null)
-                               throw new ArgumentNullException ("returnType");
-
-                       this.return_type = returnType;
-
-                       // TODO: check for null value
-                       CurrentBlock = block;
-               }
-
-               public override FlowBranching CurrentBranching {
-                       get { return current_flow_branching; }
-               }
-
-               // <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)
-               {
-                       current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
-                       return current_flow_branching;
-               }
-
-               // <summary>
-               //   Starts a new code branching for block `block'.
-               // </summary>
-               public FlowBranching StartFlowBranching (Block block)
-               {
-                       Set (Options.DoFlowAnalysis);
-
-                       current_flow_branching = FlowBranching.CreateBranching (
-                               CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
-                       return current_flow_branching;
-               }
-
-               public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
-               {
-                       FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
-                       current_flow_branching = branching;
-                       return branching;
-               }
-
-               public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
-               {
-                       FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
-                       current_flow_branching = branching;
-                       return branching;
-               }
-
-               public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
-               {
-                       FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
-                       current_flow_branching = branching;
-                       return branching;
-               }
-
-               public FlowBranchingIterator StartFlowBranching (Iterator iterator)
-               {
-                       FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
-                       current_flow_branching = branching;
-                       return branching;
-               }
-
-               public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt, FlowBranching parent)
-               {
-                       FlowBranchingToplevel branching = new FlowBranchingToplevel (parent, stmt);
-                       current_flow_branching = branching;
-                       return branching;
-               }
-
-               // <summary>
-               //   Ends a code branching.  Merges the state of locals and parameters
-               //   from all the children of the ending branching.
-               // </summary>
-               public bool EndFlowBranching ()
-               {
-                       FlowBranching old = current_flow_branching;
-                       current_flow_branching = current_flow_branching.Parent;
-
-                       FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
-                       return vector.IsUnreachable;
-               }
-
-               // <summary>
-               //   Kills the current code branching.  This throws away any changed state
-               //   information and should only be used in case of an error.
-               // </summary>
-               // FIXME: this is evil
-               public void KillFlowBranching ()
-               {
-                       current_flow_branching = current_flow_branching.Parent;
-               }
-
-               //
-               // This method is used during the Resolution phase to flag the
-               // need to define the ReturnLabel
-               //
-               public void NeedReturnLabel ()
-               {
-                       if (!HasReturnLabel)
-                               HasReturnLabel = true;
-               }
-
-               public Type ReturnType {
-                       get { return return_type; }
-               }
-       }
-
        /// <summary>
        ///   An Emit Context is created for each body of code (from methods,
        ///   properties bodies, indexer bodies or constructor bodies)
        /// </summary>
-       public class EmitContext {
-
-               [Flags]
-               public enum Options
-               {
-                       /// <summary>
-                       ///   This flag 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>
-                       CheckedScope = 1 << 0,
-
-                       /// <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>
-                       ConstantCheckState = 1 << 1,
-
-                       AllCheckStateFlags = CheckedScope | ConstantCheckState,
-
-                       OmitDebugInfo = 1 << 2,
-
-                       ConstructorScope = 1 << 3
-               }
-
-               // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
-               // it's public so that we can use a struct at the callsite
-               public struct FlagsHandle : IDisposable
-               {
-                       EmitContext ec;
-                       readonly Options invmask, oldval;
-
-                       public FlagsHandle (EmitContext ec, Options flagsToSet)
-                               : this (ec, flagsToSet, flagsToSet)
-                       {
-                       }
-
-                       internal FlagsHandle (EmitContext ec, Options mask, Options val)
-                       {
-                               this.ec = ec;
-                               invmask = ~mask;
-                               oldval = ec.flags & mask;
-                               ec.flags = (ec.flags & invmask) | (val & mask);
-                       }
-
-                       public void Dispose ()
-                       {
-                               ec.flags = (ec.flags & invmask) | oldval;
-                       }
-               }
-
-               Options flags;
-
+       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>
-               protected Type return_type;
+               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;
+               Dictionary<TypeSpec, object> temporary_storage;
 
                /// <summary>
                ///   The location where we store the return value.
@@ -507,6 +278,22 @@ namespace Mono.CSharp {
                /// </summary>
                public bool HasReturnLabel;
 
+               /// <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>
                ///  Whether we are inside an anonymous method.
                /// </summary>
@@ -514,7 +301,7 @@ namespace Mono.CSharp {
                
                public readonly IMemberContext MemberContext;
 
-               public EmitContext (IMemberContext rc, ILGenerator ig, Type return_type)
+               public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
                {
                        this.MemberContext = rc;
                        this.ig = ig;
@@ -522,7 +309,9 @@ namespace Mono.CSharp {
                        this.return_type = return_type;
                }
 
-               public Type CurrentType {
+#region Properties
+
+               public TypeSpec CurrentType {
                        get { return MemberContext.CurrentType; }
                }
 
@@ -530,30 +319,33 @@ namespace Mono.CSharp {
                        get { return MemberContext.CurrentTypeParameters; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return MemberContext.CurrentTypeDefinition; }
+               public MemberCore CurrentTypeDefinition {
+                       get { return MemberContext.CurrentMemberDefinition; }
                }
 
-               public bool HasSet (Options options)
-               {
-                       return (this.flags & options) == options;
+               public bool IsStatic {
+                       get { return MemberContext.IsStatic; }
                }
 
-               // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
-               public FlagsHandle With (Options options, bool enable)
-               {
-                       return new FlagsHandle (this, options, enable ? options : 0);
+               bool IsAnonymousStoreyMutateRequired {
+                       get {
+                               return CurrentAnonymousMethod != null &&
+                                       CurrentAnonymousMethod.Storey != null &&
+                                       CurrentAnonymousMethod.Storey.Mutator != null;
+                       }
                }
-               
-               public bool IsStatic {
-                       get { return MemberContext.IsStatic; }
+
+               // Has to be used for emitter errors only
+               public Report Report {
+                       get { return MemberContext.Compiler.Report; }
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
                                return return_type;
                        }
                }
+#endregion
 
                /// <summary>
                ///   This is called immediately before emitting an IL opcode to tell the symbol
@@ -572,396 +364,466 @@ namespace Mono.CSharp {
                        SymbolWriter.DefineLocalVariable (name, builder);
                }
 
+               public void BeginCatchBlock (TypeSpec type)
+               {
+                       ig.BeginCatchBlock (type.GetMetaInfo ());
+               }
+
+               public void BeginExceptionBlock ()
+               {
+                       ig.BeginExceptionBlock ();
+               }
+
+               public void BeginFinallyBlock ()
+               {
+                       ig.BeginFinallyBlock ();
+               }
+
                public void BeginScope ()
                {
                        ig.BeginScope();
                        SymbolWriter.OpenScope(ig);
                }
 
+               public void EndExceptionBlock ()
+               {
+                       ig.EndExceptionBlock ();
+               }
+
                public void EndScope ()
                {
                        ig.EndScope();
                        SymbolWriter.CloseScope(ig);
                }
 
-               /// <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 DeclareLocal (TypeSpec type, bool pinned)
                {
-                       if (temporary_storage != null) {
-                               object o = temporary_storage [t];
-                               if (o != null) {
-                                       if (o is Stack) {
-                                               Stack s = (Stack) o;
-                                               o = s.Count == 0 ? null : s.Pop ();
-                                       } else {
-                                               temporary_storage.Remove (t);
-                                       }
-                               }
-                               if (o != null)
-                                       return (LocalBuilder) o;
-                       }
-                       return ig.DeclareLocal (t);
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+                       return ig.DeclareLocal (type.GetMetaInfo (), pinned);
                }
 
-               public void FreeTemporaryLocal (LocalBuilder b, Type t)
+               public Label DefineLabel ()
                {
-                       if (temporary_storage == null) {
-                               temporary_storage = new Hashtable ();
-                               temporary_storage [t] = b;
-                               return;
-                       }
-                       object o = temporary_storage [t];
-                       if (o == null) {
-                               temporary_storage [t] = b;
-                               return;
-                       }
-                       Stack s = o as Stack;
-                       if (s == null) {
-                               s = new Stack ();
-                               s.Push (o);
-                               temporary_storage [t] = s;
-                       }
-                       s.Push (b);
+                       return ig.DefineLabel ();
                }
 
-               /// <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
-               ///   used.  This is only required when returns are found inside
-               ///   Try or Catch statements.
-               ///
-               ///   This method is typically invoked from the Emit phase, so
-               ///   we allow the creation of a return label if it was not
-               ///   requested during the resolution phase.   Could be cleaned
-               ///   up, but it would replicate a lot of logic in the Emit phase
-               ///   of the code that uses it.
-               /// </summary>
-               public LocalBuilder TemporaryReturn ()
+               public void MarkLabel (Label label)
                {
-                       if (return_value == null){
-                               return_value = ig.DeclareLocal (return_type);
-                               if (!HasReturnLabel){
-                                       ReturnLabel = ig.DefineLabel ();
-                                       HasReturnLabel = true;
-                               }
-                       }
-
-                       return return_value;
+                       ig.MarkLabel (label);
                }
-       }
 
-       public class ResolveContext : IMemberContext
-       {
-               [Flags]
-               public enum Options
+               public void Emit (OpCode opcode)
                {
-                       /// <summary>
-                       ///   This flag 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>
-                       CheckedScope = 1 << 0,
-
-                       /// <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>
-                       ConstantCheckState = 1 << 1,
-
-                       AllCheckStateFlags = CheckedScope | ConstantCheckState,
-
-                       //
-                       // unsafe { ... } scope
-                       //
-                       UnsafeScope = 1 << 2,
-                       CatchScope = 1 << 3,
-                       FinallyScope = 1 << 4,
-                       FieldInitializerScope = 1 << 5,
-                       CompoundAssignmentScope = 1 << 6,
-                       FixedInitializerScope = 1 << 7,
-                       BaseInitializer = 1 << 8,
-
-                       //
-                       // 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
-                       //
-                       EnumScope = 1 << 9,
-
-                       ConstantScope = 1 << 10,
-
-                       ConstructorScope = 1 << 11,
-
-                       /// <summary>
-                       ///   Whether control flow analysis is enabled
-                       /// </summary>
-                       DoFlowAnalysis = 1 << 20,
-
-                       /// <summary>
-                       ///   Whether control flow analysis is disabled on structs
-                       ///   (only meaningful when DoFlowAnalysis is set)
-                       /// </summary>
-                       OmitStructFlowAnalysis = 1 << 21,
-
-                       ///
-                       /// Indicates the current context is in probing mode, no errors are reported. 
-                       ///
-                       ProbingMode = 1 << 22,
-
-                       //
-                       // Return and ContextualReturn statements will set the ReturnType
-                       // value based on the expression types of each return statement
-                       // instead of the method return type which is initially null.
-                       //
-                       InferReturnType = 1 << 23,
-
-                       OmitDebuggingInfo = 1 << 24
+                       ig.Emit (opcode);
                }
 
-               // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
-               // it's public so that we can use a struct at the callsite
-               public struct FlagsHandle : IDisposable
+               public void Emit (OpCode opcode, LocalBuilder local)
                {
-                       ResolveContext ec;
-                       readonly Options invmask, oldval;
+                       ig.Emit (opcode, local);
+               }
 
-                       public FlagsHandle (ResolveContext ec, Options flagsToSet)
-                               : this (ec, flagsToSet, flagsToSet)
-                       {
-                       }
+               public void Emit (OpCode opcode, string arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
 
-                       internal FlagsHandle (ResolveContext ec, Options mask, Options val)
-                       {
-                               this.ec = ec;
-                               invmask = ~mask;
-                               oldval = ec.flags & mask;
-                               ec.flags = (ec.flags & invmask) | (val & mask);
+               public void Emit (OpCode opcode, double arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
 
-                               if ((mask & Options.ProbingMode) != 0)
-                                       Report.DisableReporting ();
-                       }
+               public void Emit (OpCode opcode, float arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
 
-                       public void Dispose ()
-                       {
-                               if ((invmask & Options.ProbingMode) == 0)
-                                       Report.EnableReporting ();
+               public void Emit (OpCode opcode, int arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
 
-                               ec.flags = (ec.flags & invmask) | oldval;
-                       }
+               public void Emit (OpCode opcode, byte arg)
+               {
+                       ig.Emit (opcode, arg);
                }
 
-               Options flags;
+               public void Emit (OpCode opcode, Label label)
+               {
+                       ig.Emit (opcode, label);
+               }
 
-               //
-               // Whether we are inside an anonymous method.
-               //
-               public AnonymousExpression CurrentAnonymousMethod;
+               public void Emit (OpCode opcode, Label[] labels)
+               {
+                       ig.Emit (opcode, labels);
+               }
 
-               //
-               // Holds a varible used during collection or object initialization.
-               //
-               public Expression CurrentInitializerVariable;
+               public void Emit (OpCode opcode, TypeSpec type)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
 
-               public Block CurrentBlock;
+                       ig.Emit (opcode, type.GetMetaInfo ());
+               }
 
-               public IMemberContext MemberContext;
+               public void Emit (OpCode opcode, FieldSpec field)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-               /// <summary>
-               ///   If this is non-null, points to the current switch statement
-               /// </summary>
-               public Switch Switch;
+                       ig.Emit (opcode, field.GetMetaInfo ());
+               }
 
-               public ResolveContext (IMemberContext mc)
+               public void Emit (OpCode opcode, MethodSpec method)
                {
-                       MemberContext = mc;
-
-                       //
-                       // The default setting comes from the command line option
-                       //
-                       if (RootContext.Checked)
-                               flags |= Options.CheckedScope;
+                       if (IsAnonymousStoreyMutateRequired)
+                               method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-                       //
-                       // The constant check state is always set to true
-                       //
-                       flags |= Options.ConstantCheckState;
+                       if (method.IsConstructor)
+                               ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
+                       else
+                               ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
                }
 
-               public ResolveContext (IMemberContext mc, Options options)
-                       : this (mc)
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, MethodInfo method)
                {
-                       flags |= options;
+                       ig.Emit (opcode, method);
                }
 
-               public virtual FlowBranching CurrentBranching {
-                       get { return null; }
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, FieldBuilder field)
+               {
+                       ig.Emit (opcode, field);
                }
 
-               //
-               // The current iterator
-               //
-               public Iterator CurrentIterator {
-                       get { return CurrentAnonymousMethod as Iterator; }
+               public void Emit (OpCode opcode, MethodSpec method, Type[] vargs)
+               {
+                       // TODO MemberCache: This should mutate too
+                       ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
                }
 
-               public Type CurrentType {
-                       get { return MemberContext.CurrentType; }
-               }
+               public void EmitArrayNew (ArrayContainer ac)
+               {
+                       if (ac.Rank == 1) {
+                               Emit (OpCodes.Newarr, ac.Element);
+                       } else {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-               public TypeParameter[] CurrentTypeParameters {
-                       get { return MemberContext.CurrentTypeParameters; }
+                               ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
+                       }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return MemberContext.CurrentTypeDefinition; }
-               }
+               //
+               // Emits the right opcode to load from an array
+               //
+               public void EmitArrayLoad (ArrayContainer ac)
+               {
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-               public bool ConstantCheckState {
-                       get { return (flags & Options.ConstantCheckState) != 0; }
-               }
+                               ig.Emit (OpCodes.Call, ac.GetGetMethod ());
+                               return;
+                       }
 
-               public bool DoFlowAnalysis {
-                       get { return (flags & Options.DoFlowAnalysis) != 0; }
+                       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);
                }
 
-               public bool IsInProbingMode {
-                       get { return (flags & Options.ProbingMode) != 0; }
-               }
+               //
+               // Emits the right opcode to store to an array
+               //
+               public void EmitArrayStore (ArrayContainer ac)
+               {
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
 
-               public bool IsVariableCapturingRequired {
-                       get {
-                               return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
+                               ig.Emit (OpCodes.Call, ac.GetSetMethod ());
+                               return;
                        }
-               }
 
-               public bool OmitStructFlowAnalysis {
-                       get { return (flags & Options.OmitStructFlowAnalysis) != 0; }
+                       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);
                }
 
-               // TODO: Merge with CompilerGeneratedThis
-               public Expression GetThis (Location loc)
+               public void EmitInt (int i)
                {
-                       This my_this;
-                       if (CurrentBlock != null)
-                               my_this = new This (CurrentBlock, loc);
-                       else
-                               my_this = new This (loc);
+                       switch (i) {
+                       case -1:
+                               ig.Emit (OpCodes.Ldc_I4_M1);
+                               break;
 
-                       if (!my_this.ResolveBase (this))
-                               my_this = null;
+                       case 0:
+                               ig.Emit (OpCodes.Ldc_I4_0);
+                               break;
 
-                       return my_this;
-               }
+                       case 1:
+                               ig.Emit (OpCodes.Ldc_I4_1);
+                               break;
 
-               public bool MustCaptureVariable (LocalInfo local)
-               {
-                       if (CurrentAnonymousMethod == null)
-                               return false;
+                       case 2:
+                               ig.Emit (OpCodes.Ldc_I4_2);
+                               break;
 
-                       // FIXME: IsIterator is too aggressive, we should capture only if child
-                       // block contains yield
-                       if (CurrentAnonymousMethod.IsIterator)
-                               return true;
+                       case 3:
+                               ig.Emit (OpCodes.Ldc_I4_3);
+                               break;
 
-                       return local.Block.Toplevel != CurrentBlock.Toplevel;
-               }
+                       case 4:
+                               ig.Emit (OpCodes.Ldc_I4_4);
+                               break;
 
-               public bool HasSet (Options options)
-               {
-                       return (this.flags & options) == options;
-               }
+                       case 5:
+                               ig.Emit (OpCodes.Ldc_I4_5);
+                               break;
 
-               public bool HasAny (Options options)
-               {
-                       return (this.flags & options) != 0;
-               }
+                       case 6:
+                               ig.Emit (OpCodes.Ldc_I4_6);
+                               break;
 
-               // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
-               public FlagsHandle Set (Options options)
-               {
-                       return new FlagsHandle (this, options);
-               }
+                       case 7:
+                               ig.Emit (OpCodes.Ldc_I4_7);
+                               break;
 
-               public FlagsHandle With (Options options, bool enable)
-               {
-                       return new FlagsHandle (this, options, enable ? options : 0);
-               }
+                       case 8:
+                               ig.Emit (OpCodes.Ldc_I4_8);
+                               break;
 
-               public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
-               {
-                       Options newflags =
-                               (do_flow_analysis ? Options.DoFlowAnalysis : 0) |
-                               (omit_struct_analysis ? Options.OmitStructFlowAnalysis : 0);
-                       return new FlagsHandle (this, Options.DoFlowAnalysis | Options.OmitStructFlowAnalysis, newflags);
+                       default:
+                               if (i >= -128 && i <= 127) {
+                                       ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
+                               } else
+                                       ig.Emit (OpCodes.Ldc_I4, i);
+                               break;
+                       }
                }
 
-               #region IMemberContext Members
+               public void EmitLong (long l)
+               {
+                       if (l >= int.MinValue && l <= int.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_I8);
+                               return;
+                       }
 
-               public bool IsObsolete {
-                       get {
-                               // Disables obsolete checks when probing is on
-                               return IsInProbingMode || MemberContext.IsObsolete;
+                       if (l >= 0 && l <= uint.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_U8);
+                               return;
                        }
-               }
 
-               public bool IsStatic {
-                       get { return MemberContext.IsStatic; }
+                       ig.Emit (OpCodes.Ldc_I8, l);
                }
 
-               public bool IsUnsafe {
-                       get { return HasSet (Options.UnsafeScope) || MemberContext.IsUnsafe; }
+               //
+               // Load the object from the pointer.  
+               //
+               public void EmitLoadFromPtr (TypeSpec t)
+               {
+                       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);
                }
 
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               //
+               // The stack contains the pointer and the value of type `type'
+               //
+               public void EmitStoreFromPtr (TypeSpec type)
                {
-                       return MemberContext.LookupExtensionMethod (extensionType, name, loc);
+                       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);
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               /// <summary>
+               ///   Returns a temporary storage for a variable of type t as 
+               ///   a local variable in the current body.
+               /// </summary>
+               public LocalBuilder GetTemporaryLocal (TypeSpec t)
                {
-                       return MemberContext.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       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 DeclareLocal (t, false);
                }
 
-               public FullNamedExpression LookupNamespaceAlias (string name)
+               public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
                {
-                       return MemberContext.LookupNamespaceAlias (name);
+                       if (temporary_storage == null) {
+                               temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
+                               temporary_storage.Add (t, b);
+                               return;
+                       }
+                       object o;
+                       
+                       if (!temporary_storage.TryGetValue (t, out o)) {
+                               temporary_storage.Add (t, b);
+                               return;
+                       }
+                       var s = o as Stack<LocalBuilder>;
+                       if (s == null) {
+                               s = new Stack<LocalBuilder> ();
+                               s.Push ((LocalBuilder)o);
+                               temporary_storage [t] = s;
+                       }
+                       s.Push (b);
                }
 
-               #endregion
-       }
+               /// <summary>
+               ///   ReturnValue creates on demand the LocalBuilder for the
+               ///   return value from the function.  By default this is not
+               ///   used.  This is only required when returns are found inside
+               ///   Try or Catch statements.
+               ///
+               ///   This method is typically invoked from the Emit phase, so
+               ///   we allow the creation of a return label if it was not
+               ///   requested during the resolution phase.   Could be cleaned
+               ///   up, but it would replicate a lot of logic in the Emit phase
+               ///   of the code that uses it.
+               /// </summary>
+               public LocalBuilder TemporaryReturn ()
+               {
+                       if (return_value == null){
+                               return_value = DeclareLocal (return_type, false);
+                               if (!HasReturnLabel){
+                                       ReturnLabel = DefineLabel ();
+                                       HasReturnLabel = true;
+                               }
+                       }
 
+                       return return_value;
+               }
+       }
 
        public abstract class CommonAssemblyModulClass : Attributable, IMemberContext
        {
-               public void AddAttributes (ArrayList attrs, IMemberContext context)
+               public void AddAttributes (List<Attribute> attrs, IMemberContext context)
                {
                        foreach (Attribute a in attrs)
                                a.AttachTo (this, context);
@@ -990,9 +852,13 @@ namespace Mono.CSharp {
                        return a;
                }
 
-               #region IResolveContext Members
+               #region IMemberContext Members
 
-               public Type CurrentType {
+               public CompilerContext Compiler {
+                       get { return RootContext.ToplevelTypes.Compiler; }
+               }
+
+               public TypeSpec CurrentType {
                        get { return null; }
                }
 
@@ -1000,12 +866,17 @@ namespace Mono.CSharp {
                        get { return null; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
+               public MemberCore CurrentMemberDefinition {
                        get { return RootContext.ToplevelTypes; }
                }
 
-               public DeclSpace DeclContainer {
-                       get { return RootContext.ToplevelTypes; }
+               public string GetSignatureForError ()
+               {
+                       return "<module>";
+               }
+
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
                }
 
                public bool IsObsolete {
@@ -1020,14 +891,14 @@ namespace Mono.CSharp {
                        get { return false; }
                }
 
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
                        throw new NotImplementedException ();
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
-                       return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return RootContext.ToplevelTypes.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                }
 
                public FullNamedExpression LookupNamespaceAlias (string name)
@@ -1046,16 +917,16 @@ 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;
-               ListDictionary emitted_forwarders;
+               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;
                }
@@ -1089,6 +960,10 @@ namespace Mono.CSharp {
                        return is_cls_compliant;
                }
 
+               Report Report {
+                       get { return Compiler.Report; }
+               }
+
                public void Resolve ()
                {
                        if (RootContext.Unsafe) {
@@ -1106,7 +981,7 @@ namespace Mono.CSharp {
                                pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
 
                                Arguments named = new Arguments (1);
-                               named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
+                               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"),
@@ -1114,7 +989,7 @@ namespace Mono.CSharp {
                                g.AttachTo (this, this);
 
                                if (g.Resolve () != null) {
-                                       declarative_security = new ListDictionary ();
+                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
                                        g.ExtractSecurityPermissionSet (declarative_security);
                                }
                        }
@@ -1134,9 +1009,9 @@ namespace Mono.CSharp {
 
                        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;
                        }
                }
 
@@ -1296,11 +1171,7 @@ namespace Mono.CSharp {
                                
                        AssemblyName aname = null;
                        try {
-#if GMCS_SOURCE
                                aname = new AssemblyName (assembly_name);
-#else
-                               throw new NotSupportedException ();
-#endif
                        } catch (FileLoadException) {
                        } catch (ArgumentException) {
                        }
@@ -1343,11 +1214,11 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               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;
@@ -1381,32 +1252,31 @@ namespace Mono.CSharp {
                                return;
 
                        if (a.Type == pa.TypeForwarder) {
-                               Type t = a.GetArgumentType ();
+                               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;
                                }
 
-                               t = TypeManager.DropGenericTypeArguments (t);
                                if (emitted_forwarders == null) {
-                                       emitted_forwarders = new ListDictionary();
-                               } else if (emitted_forwarders.Contains(t)) {
-                                       Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, 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, a);
+                               emitted_forwarders.Add(t.MemberDefinition, a);
 
-                               if (TypeManager.LookupDeclSpace (t) != null) {
+                               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.DeclaringType != null) {
+                               if (t.IsNested) {
                                        Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
                                                TypeManager.CSharpName (t));
                                        return;
@@ -1422,7 +1292,7 @@ namespace Mono.CSharp {
                                        }
                                }
 
-                               add_type_forwarder.Invoke (Builder, new object[] { t });
+                               add_type_forwarder.Invoke (Builder, new object[] { t.GetMetaInfo () });
                                return;
                        }
                        
@@ -1431,7 +1301,7 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       Builder.SetCustomAttribute (cb);
+                       Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override void Emit (TypeContainer tc)
@@ -1444,14 +1314,13 @@ namespace Mono.CSharp {
                        // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
                        PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
                        if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
-                               ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
-                                       pa.Type, Location.Null, Type.EmptyTypes);
+                               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);
+                                       "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type).MetaInfo;
                                object [] pargs = new object [1];
                                pargs [0] = true;
-                               Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
+                               Builder.SetCustomAttribute (new CustomAttributeBuilder ((ConstructorInfo) ci.GetMetaInfo (), new object[0], pis, pargs));
                        }
 
                        if (declarative_security != null) {
@@ -1462,16 +1331,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 {