Added few unsafe tests.
[mono.git] / mcs / mcs / typemanager.cs
index 66a1ff9776bd55163ec53d947e1695c0aaf38eea..431b329f04ed42762464641a356a3812efc8f5b0 100644 (file)
@@ -5,10 +5,10 @@
 //         Ravi Pratap     (ravi@ximian.com)
 //         Marek Safar     (marek.safar@seznam.cz)
 //
-// Licensed under the terms of the GNU GPL
-//
-// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// Dual licensed under the terms of the MIT X11 or GNU GPL
 //
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc.
 //
 
 //
@@ -25,7 +25,6 @@ using System.Collections;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Text;
-using System.Text.RegularExpressions;
 using System.Runtime.CompilerServices;
 using System.Diagnostics;
 
@@ -62,35 +61,27 @@ namespace Mono.CSharp {
        static public Type null_type;
        static public Type array_type;
        static public Type runtime_handle_type;
-       static public Type icloneable_type;
        static public Type type_type;
        static public Type ienumerator_type;
        static public Type ienumerable_type;
        static public Type idisposable_type;
-       static public Type iconvertible_type;
        static public Type default_member_type;
        static public Type iasyncresult_type;
        static public Type asynccallback_type;
        static public Type intptr_type;
        static public Type uintptr_type;
-       static public Type monitor_type;
-       static public Type interlocked_type;
        static public Type runtime_field_handle_type;
-       static public Type runtime_method_handle_type;
        static public Type runtime_argument_handle_type;
        static public Type attribute_type;
        static public Type attribute_usage_type;
        static public Type decimal_constant_attribute_type;
        static public Type dllimport_type;
-       static public Type unverifiable_code_type;
        static public Type methodimpl_attr_type;
        static public Type marshal_as_attr_type;
        static public Type param_array_type;
        static public Type void_ptr_type;
        static public Type indexer_name_type;
        static public Type exception_type;
-       static public Type invalid_operation_exception_type;
-       static public Type not_supported_exception_type;
        static public Type obsolete_attribute_type;
        static public Type conditional_attribute_type;
        static public Type in_attribute_type;
@@ -112,23 +103,28 @@ namespace Mono.CSharp {
        static public Type assembly_version_attribute_type;
        static public Type coclass_attr_type;
        static public Type comimport_attr_type;
+       public static Type runtime_helpers_type;
+       public static Type internals_visible_attr_type;
 
-#if GMCS_SOURCE
        // 
        // C# 2.0
        //
-       static internal Type runtime_compatibility_attr_type;
-       static internal Type compiler_generated_attr_type;
        static internal Type fixed_buffer_attr_type;
        static internal Type default_charset_type;
-       static internal Type internals_visible_attr_type;
        static internal Type type_forwarder_attr_type;
+       static internal Type isvolatile_type;
+       static public Type activator_type;
+       static public Type generic_ilist_type;
+       static public Type generic_icollection_type;
+       static public Type generic_ienumerator_type;
+       static public Type generic_ienumerable_type;
+       static public Type generic_nullable_type;
 
        //
        // C# 3.0
        //
        static internal Type expression_type;
-#endif
+       public static Type parameter_expression_type;
 
        // 
        // Expressions representing the internal types.  Used during declaration
@@ -142,47 +138,17 @@ namespace Mono.CSharp {
        static public TypeExpr system_int32_expr, system_uint32_expr;
        static public TypeExpr system_int64_expr, system_uint64_expr;
        static public TypeExpr system_char_expr, system_void_expr;
-       static public TypeExpr system_asynccallback_expr;
-       static public TypeExpr system_iasyncresult_expr;
        static public TypeExpr system_valuetype_expr;
        static public TypeExpr system_intptr_expr;
+       public static TypeExpr expression_type_expr;
 
-       //
-       // This is only used when compiling corlib
-       //
-       static public Type system_int32_type;
-       static public Type system_array_type;
-       static public Type system_type_type;
-       static public Type system_assemblybuilder_type;
-       static public MethodInfo system_int_array_get_length;
-       static public MethodInfo system_int_array_get_rank;
-       static public MethodInfo system_object_array_clone;
-       static public MethodInfo system_int_array_get_length_int;
-       static public MethodInfo system_int_array_get_lower_bound_int;
-       static public MethodInfo system_int_array_get_upper_bound_int;
-       static public MethodInfo system_void_array_copyto_array_int;
 
-       
-       //
-       // Internal, not really used outside
-       //
-       static Type runtime_helpers_type;
-       
        //
        // These methods are called by code generated by the compiler
        //
-       static public MethodInfo string_concat_string_string;
-       static public MethodInfo string_concat_string_string_string;
-       static public MethodInfo string_concat_string_string_string_string;
-       static public MethodInfo string_concat_string_dot_dot_dot;
-       static public MethodInfo string_concat_object_object;
-       static public MethodInfo string_concat_object_object_object;
-       static public MethodInfo string_concat_object_dot_dot_dot;
        static public MethodInfo string_isinterned_string;
        static public MethodInfo system_type_get_type_from_handle;
        static public MethodInfo bool_movenext_void;
-       static public MethodInfo ienumerable_getenumerator_void;
-       static public MethodInfo void_reset_void;
        static public MethodInfo void_dispose_void;
        static public MethodInfo void_monitor_enter_object;
        static public MethodInfo void_monitor_exit_object;
@@ -191,37 +157,32 @@ namespace Mono.CSharp {
        static public MethodInfo delegate_combine_delegate_delegate;
        static public MethodInfo delegate_remove_delegate_delegate;
        static public MethodInfo int_get_offset_to_string_data;
-       static public MethodInfo int_array_get_length;
-       static public MethodInfo int_array_get_rank;
-       static public MethodInfo object_array_clone;
-       static public MethodInfo int_array_get_length_int;
-       static public MethodInfo int_array_get_lower_bound_int;
-       static public MethodInfo int_array_get_upper_bound_int;
-       static public MethodInfo void_array_copyto_array_int;
        static public MethodInfo int_interlocked_compare_exchange;
        static public PropertyInfo ienumerator_getcurrent;
+       public static MethodInfo methodbase_get_type_from_handle;
+       public static MethodInfo methodbase_get_type_from_handle_generic;
+       public static MethodInfo fieldinfo_get_field_from_handle;
+       static public MethodInfo activator_create_instance;
        
        //
        // The attribute constructors.
        //
-       static public ConstructorInfo object_ctor;
-       static public ConstructorInfo cons_param_array_attribute;
        static public ConstructorInfo void_decimal_ctor_five_args;
        static public ConstructorInfo void_decimal_ctor_int_arg;
-       static public ConstructorInfo unverifiable_code_ctor;
        static public ConstructorInfo default_member_ctor;
        static public ConstructorInfo decimal_constant_attribute_ctor;
        static internal ConstructorInfo struct_layout_attribute_ctor;
        static public ConstructorInfo field_offset_attribute_ctor;
-       
-#if GMCS_SOURCE
+       public static ConstructorInfo invalid_operation_exception_ctor;
+
+       static public CustomAttributeBuilder param_array_attr;
+       static CustomAttributeBuilder compiler_generated_attr;
+
        // C# 2.0
-       static internal CustomAttributeBuilder compiler_generated_attr;
        static internal ConstructorInfo fixed_buffer_attr_ctor;
 
        // C# 3.0
        static internal CustomAttributeBuilder extension_attribute_attr;
-#endif
 
        static PtrHashtable builder_to_declspace;
 
@@ -265,16 +226,8 @@ namespace Mono.CSharp {
        static Hashtable propertybuilder_to_property;
        static Hashtable fields;
        static Hashtable events;
-
-#if GMCS_SOURCE
        static PtrHashtable assembly_internals_vis_attrs;
-#endif
 
-       struct Signature {
-               public string name;
-               public Type [] args;
-       }
-       
        public static void CleanUp ()
        {
                // Lets get everything clean so that we can collect before generating code
@@ -290,57 +243,11 @@ namespace Mono.CSharp {
                events = null;
                type_hash = null;
                propertybuilder_to_property = null;
-
-#if GMCS_SOURCE
                assembly_internals_vis_attrs = null;
-#endif
 
                TypeHandle.CleanUp ();
        }
 
-       /// <summary>
-       ///   A filter for Findmembers that uses the Signature object to
-       ///   extract objects
-       /// </summary>
-       static bool SignatureFilter (MemberInfo mi, object criteria)
-       {
-               Signature sig = (Signature) criteria;
-
-               if (!(mi is MethodBase))
-                       return false;
-
-               if (mi.Name != sig.name)
-                       return false;
-
-               int count = sig.args.Length;
-               
-               if (mi is MethodBuilder || mi is ConstructorBuilder){
-                       Type [] candidate_args = GetParameterData ((MethodBase) mi).Types;
-
-                       if (candidate_args.Length != count)
-                               return false;
-                       
-                       for (int i = 0; i < count; i++)
-                               if (candidate_args [i] != sig.args [i])
-                                       return false;
-                       
-                       return true;
-               } else {
-                       ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
-
-                       if (pars.Length != count)
-                               return false;
-
-                       for (int i = 0; i < count; i++)
-                               if (pars [i].ParameterType != sig.args [i])
-                                       return false;
-                       return true;
-               }
-       }
-
-       // A delegate that points to the filter above.
-       static MemberFilter signature_filter;
-
        //
        // These are expressions that represent some of the internal data types, used
        // elsewhere
@@ -363,8 +270,6 @@ namespace Mono.CSharp {
                system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
                system_char_expr    = new TypeLookupExpression ("System.Char");
                system_void_expr    = new TypeLookupExpression ("System.Void");
-               system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
-               system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
                system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
                system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
        }
@@ -373,7 +278,6 @@ namespace Mono.CSharp {
        {
                Reset ();
 
-               signature_filter = new MemberFilter (SignatureFilter);
                InitExpressionTypes ();
        }
 
@@ -392,11 +296,43 @@ namespace Mono.CSharp {
                propertybuilder_to_property = new Hashtable ();
                fields = new Hashtable ();
                type_hash = new DoubleHash ();
-
-#if GMCS_SOURCE
                assembly_internals_vis_attrs = new PtrHashtable ();
-#endif
 
+               // TODO: I am really bored by all this static stuff
+               string_isinterned_string =
+               system_type_get_type_from_handle =
+               bool_movenext_void =
+               void_dispose_void =
+               void_monitor_enter_object =
+               void_monitor_exit_object =
+               void_initializearray_array_fieldhandle =
+               int_getlength_int =
+               delegate_combine_delegate_delegate =
+               delegate_remove_delegate_delegate =
+               int_get_offset_to_string_data =
+               int_interlocked_compare_exchange =
+               methodbase_get_type_from_handle =
+               methodbase_get_type_from_handle_generic =
+               fieldinfo_get_field_from_handle =
+               activator_create_instance = null;
+
+               ienumerator_getcurrent = null;
+
+               void_decimal_ctor_five_args =
+               void_decimal_ctor_int_arg =
+               default_member_ctor =
+               decimal_constant_attribute_ctor =
+               struct_layout_attribute_ctor =
+               field_offset_attribute_ctor =
+               invalid_operation_exception_ctor =
+               fixed_buffer_attr_ctor = null;
+
+               param_array_attr =
+               compiler_generated_attr =
+               extension_attribute_attr = null;
+
+               isvolatile_type = null;
+                       
                // to uncover regressions
                AllClsTopLevelTypes = null;
        }
@@ -587,6 +523,24 @@ namespace Mono.CSharp {
                return null;
        }
 
+       public static CustomAttributeBuilder GetCompilerGeneratedAttribute (Location loc)
+       {
+               if (compiler_generated_attr != null)
+                       return compiler_generated_attr;
+
+               Type t = TypeManager.CoreLookupType (
+                       "System.Runtime.CompilerServices", "CompilerGeneratedAttribute", Kind.Class, true);
+
+               // TODO: it cannot be null
+               if (t == null)
+                       return null;
+
+               compiler_generated_attr = new CustomAttributeBuilder (
+                       GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
+
+               return compiler_generated_attr;
+       }
+
        public static Type GetNestedType (Type t, string name)
        {
                object ret = null;
@@ -626,7 +580,7 @@ namespace Mono.CSharp {
        /// </summary>
        static public string CSharpName (Type t)
        {
-               if (t == typeof(NullType))
+               if (t == null_type)
                        return "null";
 
                if (t == typeof (ArglistParameter))
@@ -638,46 +592,56 @@ namespace Mono.CSharp {
                return CSharpName (GetFullName (t));
     }
 
+       static readonly char [] elements = new char [] { '*', '[' };
+
        public static string CSharpName (string name)
        {
-               if (name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
-                               return AnonymousTypeClass.SignatureForError;
-                       
-               return Regex.Replace (name,
-                       @"^System\." +
-                       @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
-                       @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
-                       @"Boolean|String|Void|Null)" +
-                       @"(\W+|\b)",
-                       new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
+               if (name.Length > 10) {
+                       switch (name) {
+                       case "System.Int32": return "int";
+                       case "System.Int64": return "long";
+                       case "System.String": return "string";
+                       case "System.Boolean": return "bool";
+                       case "System.Void": return "void";
+                       case "System.Object": return "object";
+                       case "System.UInt32": return "uint";
+                       case "System.Int16": return "short";
+                       case "System.UInt16": return "ushort";
+                       case "System.UInt64": return "ulong";
+                       case "System.Single": return "float";
+                       case "System.Double": return "double";
+                       case "System.Decimal": return "decimal";
+                       case "System.Char": return "char";
+                       case "System.Byte": return "byte";
+                       case "System.SByte": return "sbyte";
+                       }
+
+                       int idx = name.IndexOfAny (elements, 10);
+                       if (idx > 0)
+                               return CSharpName (name.Substring (0, idx)) + name.Substring (idx);
+               }
+
+               if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
+                       return AnonymousTypeClass.SignatureForError;
+
+               return name.Replace ('+', '.');
        }
 
        static public string CSharpName (Type[] types)
        {
+               if (types.Length == 0)
+                       return string.Empty;
+
                StringBuilder sb = new StringBuilder ();
-               foreach (Type t in types) {
-                       sb.Append (CSharpName (t));
-                       sb.Append (',');
+               for (int i = 0; i < types.Length; ++i) {
+                       if (i > 0)
+                               sb.Append (", ");
+
+                       sb.Append (CSharpName (types [i]));
                }
-               sb.Remove (sb.Length - 1, 1);
                return sb.ToString ();
        }
        
-       static String CSharpNameMatch (Match match) 
-       {
-               string s = match.Groups [1].Captures [0].Value;
-               return s.ToLower ().
-               Replace ("int32", "int").
-               Replace ("uint32", "uint").
-               Replace ("int16", "short").
-               Replace ("uint16", "ushort").
-               Replace ("int64", "long").
-               Replace ("uint64", "ulong").
-               Replace ("single", "float").
-               Replace ("boolean", "bool")
-               + match.Groups [2].Captures [0].Value;
-       }
-
        // Used for error reporting to show symbolic name instead of underlying value
        public static string CSharpEnumValue (Type t, object value)
        {
@@ -879,298 +843,278 @@ namespace Mono.CSharp {
                return CSharpName (ei.DeclaringType) + "." + ei.Name;
        }
 
-       /// <summary>
-       ///   Looks up a type, and aborts if it is not found.  This is used
-       ///   by types required by the compiler
-       /// </summary>
-       public static Type CoreLookupType (string namespaceName, string name)
-       {
-               return CoreLookupType (namespaceName, name, false);
-       }
-
-       static Type CoreLookupType (string ns_name, string name, bool mayFail)
-       {
-               Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
-               FullNamedExpression fne = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
-               Type t = fne == null ? null : fne.Type;
-               if (t == null) {
-                       if (!mayFail)
-                               Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
-                       return null;
-               }
-
-               AttributeTester.RegisterNonObsoleteType (t);
-               return t;
-       }
-
-       /// <summary>
-       ///   Returns the MethodInfo for a method named `name' defined
-       ///   in type `t' which takes arguments of types `args'
-       /// </summary>
-       static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
+       //
+       // Looks up a type, and aborts if it is not found.  This is used
+       // by predefined types required by the compiler
+       //
+       public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
        {
-               MemberList list;
-               Signature sig;
-               BindingFlags flags = instance_and_static | BindingFlags.Public;
-
-               sig.name = name;
-               sig.args = args;
+               Expression expr;
+               if (RootContext.StdLib) {
+                       Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
+                       expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
+               } else {
+                       if (!required)
+                               Report.DisableReporting ();
 
-               if (is_private)
-                       flags |= BindingFlags.NonPublic;
+                       TypeLookupExpression tle = new TypeLookupExpression (ns_name + "." + name);
+                       expr = tle.ResolveAsTypeTerminal (RootContext.ToplevelTypes, false);
 
-               list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
-               if (list.Count == 0) {
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core function `" + name + "'");
-                       return null;
+                       if (!required)
+                               Report.EnableReporting ();
                }
 
-               MethodInfo mi = list [0] as MethodInfo;
-               if (mi == null) {
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core function `" + name + "'");
+               if (expr == null) {
+                       if (required) {
+                               Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
+                                       ns_name, name);
+                       }
                        return null;
                }
 
-               return mi;
-       }
+               Type t = expr.Type;
+               if (RootContext.StdLib || t == null || !required)
+                       return t;
 
-       static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
-       {
-               return GetMethod (t, name, args, false, report_errors);
-       }
+               // TODO: All predefined imported types have to have correct signature
+               if (t.Module != CodeGen.Module.Builder)
+                       return t;
 
-       public static MethodInfo GetMethod (Type t, string name, Type [] args)
-       {
-               return GetMethod (t, name, args, true);
+               DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
+               if (ds is Delegate) {
+                       if (type_kind == Kind.Delegate)
+                               return t;
+               } else {
+                       TypeContainer tc = (TypeContainer)ds;
+                       if (tc.Kind == type_kind)
+                               return t;
+               }
+
+               Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
+                       ns_name, name);
+               return null;
        }
 
-       /// <summary>
-       ///   Returns the PropertyInfo for a property named `name' defined
-       ///   in type `t'
-       /// </summary>
-       public static PropertyInfo GetProperty (Type t, string name)
+       static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
        {
-               MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
-                                              BindingFlags.Instance, Type.FilterName, name);
-               if (list.Count == 0) {
-                       Report.Error (-19, "Can not find the core property `" + name + "'");
-                       return null;
-               }
+               const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
 
-               PropertyInfo pi = list [0] as PropertyInfo;
-               if (pi == null) {
-                       Report.Error (-19, "Can not find the core function `" + name + "'");
-                       return null;
-               }
+               MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
+               if (members != null) {
+                       for (int i = 0; i < members.Length; ++i) {
+                               MemberInfo member = members [i];
+                               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
+                                       MethodBase mb = member as MethodBase;
+                                       if (mb == null)
+                                               continue;
 
-               return pi;
-       }
+                                       ParameterData pd = TypeManager.GetParameterData (mb);
+                                       if (IsEqual (pd.Types, args))
+                                               return member;
+                               }
+                               if (mt == MemberTypes.Field) {
+                                       FieldInfo fi = member as FieldInfo;
+                                       if (fi == null)
+                                               continue;
 
-       /// <summary>
-       ///    Returns the ConstructorInfo for "args"
-       /// </summary>
-       public static ConstructorInfo GetConstructor (Type t, Type [] args)
-       {
-               return GetConstructor (t, args, true);
-       }
+                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
+                                               continue;
 
-       public static ConstructorInfo GetConstructor (Type t, Type [] args, bool report_errors)
-       {
-               MemberList list;
-               Signature sig;
+                                       return member;
+                               }
 
-               sig.name = ".ctor";
-               sig.args = args;
+                               if (mt == MemberTypes.Property) {
+                                       PropertyInfo pi = member as PropertyInfo;
+                                       if (pi == null)
+                                               continue;
 
-               if (t == null)
-                       throw new InternalErrorException ("Core types haven't been initialized yet?");
-               
-               list = FindMembers (t, MemberTypes.Constructor,
-                                   instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
-                                   signature_filter, sig);
-               if (list.Count == 0){
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
-                       return null;
-               }
+                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
+                                               continue;
 
-               ConstructorInfo ci = list [0] as ConstructorInfo;
-               if (ci == null){
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
-                       return null;
+                                       return member;
+                               }
+                       }
                }
 
-               return ci;
+               string method_args = null;
+               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
+                       method_args = "(" + TypeManager.CSharpName (args) + ")";
+
+               Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
+                       TypeManager.CSharpName (t), name, method_args);
+
+               return null;
        }
 
-       public static void InitEnumUnderlyingTypes ()
+       //
+       // Returns the ConstructorInfo for "args"
+       //
+       public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
        {
-               int32_type    = CoreLookupType ("System", "Int32");
-               int64_type    = CoreLookupType ("System", "Int64");
-               uint32_type   = CoreLookupType ("System", "UInt32"); 
-               uint64_type   = CoreLookupType ("System", "UInt64"); 
-               byte_type     = CoreLookupType ("System", "Byte");
-               sbyte_type    = CoreLookupType ("System", "SByte");
-               short_type    = CoreLookupType ("System", "Int16");
-               ushort_type   = CoreLookupType ("System", "UInt16");
+               return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
+       }
 
-               ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator");
-               ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable");
+       //
+       // Returns the MethodInfo for a method named `name' defined
+       // in type `t' which takes arguments of types `args'
+       //
+       public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
+       {
+               return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
+       }
 
-               idisposable_type     = CoreLookupType ("System", "IDisposable");
+       public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
+       {
+               return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
+       }
 
-#if GMCS_SOURCE
-               InitGenericCoreTypes ();
-#endif
+       public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
+       {
+               return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
        }
-       
+
        /// <remarks>
        ///   The types have to be initialized after the initial
        ///   population of the type has happened (for example, to
        ///   bootstrap the corlib.dll
        /// </remarks>
-       public static void InitCoreTypes ()
+       public static bool InitCoreTypes ()
        {
-               object_type   = CoreLookupType ("System", "Object");
+               object_type   = CoreLookupType ("System", "Object", Kind.Class, true);
                system_object_expr.Type = object_type;
-               value_type    = CoreLookupType ("System", "ValueType");
+               value_type    = CoreLookupType ("System", "ValueType", Kind.Class, true);
                system_valuetype_expr.Type = value_type;
+               attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
 
-               InitEnumUnderlyingTypes ();
+               int32_type    = CoreLookupType ("System", "Int32", Kind.Struct, true);
+               int64_type    = CoreLookupType ("System", "Int64", Kind.Struct, true);
+               uint32_type   = CoreLookupType ("System", "UInt32", Kind.Struct, true); 
+               uint64_type   = CoreLookupType ("System", "UInt64", Kind.Struct, true); 
+               byte_type     = CoreLookupType ("System", "Byte", Kind.Struct, true);
+               sbyte_type    = CoreLookupType ("System", "SByte", Kind.Struct, true);
+               short_type    = CoreLookupType ("System", "Int16", Kind.Struct, true);
+               ushort_type   = CoreLookupType ("System", "UInt16", Kind.Struct, true);
 
-               char_type     = CoreLookupType ("System", "Char");
-               string_type   = CoreLookupType ("System", "String");
-               float_type    = CoreLookupType ("System", "Single");
-               double_type   = CoreLookupType ("System", "Double");
-               char_ptr_type = GetPointerType (char_type);
-               decimal_type  = CoreLookupType ("System", "Decimal");
-               bool_type     = CoreLookupType ("System", "Boolean");
-               enum_type     = CoreLookupType ("System", "Enum");
-
-               multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
-               delegate_type           = CoreLookupType ("System", "Delegate");
-
-               array_type    = CoreLookupType ("System", "Array");
-               void_type     = CoreLookupType ("System", "Void");
-               type_type     = CoreLookupType ("System", "Type");
-
-               runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
-               runtime_method_handle_type = CoreLookupType ("System", "RuntimeMethodHandle");
-               runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
-               runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
-               default_member_type  = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
-               runtime_handle_type  = CoreLookupType ("System", "RuntimeTypeHandle");
-               asynccallback_type   = CoreLookupType ("System", "AsyncCallback");
-               iasyncresult_type    = CoreLookupType ("System", "IAsyncResult");
-               icloneable_type      = CoreLookupType ("System", "ICloneable");
-               iconvertible_type    = CoreLookupType ("System", "IConvertible");
-               interlocked_type     = CoreLookupType ("System.Threading", "Interlocked");
-               monitor_type         = CoreLookupType ("System.Threading", "Monitor");
-               intptr_type          = CoreLookupType ("System", "IntPtr");
-               uintptr_type         = CoreLookupType ("System", "UIntPtr");
-
-               attribute_type       = CoreLookupType ("System", "Attribute");
-               attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
-               dllimport_type       = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
-               methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
-               marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
-               param_array_type     = CoreLookupType ("System", "ParamArrayAttribute");
-               in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
-               out_attribute_type   = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
-#if NET_2_0
-               // needed before any call susceptible to fail, as it is used during resolution
-               internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
-
-               // this can fail if the user doesn't have an -r:System.dll
-               default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", true);
-#endif
-               typed_reference_type = CoreLookupType ("System", "TypedReference");
-               arg_iterator_type    = CoreLookupType ("System", "ArgIterator", true);
-               mbr_type             = CoreLookupType ("System", "MarshalByRefObject");
-               decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
+               ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
+               ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
+               idisposable_type     = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
 
-               unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
+               // HACK: DefineType immediately resolves iterators (very wrong)
+               generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
 
-               void_ptr_type         = GetPointerType (void_type);
+               char_type     = CoreLookupType ("System", "Char", Kind.Struct, true);
+               string_type   = CoreLookupType ("System", "String", Kind.Class, true);
+               float_type    = CoreLookupType ("System", "Single", Kind.Struct, true);
+               double_type   = CoreLookupType ("System", "Double", Kind.Struct, true);
+               decimal_type  = CoreLookupType ("System", "Decimal", Kind.Struct, true);
+               bool_type     = CoreLookupType ("System", "Boolean", Kind.Struct, true);
+               intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
+               uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
 
-               indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
+               multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
+               delegate_type           = CoreLookupType ("System", "Delegate", Kind.Class, true);
 
-               exception_type        = CoreLookupType ("System", "Exception");
-               invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
-               not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
+               enum_type       = CoreLookupType ("System", "Enum", Kind.Class, true);
+               array_type      = CoreLookupType ("System", "Array", Kind.Class, true);
+               void_type       = CoreLookupType ("System", "Void", Kind.Struct, true);
+               type_type       = CoreLookupType ("System", "Type", Kind.Class, true);
+               exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
 
-               //
-               // Attribute types
-               //
-               obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
-               conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
-               cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
-               struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
-               field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
-               security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
-               required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", true);
-               guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
-               assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
-               assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute");
-               comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
-               coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
+               runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
+               runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
+
+               param_array_type = CoreLookupType ("System", "ParamArrayAttribute", Kind.Class, true);
+               out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute", Kind.Class, true);
+
+               return Report.Errors == 0;
+       }
+
+       //
+       // Initializes optional core types
+       //
+       public static void InitOptionalCoreTypes ()
+       {
+               void_ptr_type = GetPointerType (void_type);
+               char_ptr_type = GetPointerType (char_type);
 
                //
-               // .NET 2.0
+               // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
+               // types cache with incorrect accessiblity when any of optional types is internal.
                //
-#if NET_2_0
-               compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
-               fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
-               default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
-               runtime_compatibility_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
-               type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", true);
+               internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", Kind.Class, false);
+
+               runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
+               asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
+               iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
+               typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
+               arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
+               mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
 
                //
-               // C# 3.0
+               // Optional attributes, used for error reporting only
                //
-               extension_attribute_type = CoreLookupType("System.Runtime.CompilerServices", "ExtensionAttribute", true);
-               expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", true);
-#endif
+               obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute", Kind.Class, false);
+               if (obsolete_attribute_type != null) {
+                       Class c = TypeManager.LookupClass (obsolete_attribute_type);
+                       if (c != null)
+                               c.DefineMembers ();
+               }
+
+               dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute", Kind.Class, false);
+               methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute", Kind.Class, false);
+               marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute", Kind.Class, false);
+               in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute", Kind.Class, false);
+               indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute", Kind.Class, false);
+               conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute", Kind.Class, false);
+               cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute", Kind.Class, false);
+               security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute", Kind.Class, false);
+               required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", Kind.Class, false);
+               guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute", Kind.Class, false);
+               assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute", Kind.Class, false);
+               assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute", Kind.Class, false);
+               comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute", Kind.Class, false);
+               coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute", Kind.Class, false);
+               attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute", Kind.Class, false);
+               default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", Kind.Class, false);
+
+               // New in .NET 2.0
+               default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute", Kind.Class, false);
+               type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", Kind.Class, false);
+               generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
+               generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
+               generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
+               generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
 
                //
-               // When compiling corlib, store the "real" types here.
+               // Optional types which are used as types and for member lookup
                //
+               default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute", Kind.Class, false);
+               runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
+               decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute", Kind.Class, false);
+               struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, false);
+               field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, false);
+
+               // New in .NET 2.0
+               fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, false);
+
+               // New in .NET 3.5
+               extension_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
+               expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
+
                if (!RootContext.StdLib) {
-                       system_int32_type = typeof (System.Int32);
-                       system_array_type = typeof (System.Array);
-                       system_type_type = typeof (System.Type);
-                       system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
-
-                       system_int_array_get_length = GetMethod (
-                               system_array_type, "get_Length", Type.EmptyTypes);
-                       system_int_array_get_rank = GetMethod (
-                               system_array_type, "get_Rank", Type.EmptyTypes);
-                       system_object_array_clone = GetMethod (
-                               system_array_type, "Clone", Type.EmptyTypes);
-
-                       Type [] system_int_arg = { system_int32_type };
-                       system_int_array_get_length_int = GetMethod (
-                               system_array_type, "GetLength", system_int_arg);
-                       system_int_array_get_upper_bound_int = GetMethod (
-                               system_array_type, "GetUpperBound", system_int_arg);
-                       system_int_array_get_lower_bound_int = GetMethod (
-                               system_array_type, "GetLowerBound", system_int_arg);
-
-                       Type [] system_array_int_arg = { system_array_type, system_int32_type };
-                       system_void_array_copyto_array_int = GetMethod (
-                               system_array_type, "CopyTo", system_array_int_arg);
-
-                       Type [] system_3_type_arg = {
-                               system_type_type, system_type_type, system_type_type };
-                       Type [] system_4_type_arg = {
-                               system_type_type, system_type_type, system_type_type, system_type_type };
-
-                       MethodInfo set_corlib_type_builders = GetMethod (
-                               system_assemblybuilder_type, "SetCorlibTypeBuilders",
-                               system_4_type_arg, true, false);
+                       //
+                       // HACK: When building Mono corlib mcs uses loaded mscorlib which
+                       // has different predefined types and this method sets mscorlib types
+                       // to be same to avoid any type check errors.
+                       //
+
+                       Type type = typeof (Type);
+                       Type [] system_4_type_arg = { type, type, type, type };
+                               
+                       MethodInfo set_corlib_type_builders = 
+                               typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
+                               "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
+                               system_4_type_arg, null);
 
                        if (set_corlib_type_builders != null) {
                                object[] args = new object [4];
@@ -1181,22 +1125,9 @@ namespace Mono.CSharp {
                                
                                set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
                        } else {
-                               // Compatibility for an older version of the class libs.
-                               set_corlib_type_builders = GetMethod (
-                                       system_assemblybuilder_type, "SetCorlibTypeBuilders",
-                                       system_3_type_arg, true, true);
-
-                               if (set_corlib_type_builders == null) {
-                                       Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
-                                       return;
-                               }
-
-                               object[] args = new object [3];
-                               args [0] = object_type;
-                               args [1] = value_type;
-                               args [2] = enum_type;
-                               
-                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
+                               Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
+                                       TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
+                                       TypeManager.CSharpName (system_4_type_arg));
                        }
                }
 
@@ -1215,190 +1146,14 @@ namespace Mono.CSharp {
                system_uint64_expr.Type = uint64_type;
                system_char_expr.Type = char_type;
                system_void_expr.Type = void_type;
-               system_asynccallback_expr.Type = asynccallback_type;
-               system_iasyncresult_expr.Type = iasyncresult_type;
 
                //
                // These are only used for compare purposes
                //
                anonymous_method_type = typeof (AnonymousMethod);
-               null_type = typeof (NullType);
+               null_type = typeof (NullLiteral);
        }
 
-       //
-       // The helper methods that are used by the compiler
-       //
-       public static void InitCodeHelpers ()
-       {
-               //
-               // Now load the default methods that we use.
-               //
-               Type [] string_string = { string_type, string_type };
-               string_concat_string_string = GetMethod (
-                       string_type, "Concat", string_string);
-               Type [] string_string_string = { string_type, string_type, string_type };
-               string_concat_string_string_string = GetMethod (
-                       string_type, "Concat", string_string_string);
-               Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
-               string_concat_string_string_string_string = GetMethod (
-                       string_type, "Concat", string_string_string_string);
-               Type[] params_string = { GetConstructedType (string_type, "[]") };
-               string_concat_string_dot_dot_dot = GetMethod (
-                       string_type, "Concat", params_string);
-
-               Type [] object_object = { object_type, object_type };
-               string_concat_object_object = GetMethod (
-                       string_type, "Concat", object_object);
-               Type [] object_object_object = { object_type, object_type, object_type };
-               string_concat_object_object_object = GetMethod (
-                       string_type, "Concat", object_object_object);
-               Type[] params_object = { GetConstructedType (object_type, "[]") };
-               string_concat_object_dot_dot_dot = GetMethod (
-                       string_type, "Concat", params_object);
-
-               Type [] string_ = { string_type };
-               string_isinterned_string = GetMethod (
-                       string_type, "IsInterned", string_);
-               
-               Type [] runtime_type_handle = { runtime_handle_type };
-               system_type_get_type_from_handle = GetMethod (
-                       type_type, "GetTypeFromHandle", runtime_type_handle);
-
-               Type [] delegate_delegate = { delegate_type, delegate_type };
-               delegate_combine_delegate_delegate = GetMethod (
-                               delegate_type, "Combine", delegate_delegate);
-
-               delegate_remove_delegate_delegate = GetMethod (
-                               delegate_type, "Remove", delegate_delegate);
-
-               //
-               // Void arguments
-               //
-               ienumerator_getcurrent = GetProperty (
-                       ienumerator_type, "Current");
-               bool_movenext_void = GetMethod (
-                       ienumerator_type, "MoveNext", Type.EmptyTypes);
-               void_reset_void = GetMethod (
-                       ienumerator_type, "Reset", Type.EmptyTypes);
-               void_dispose_void = GetMethod (
-                       idisposable_type, "Dispose", Type.EmptyTypes);
-               int_get_offset_to_string_data = GetMethod (
-                       runtime_helpers_type, "get_OffsetToStringData", Type.EmptyTypes);
-               int_array_get_length = GetMethod (
-                       array_type, "get_Length", Type.EmptyTypes);
-               int_array_get_rank = GetMethod (
-                       array_type, "get_Rank", Type.EmptyTypes);
-               ienumerable_getenumerator_void = GetMethod (
-                       ienumerable_type, "GetEnumerator", Type.EmptyTypes);
-               
-               //
-               // Int32 arguments
-               //
-               Type [] int_arg = { int32_type };
-               int_array_get_length_int = GetMethod (
-                       array_type, "GetLength", int_arg);
-               int_array_get_upper_bound_int = GetMethod (
-                       array_type, "GetUpperBound", int_arg);
-               int_array_get_lower_bound_int = GetMethod (
-                       array_type, "GetLowerBound", int_arg);
-
-               //
-               // System.Array methods
-               //
-               object_array_clone = GetMethod (
-                       array_type, "Clone", Type.EmptyTypes);
-               Type [] array_int_arg = { array_type, int32_type };
-               void_array_copyto_array_int = GetMethod (
-                       array_type, "CopyTo", array_int_arg);
-               
-               //
-               // object arguments
-               //
-               Type [] object_arg = { object_type };
-               void_monitor_enter_object = GetMethod (
-                       monitor_type, "Enter", object_arg);
-               void_monitor_exit_object = GetMethod (
-                       monitor_type, "Exit", object_arg);
-
-               Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
-               
-               void_initializearray_array_fieldhandle = GetMethod (
-                       runtime_helpers_type, "InitializeArray", array_field_handle_arg);
-
-               //
-               // Array functions
-               //
-               int_getlength_int = GetMethod (
-                       array_type, "GetLength", int_arg);
-
-               //
-               // Decimal constructors
-               //
-               Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
-               void_decimal_ctor_five_args = GetConstructor (
-                       decimal_type, dec_arg);
-               
-               void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
-
-               //
-               // Attributes
-               //
-               unverifiable_code_ctor = GetConstructor (unverifiable_code_type, Type.EmptyTypes);
-               default_member_ctor = GetConstructor (default_member_type, string_);
-               cons_param_array_attribute = GetConstructor (param_array_type, Type.EmptyTypes);
-
-               Type[] short_arg = { short_type };
-               // fails for .net 2.1
-               struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg, false);
-
-               decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
-                       { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
-
-               field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
-                       { int32_type });
-
-               //
-               // System.Threading.CompareExchange
-               //
-               Type[] compare_exchange_types = {
-                       GetReferenceType (int32_type), int32_type, int32_type };
-               int_interlocked_compare_exchange = GetMethod (
-                       interlocked_type, "CompareExchange", compare_exchange_types);
-
-               //
-               // .NET 2.0 types
-               //
-#if NET_2_0
-               compiler_generated_attr = new CustomAttributeBuilder (
-                       GetConstructor (compiler_generated_attr_type, Type.EmptyTypes), new object[0]);
-
-               Type[] type_int_arg = { type_type, int32_type };
-               fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
-
-               // C# 3.0
-               InitSystemCore ();
-#endif
-
-               // Object
-               object_ctor = GetConstructor (object_type, Type.EmptyTypes);
-
-#if GMCS_SOURCE
-               InitGenericCodeHelpers ();
-#endif
-       }
-
-#if GMCS_SOURCE
-       static void InitSystemCore ()
-       {
-               if (RootContext.Version != LanguageVersion.LINQ)
-                       return;
-
-               if (extension_attribute_type != null)
-                       extension_attribute_attr = new CustomAttributeBuilder (
-                               GetConstructor (extension_attribute_type, Type.EmptyTypes), new object[0]);
-       }
-#endif
-
        const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
 
        /// <remarks>
@@ -1605,11 +1360,6 @@ namespace Mono.CSharp {
                        return false;
        }
 
-       public static bool IsBuiltinType (TypeContainer tc)
-       {
-               return IsBuiltinType (tc.TypeBuilder);
-       }
-
        //
        // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
        // the pieces in the code where we use IsBuiltinType and special case decimal_type.
@@ -1629,24 +1379,17 @@ namespace Mono.CSharp {
                        return false;
 #endif
 
-               t = DropGenericTypeArguments (t);
-               if (t.IsSubclassOf (TypeManager.delegate_type))
-                       return true;
-               else
+               if (t == TypeManager.delegate_type)
                        return false;
+
+               t = DropGenericTypeArguments (t);
+               return IsSubclassOf (t, TypeManager.delegate_type);
        }
        
        public static bool IsEnumType (Type t)
        {
                t = DropGenericTypeArguments (t);
-               if (builder_to_declspace [t] is Enum)
-                       return true;
-
-#if MS_COMPATIBLE && GMCS_SOURCE
-               if (t.IsGenericParameter || t.IsGenericType)
-                       return false;
-#endif
-               return t.IsEnum;
+               return t.BaseType == TypeManager.enum_type;
        }
 
        public static bool IsBuiltinOrEnum (Type t)
@@ -1660,11 +1403,6 @@ namespace Mono.CSharp {
                return false;
        }
 
-       public static bool IsNullType (Type t)
-       {
-               return t == null_type;
-       }
-
        public static bool IsAttributeType (Type t)
        {
                return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
@@ -1878,18 +1616,19 @@ namespace Mono.CSharp {
                return false;
        }
 
-#if GMCS_SOURCE
        //
        // Checks whether `extern_type' is friend of the output assembly
        //
-       public static bool IsFriendAssembly (Assembly assembly)
+       public static bool IsThisOrFriendAssembly (Assembly assembly)
        {
-               // FIXME: This should not be reached
                if (assembly == CodeGen.Assembly.Builder)
-                       return false;
+                       return true;
 
                if (assembly_internals_vis_attrs.Contains (assembly))
                        return (bool)(assembly_internals_vis_attrs [assembly]);
+                               
+               if (internals_visible_attr_type == null)
+                       return false;
                
                object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
                if (attrs.Length == 0) {
@@ -1897,9 +1636,10 @@ namespace Mono.CSharp {
                        return false;
                }
 
+               bool is_friend = false;
+#if GMCS_SOURCE
                AssemblyName this_name = CodeGen.Assembly.Name;
                byte [] this_token = this_name.GetPublicKeyToken ();
-               bool is_friend = false;
                foreach (InternalsVisibleToAttribute attr in attrs) {
                        if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
                                continue;
@@ -1929,11 +1669,12 @@ namespace Mono.CSharp {
                        is_friend = true;
                        break;
                }
-
+#endif
                assembly_internals_vis_attrs.Add (assembly, is_friend);
                return is_friend;
        }
 
+#if GMCS_SOURCE
        static bool CompareKeyTokens (byte [] token1, byte [] token2)
        {
                for (int i = 0; i < token1.Length; i++)
@@ -1950,13 +1691,8 @@ namespace Mono.CSharp {
                                "'. Try adding a reference to `" + other_name + 
                                "' or change the output assembly name to match it");
        }
-#else
-       public static bool IsFriendAssembly (Assembly assembly)
-       {
-               return false;
-       }
 #endif
-       
+
         //
         // Do the right thing when returning the element type of an
         // array type based on whether we are compiling corlib or not
@@ -1976,6 +1712,21 @@ namespace Mono.CSharp {
        {
                return t.IsArray || t.IsPointer || t.IsByRef;
        }
+
+       public static Type GetEnumUnderlyingType (Type t)
+       {
+               t = DropGenericTypeArguments (t);
+               Enum e = LookupTypeContainer (t) as Enum;
+               if (e != null)
+                       return e.UnderlyingType;
+
+               // TODO: cache it ?
+               FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null);
+               if (fi == null)
+                       return TypeManager.int32_type;
+
+               return TypeToCoreType (fi.FieldType);
+       }
        
        /// <summary>
        ///   Gigantic work around for missing features in System.Reflection.Emit follows.
@@ -2174,7 +1925,7 @@ namespace Mono.CSharp {
        public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
                                              Hashtable hash)
        {
-               if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
+               if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
                        return true;
 
                //
@@ -2421,7 +2172,7 @@ namespace Mono.CSharp {
                        if (conversionType.Equals (typeof (DateTime)))
                                return (object)(convert_value.ToDateTime (nf_provider));
 
-                       if (conversionType.Equals (TypeManager.decimal_type)) {
+                       if (conversionType.Equals (decimal_type)) {
                                if (convert_value.GetType () == TypeManager.char_type)
                                        return (decimal)convert_value.ToInt32 (nf_provider);
                                return convert_value.ToDecimal (nf_provider);
@@ -2435,9 +2186,9 @@ namespace Mono.CSharp {
 
                        if (conversionType.Equals (typeof (Int16)))
                                return (object)(convert_value.ToInt16 (nf_provider));
-                       if (conversionType.Equals (typeof (Int32)))
+                       if (conversionType.Equals (int32_type))
                                return (object)(convert_value.ToInt32 (nf_provider));
-                       if (conversionType.Equals (typeof (Int64)))
+                       if (conversionType.Equals (int64_type))
                                return (object)(convert_value.ToInt64 (nf_provider));
                        if (conversionType.Equals (typeof (SByte)))
                                return (object)(convert_value.ToSByte (nf_provider));
@@ -2467,68 +2218,12 @@ namespace Mono.CSharp {
        }
 
        //
-       // This is needed, because enumerations from assemblies
-       // do not report their underlyingtype, but they report
-       // themselves
-       //
-       public static Type EnumToUnderlying (Type t)
-       {
-               t = DropGenericTypeArguments (t);
-               if (t == TypeManager.enum_type)
-                       return t;
-
-               t = t.UnderlyingSystemType;
-               if (!TypeManager.IsEnumType (t))
-                       return t;
-       
-               if (t is TypeBuilder) {
-                       // slow path needed to compile corlib
-                       if (t == TypeManager.bool_type ||
-                           t == TypeManager.byte_type ||
-                           t == TypeManager.sbyte_type ||
-                           t == TypeManager.char_type ||
-                           t == TypeManager.short_type ||
-                           t == TypeManager.ushort_type ||
-                           t == TypeManager.int32_type ||
-                           t == TypeManager.uint32_type ||
-                           t == TypeManager.int64_type ||
-                           t == TypeManager.uint64_type)
-                               return t;
-               }
-               TypeCode tc = Type.GetTypeCode (t);
-
-               switch (tc){
-               case TypeCode.Boolean:
-                       return TypeManager.bool_type;
-               case TypeCode.Byte:
-                       return TypeManager.byte_type;
-               case TypeCode.SByte:
-                       return TypeManager.sbyte_type;
-               case TypeCode.Char:
-                       return TypeManager.char_type;
-               case TypeCode.Int16:
-                       return TypeManager.short_type;
-               case TypeCode.UInt16:
-                       return TypeManager.ushort_type;
-               case TypeCode.Int32:
-                       return TypeManager.int32_type;
-               case TypeCode.UInt32:
-                       return TypeManager.uint32_type;
-               case TypeCode.Int64:
-                       return TypeManager.int64_type;
-               case TypeCode.UInt64:
-                       return TypeManager.uint64_type;
-               }
-               throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
-       }
-
-       //
-       // When compiling corlib and called with one of the core types, return
-       // the corresponding typebuilder for that type.
+       // When compiling with -nostdlib and the type is imported from an external assembly
+       // SRE uses "wrong" type and we have to convert it to the right compiler instance.
        //
        public static Type TypeToCoreType (Type t)
        {
-               if (RootContext.StdLib || (t is TypeBuilder))
+               if (RootContext.StdLib || t.Module != typeof (object).Module)
                        return t;
 
                TypeCode tc = Type.GetTypeCode (t);
@@ -2562,17 +2257,34 @@ namespace Mono.CSharp {
                        return TypeManager.string_type;
                case TypeCode.Decimal:
                        return TypeManager.decimal_type;
-               default:
-                       if (t == typeof (void))
-                               return TypeManager.void_type;
-                       if (t == typeof (object))
-                               return TypeManager.object_type;
-                       if (t == typeof (System.Type))
-                               return TypeManager.type_type;
-                       if (t == typeof (System.IntPtr))
-                               return TypeManager.intptr_type;
-                       return t;
                }
+
+               if (t == typeof (void))
+                       return TypeManager.void_type;
+               if (t == typeof (object))
+                       return TypeManager.object_type;
+               if (t == typeof (System.Type))
+                       return TypeManager.type_type;
+               if (t == typeof (System.IntPtr))
+                       return TypeManager.intptr_type;
+               if (t == typeof (System.UIntPtr))
+                       return TypeManager.uintptr_type;
+#if GMCS_SOURCE
+               if (t.IsArray) {
+                       int dim = t.GetArrayRank ();
+                       t = GetElementType (t);
+                       return t.MakeArrayType (dim);
+               }
+               if (t.IsByRef) {
+                       t = GetElementType (t);
+                       return t.MakeByRefType ();
+               }
+               if (t.IsPointer) {
+                       t = GetElementType (t);
+                       return t.MakePointerType ();
+               }
+#endif
+               return t;
        }
 
        /// <summary>
@@ -2711,11 +2423,11 @@ namespace Mono.CSharp {
                        if (method.Name != new_method.Name)
                                continue;
 
-                        if (method is MethodInfo && new_method is MethodInfo)
-                                if (!IsSignatureEqual (((MethodInfo) method).ReturnType,
-                                                      ((MethodInfo) new_method).ReturnType))
-                                        continue;
-
+                       if (method is MethodInfo && new_method is MethodInfo &&
+                               !IsSignatureEqual (
+                                       TypeToCoreType (((MethodInfo) method).ReturnType),
+                                       TypeToCoreType (((MethodInfo) new_method).ReturnType)))
+                               continue;
                         
                        Type [] old_args = TypeManager.GetParameterData (method).Types;
                        int old_count = old_args.Length;
@@ -2907,6 +2619,19 @@ namespace Mono.CSharp {
                return false;
        }
 
+       public static bool IsEqual (Type[] a, Type[] b)
+       {
+               if (a.Length != b.Length)
+                       return false;
+
+               for (int i = 0; i < a.Length; ++i) {
+                       if (!IsEqual (a [i], b [i]))
+                               return false;
+               }
+
+               return true;
+       }
+
        public static Type DropGenericTypeArguments (Type t)
        {
 #if GMCS_SOURCE
@@ -2924,14 +2649,14 @@ namespace Mono.CSharp {
        public static MethodBase DropGenericMethodArguments (MethodBase m)
        {
 #if GMCS_SOURCE
-               if (m.IsGenericMethodDefinition)
-                       return m;
                if (m.IsGenericMethod)
-                       return ((MethodInfo) m).GetGenericMethodDefinition ();
-               if (!m.DeclaringType.IsGenericType)
+                 m = ((MethodInfo) m).GetGenericMethodDefinition ();
+
+               Type t = m.DeclaringType;
+               if (!t.IsGenericType || t.IsGenericTypeDefinition)
                        return m;
 
-               Type t = m.DeclaringType.GetGenericTypeDefinition ();
+               t = t.GetGenericTypeDefinition ();
                BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
 
@@ -3194,8 +2919,7 @@ namespace Mono.CSharp {
                                                IsPrivateAccessible (invocation_type, m.DeclaringType) ||
                                                IsNestedChildOf (invocation_type, m.DeclaringType);
 
-                               if (invocation_assembly == mb.DeclaringType.Assembly ||
-                                   TypeManager.IsFriendAssembly (mb.DeclaringType.Assembly)) {
+                               if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
                                        if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
                                                return true;
                                } else {
@@ -3222,9 +2946,7 @@ namespace Mono.CSharp {
                                                IsPrivateAccessible (invocation_type, m.DeclaringType) ||
                                                IsNestedChildOf (invocation_type, m.DeclaringType);
 
-                               if ((invocation_assembly == fi.DeclaringType.Assembly) ||
-                                   (invocation_assembly == null) ||
-                                   TypeManager.IsFriendAssembly (fi.DeclaringType.Assembly)) {
+                               if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
                                        if ((fa == FieldAttributes.Assembly) ||
                                            (fa == FieldAttributes.FamORAssem))
                                                return true;
@@ -3734,18 +3456,4 @@ public sealed class TypeHandle : IMemberContainer {
                        return "TypeHandle (" + id + "," + Name + ")";
        }
 }
-
-       //
-       // Common expressions used by expression trees
-       //
-       static class ExpressionTreeManager
-       {
-               public static MemberAccess Namespace = new MemberAccess (
-                       new MemberAccess (new SimpleName ("System", Location.Null), "Linq", Location.Null),
-                       "Expressions", Location.Null);
-                       
-               public static MemberAccess Type =
-                       new MemberAccess (Namespace, "Expression", Location.Null);
-       }
-
 }