EmitContext.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // EmitContext.cs
  3. //
  4. // Author:
  5. // Miguel de Icaza ([email protected])
  6. // Jb Evain ([email protected])
  7. //
  8. // (C) 2008 Novell, Inc. (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.ObjectModel;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Reflection;
  35. using System.Reflection.Emit;
  36. using System.Runtime.CompilerServices;
  37. namespace System.Linq.Expressions {
  38. abstract class EmitContext {
  39. protected LambdaExpression owner;
  40. protected Type [] param_types;
  41. protected Type return_type;
  42. protected List<object> globals = new List<object> ();
  43. public ILGenerator ig;
  44. protected EmitContext (LambdaExpression lambda)
  45. {
  46. this.owner = lambda;
  47. param_types = CreateParameterTypes (owner.Parameters);
  48. return_type = owner.GetReturnType ();
  49. }
  50. static Type [] CreateParameterTypes (ReadOnlyCollection<ParameterExpression> parameters)
  51. {
  52. var types = new Type [parameters.Count + 1];
  53. types [0] = typeof (ExecutionScope);
  54. for (int i = 0; i < parameters.Count; i++)
  55. types [i + 1] = parameters [i].Type;
  56. return types;
  57. }
  58. public static EmitContext Create (LambdaExpression lambda)
  59. {
  60. #if !NET_2_1
  61. if (Environment.GetEnvironmentVariable ("LINQ_DBG") != null)
  62. return new DebugEmitContext (lambda);
  63. #endif
  64. return new DynamicEmitContext (lambda);
  65. }
  66. public int GetParameterPosition (ParameterExpression p)
  67. {
  68. int position = owner.Parameters.IndexOf (p);
  69. if (position == -1)
  70. throw new InvalidOperationException ("Parameter not in scope");
  71. return position + 1; // + 1 because 0 is the ExecutionScope
  72. }
  73. public abstract Delegate CreateDelegate ();
  74. public void Emit (Expression expression)
  75. {
  76. expression.Emit (this);
  77. }
  78. public LocalBuilder EmitStored (Expression expression)
  79. {
  80. var local = ig.DeclareLocal (expression.Type);
  81. expression.Emit (this);
  82. ig.Emit (OpCodes.Stloc, local);
  83. return local;
  84. }
  85. public void EmitLoad (Expression expression)
  86. {
  87. if (expression.Type.IsValueType) {
  88. var local = EmitStored (expression);
  89. ig.Emit (OpCodes.Ldloca, local);
  90. } else
  91. expression.Emit (this);
  92. }
  93. public void EmitLoad (LocalBuilder local)
  94. {
  95. ig.Emit (OpCodes.Ldloc, local);
  96. }
  97. public void EmitCall (LocalBuilder local, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  98. {
  99. EmitLoad (local);
  100. EmitArguments (method, arguments);
  101. EmitCall (method);
  102. }
  103. public void EmitCall (Expression expression, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  104. {
  105. if (!method.IsStatic)
  106. EmitLoad (expression);
  107. EmitArguments (method, arguments);
  108. EmitCall (method);
  109. }
  110. void EmitArguments (MethodInfo method, ReadOnlyCollection<Expression> arguments)
  111. {
  112. var parameters = method.GetParameters ();
  113. for (int i = 0; i < parameters.Length; i++) {
  114. var parameter = parameters [i];
  115. var argument = arguments [i];
  116. if (parameter.ParameterType.IsByRef) {
  117. ig.Emit (OpCodes.Ldloca, EmitStored (argument));
  118. return;
  119. }
  120. Emit (arguments [i]);
  121. }
  122. }
  123. public void EmitCall (MethodInfo method)
  124. {
  125. ig.Emit (
  126. method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call,
  127. method);
  128. }
  129. public void EmitCollection<T> (IEnumerable<T> collection) where T : Expression
  130. {
  131. foreach (var expression in collection)
  132. expression.Emit (this);
  133. }
  134. public void EmitCollection (IEnumerable<ElementInit> initializers, LocalBuilder local)
  135. {
  136. foreach (var initializer in initializers)
  137. initializer.Emit (this, local);
  138. }
  139. public void EmitCollection (IEnumerable<MemberBinding> bindings, LocalBuilder local)
  140. {
  141. foreach (var binding in bindings)
  142. binding.Emit (this, local);
  143. }
  144. public void EmitIsInst (Expression expression, Type candidate)
  145. {
  146. expression.Emit (this);
  147. if (expression.Type.IsValueType)
  148. ig.Emit (OpCodes.Box, expression.Type);
  149. ig.Emit (OpCodes.Isinst, candidate);
  150. }
  151. public void EmitScope ()
  152. {
  153. ig.Emit (OpCodes.Ldarg_0);
  154. }
  155. public void EmitReadGlobal (object global)
  156. {
  157. EmitReadGlobal (global, global.GetType ());
  158. }
  159. public void EmitReadGlobal (object global, Type type)
  160. {
  161. EmitScope ();
  162. ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
  163. ig.Emit (OpCodes.Ldc_I4, AddGlobal (global, type));
  164. ig.Emit (OpCodes.Ldelem, typeof (object));
  165. var strongbox = type.MakeStrongBoxType ();
  166. ig.Emit (OpCodes.Isinst, strongbox);
  167. ig.Emit (OpCodes.Ldfld, strongbox.GetField ("Value"));
  168. }
  169. int AddGlobal (object value, Type type)
  170. {
  171. globals.Add (CreateStrongBox (value, type));
  172. return globals.Count - 1;
  173. }
  174. static object CreateStrongBox (object value, Type type)
  175. {
  176. return Activator.CreateInstance (
  177. type.MakeStrongBoxType (), value);
  178. }
  179. }
  180. class DynamicEmitContext : EmitContext {
  181. DynamicMethod method;
  182. static object mlock = new object ();
  183. static int method_count;
  184. public DynamicMethod Method {
  185. get { return method; }
  186. }
  187. public DynamicEmitContext (LambdaExpression lambda)
  188. : base (lambda)
  189. {
  190. // FIXME: Need to force this to be verifiable, see:
  191. // https://bugzilla.novell.com/show_bug.cgi?id=355005
  192. method = new DynamicMethod (GenerateName (), return_type, param_types, typeof (ExecutionScope), true);
  193. ig = method.GetILGenerator ();
  194. owner.Emit (this);
  195. }
  196. public override Delegate CreateDelegate ()
  197. {
  198. return method.CreateDelegate (owner.Type, new ExecutionScope (globals.ToArray ()));
  199. }
  200. static string GenerateName ()
  201. {
  202. lock (mlock) {
  203. return "lambda_method-" + (method_count++);
  204. }
  205. }
  206. }
  207. #if !NET_2_1
  208. class DebugEmitContext : DynamicEmitContext {
  209. public DebugEmitContext (LambdaExpression lambda)
  210. : base (lambda)
  211. {
  212. var name = Method.Name;
  213. var file_name = name + ".dll";
  214. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  215. new AssemblyName (name), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  216. var type = assembly.DefineDynamicModule (file_name, file_name).DefineType ("Linq", TypeAttributes.Public);
  217. var method = type.DefineMethod (name, MethodAttributes.Public | MethodAttributes.Static, return_type, param_types);
  218. ig = method.GetILGenerator ();
  219. owner.Emit (this);
  220. type.CreateType ();
  221. assembly.Save (file_name);
  222. }
  223. }
  224. #endif
  225. }