[sgen] Exclusive write on binary protocol file
[mono.git] / mono / mini / method-to-ir.c
1 /*
2  * method-to-ir.c: Convert CIL to the JIT internal representation
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #include <config.h>
15
16 #ifndef DISABLE_JIT
17
18 #include <signal.h>
19
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include <math.h>
25 #include <string.h>
26 #include <ctype.h>
27
28 #ifdef HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #endif
31
32 #ifdef HAVE_ALLOCA_H
33 #include <alloca.h>
34 #endif
35
36 #include <mono/utils/memcheck.h>
37 #include "mini.h"
38 #include <mono/metadata/abi-details.h>
39 #include <mono/metadata/assembly.h>
40 #include <mono/metadata/attrdefs.h>
41 #include <mono/metadata/loader.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/exception.h>
46 #include <mono/metadata/opcodes.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/tokentype.h>
49 #include <mono/metadata/tabledefs.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/mono-debug.h>
53 #include <mono/metadata/mono-debug-debugger.h>
54 #include <mono/metadata/gc-internals.h>
55 #include <mono/metadata/security-manager.h>
56 #include <mono/metadata/threads-types.h>
57 #include <mono/metadata/security-core-clr.h>
58 #include <mono/metadata/profiler-private.h>
59 #include <mono/metadata/profiler.h>
60 #include <mono/metadata/monitor.h>
61 #include <mono/metadata/debug-mono-symfile.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-memory-model.h>
64 #include <mono/utils/mono-error-internals.h>
65 #include <mono/metadata/mono-basic-block.h>
66 #include <mono/metadata/reflection-internals.h>
67
68 #include "trace.h"
69
70 #include "ir-emit.h"
71
72 #include "jit-icalls.h"
73 #include "jit.h"
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "aot-compiler.h"
77 #include "mini-llvm.h"
78
79 #define BRANCH_COST 10
80 #define INLINE_LENGTH_LIMIT 20
81
82 /* These have 'cfg' as an implicit argument */
83 #define INLINE_FAILURE(msg) do {                                                                        \
84         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
85                 inline_failure (cfg, msg);                                                                              \
86                 goto exception_exit;                                                                                    \
87         } \
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
91                         goto exception_exit;                                            \
92         } while (0)
93 #define METHOD_ACCESS_FAILURE(method, cmethod) do {                     \
94                 method_access_failure ((cfg), (method), (cmethod));                     \
95                 goto exception_exit;                                                                            \
96         } while (0)
97 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
98                 field_access_failure ((cfg), (method), (field));                        \
99                 goto exception_exit;    \
100         } while (0)
101 #define GENERIC_SHARING_FAILURE(opcode) do {            \
102                 if (cfg->gshared) {                                                                     \
103                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
104                         goto exception_exit;    \
105                 }                       \
106         } while (0)
107 #define GSHAREDVT_FAILURE(opcode) do {          \
108         if (cfg->gsharedvt) {                                                                                           \
109                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
110                 goto exception_exit;                                                                                    \
111         }                                                                                                                                       \
112         } while (0)
113 #define OUT_OF_MEMORY_FAILURE do {      \
114                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
115                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
116                 goto exception_exit;    \
117         } while (0)
118 #define DISABLE_AOT(cfg) do { \
119                 if ((cfg)->verbose_level >= 2)                                            \
120                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
121                 (cfg)->disable_aot = TRUE;                                                        \
122         } while (0)
123 #define LOAD_ERROR do { \
124                 break_on_unverified ();                                                         \
125                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
126                 goto exception_exit;                                                                    \
127         } while (0)
128
129 #define TYPE_LOAD_ERROR(klass) do { \
130                 cfg->exception_ptr = klass; \
131                 LOAD_ERROR;                                     \
132         } while (0)
133
134 #define CHECK_CFG_ERROR do {\
135                 if (!mono_error_ok (&cfg->error)) { \
136                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
137                         goto mono_error_exit; \
138                 } \
139         } while (0)
140
141 /* Determine whenever 'ins' represents a load of the 'this' argument */
142 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
143
144 static int ldind_to_load_membase (int opcode);
145 static int stind_to_store_membase (int opcode);
146
147 int mono_op_to_op_imm (int opcode);
148 int mono_op_to_op_imm_noemul (int opcode);
149
150 MONO_API MonoInst* mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig, MonoInst **args);
151
152 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
153                                                   guchar *ip, guint real_offset, gboolean inline_always);
154 static MonoInst*
155 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
156
157 /* helper methods signatures */
158 static MonoMethodSignature *helper_sig_domain_get;
159 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
160 static MonoMethodSignature *helper_sig_llvmonly_imt_thunk;
161
162
163 /* type loading helpers */
164 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, System.Runtime.CompilerServices, RuntimeHelpers)
165 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, System.Diagnostics, DebuggableAttribute)
166
167 /*
168  * Instruction metadata
169  */
170 #ifdef MINI_OP
171 #undef MINI_OP
172 #endif
173 #ifdef MINI_OP3
174 #undef MINI_OP3
175 #endif
176 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
177 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
178 #define NONE ' '
179 #define IREG 'i'
180 #define FREG 'f'
181 #define VREG 'v'
182 #define XREG 'x'
183 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
184 #define LREG IREG
185 #else
186 #define LREG 'l'
187 #endif
188 /* keep in sync with the enum in mini.h */
189 const char
190 ins_info[] = {
191 #include "mini-ops.h"
192 };
193 #undef MINI_OP
194 #undef MINI_OP3
195
196 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
197 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
198 /* 
199  * This should contain the index of the last sreg + 1. This is not the same
200  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
201  */
202 const gint8 ins_sreg_counts[] = {
203 #include "mini-ops.h"
204 };
205 #undef MINI_OP
206 #undef MINI_OP3
207
208 #define MONO_INIT_VARINFO(vi,id) do { \
209         (vi)->range.first_use.pos.bid = 0xffff; \
210         (vi)->reg = -1; \
211         (vi)->idx = (id); \
212 } while (0)
213
214 guint32
215 mono_alloc_ireg (MonoCompile *cfg)
216 {
217         return alloc_ireg (cfg);
218 }
219
220 guint32
221 mono_alloc_lreg (MonoCompile *cfg)
222 {
223         return alloc_lreg (cfg);
224 }
225
226 guint32
227 mono_alloc_freg (MonoCompile *cfg)
228 {
229         return alloc_freg (cfg);
230 }
231
232 guint32
233 mono_alloc_preg (MonoCompile *cfg)
234 {
235         return alloc_preg (cfg);
236 }
237
238 guint32
239 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
240 {
241         return alloc_dreg (cfg, stack_type);
242 }
243
244 /*
245  * mono_alloc_ireg_ref:
246  *
247  *   Allocate an IREG, and mark it as holding a GC ref.
248  */
249 guint32
250 mono_alloc_ireg_ref (MonoCompile *cfg)
251 {
252         return alloc_ireg_ref (cfg);
253 }
254
255 /*
256  * mono_alloc_ireg_mp:
257  *
258  *   Allocate an IREG, and mark it as holding a managed pointer.
259  */
260 guint32
261 mono_alloc_ireg_mp (MonoCompile *cfg)
262 {
263         return alloc_ireg_mp (cfg);
264 }
265
266 /*
267  * mono_alloc_ireg_copy:
268  *
269  *   Allocate an IREG with the same GC type as VREG.
270  */
271 guint32
272 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
273 {
274         if (vreg_is_ref (cfg, vreg))
275                 return alloc_ireg_ref (cfg);
276         else if (vreg_is_mp (cfg, vreg))
277                 return alloc_ireg_mp (cfg);
278         else
279                 return alloc_ireg (cfg);
280 }
281
282 guint
283 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
284 {
285         if (type->byref)
286                 return OP_MOVE;
287
288         type = mini_get_underlying_type (type);
289 handle_enum:
290         switch (type->type) {
291         case MONO_TYPE_I1:
292         case MONO_TYPE_U1:
293                 return OP_MOVE;
294         case MONO_TYPE_I2:
295         case MONO_TYPE_U2:
296                 return OP_MOVE;
297         case MONO_TYPE_I4:
298         case MONO_TYPE_U4:
299                 return OP_MOVE;
300         case MONO_TYPE_I:
301         case MONO_TYPE_U:
302         case MONO_TYPE_PTR:
303         case MONO_TYPE_FNPTR:
304                 return OP_MOVE;
305         case MONO_TYPE_CLASS:
306         case MONO_TYPE_STRING:
307         case MONO_TYPE_OBJECT:
308         case MONO_TYPE_SZARRAY:
309         case MONO_TYPE_ARRAY:    
310                 return OP_MOVE;
311         case MONO_TYPE_I8:
312         case MONO_TYPE_U8:
313 #if SIZEOF_REGISTER == 8
314                 return OP_MOVE;
315 #else
316                 return OP_LMOVE;
317 #endif
318         case MONO_TYPE_R4:
319                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
320         case MONO_TYPE_R8:
321                 return OP_FMOVE;
322         case MONO_TYPE_VALUETYPE:
323                 if (type->data.klass->enumtype) {
324                         type = mono_class_enum_basetype (type->data.klass);
325                         goto handle_enum;
326                 }
327                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
328                         return OP_XMOVE;
329                 return OP_VMOVE;
330         case MONO_TYPE_TYPEDBYREF:
331                 return OP_VMOVE;
332         case MONO_TYPE_GENERICINST:
333                 type = &type->data.generic_class->container_class->byval_arg;
334                 goto handle_enum;
335         case MONO_TYPE_VAR:
336         case MONO_TYPE_MVAR:
337                 g_assert (cfg->gshared);
338                 if (mini_type_var_is_vt (type))
339                         return OP_VMOVE;
340                 else
341                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
342         default:
343                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
344         }
345         return -1;
346 }
347
348 void
349 mono_print_bb (MonoBasicBlock *bb, const char *msg)
350 {
351         int i;
352         MonoInst *tree;
353
354         printf ("\n%s %d: [IN: ", msg, bb->block_num);
355         for (i = 0; i < bb->in_count; ++i)
356                 printf (" BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
357         printf (", OUT: ");
358         for (i = 0; i < bb->out_count; ++i)
359                 printf (" BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
360         printf (" ]\n");
361         for (tree = bb->code; tree; tree = tree->next)
362                 mono_print_ins_index (-1, tree);
363 }
364
365 void
366 mono_create_helper_signatures (void)
367 {
368         helper_sig_domain_get = mono_create_icall_signature ("ptr");
369         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
370         helper_sig_llvmonly_imt_thunk = mono_create_icall_signature ("ptr ptr ptr");
371 }
372
373 static MONO_NEVER_INLINE void
374 break_on_unverified (void)
375 {
376         if (mini_get_debug_options ()->break_on_unverified)
377                 G_BREAKPOINT ();
378 }
379
380 static MONO_NEVER_INLINE void
381 method_access_failure (MonoCompile *cfg, MonoMethod *method, MonoMethod *cil_method)
382 {
383         char *method_fname = mono_method_full_name (method, TRUE);
384         char *cil_method_fname = mono_method_full_name (cil_method, TRUE);
385         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
386         mono_error_set_generic_error (&cfg->error, "System", "MethodAccessException", "Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);
387         g_free (method_fname);
388         g_free (cil_method_fname);
389 }
390
391 static MONO_NEVER_INLINE void
392 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
393 {
394         char *method_fname = mono_method_full_name (method, TRUE);
395         char *field_fname = mono_field_full_name (field);
396         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
397         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
398         g_free (method_fname);
399         g_free (field_fname);
400 }
401
402 static MONO_NEVER_INLINE void
403 inline_failure (MonoCompile *cfg, const char *msg)
404 {
405         if (cfg->verbose_level >= 2)
406                 printf ("inline failed: %s\n", msg);
407         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
408 }
409
410 static MONO_NEVER_INLINE void
411 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
412 {
413         if (cfg->verbose_level > 2)                                                                                     \
414                 printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), line);
415         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
416 }
417
418 static MONO_NEVER_INLINE void
419 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
420 {
421         cfg->exception_message = g_strdup_printf ("gsharedvt failed for method %s.%s.%s/%d opcode %s %s:%d", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), file, line);
422         if (cfg->verbose_level >= 2)
423                 printf ("%s\n", cfg->exception_message);
424         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
425 }
426
427 /*
428  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
429  * foo<T> (int i) { ldarg.0; box T; }
430  */
431 #define UNVERIFIED do { \
432         if (cfg->gsharedvt) { \
433                 if (cfg->verbose_level > 2)                                                                     \
434                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
435                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
436                 goto exception_exit;                                                                                    \
437         }                                                                                                                                       \
438         break_on_unverified ();                                                                                         \
439         goto unverified;                                                                                                        \
440 } while (0)
441
442 #define GET_BBLOCK(cfg,tblock,ip) do {  \
443                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
444                 if (!(tblock)) {        \
445                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
446             NEW_BBLOCK (cfg, (tblock)); \
447                         (tblock)->cil_code = (ip);      \
448                         ADD_BBLOCK (cfg, (tblock));     \
449                 } \
450         } while (0)
451
452 #if defined(TARGET_X86) || defined(TARGET_AMD64)
453 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
454                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
455                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
456                 (dest)->sreg1 = (sr1); \
457                 (dest)->sreg2 = (sr2); \
458                 (dest)->inst_imm = (imm); \
459                 (dest)->backend.shift_amount = (shift); \
460                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
461         } while (0)
462 #endif
463
464 /* Emit conversions so both operands of a binary opcode are of the same type */
465 static void
466 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
467 {
468         MonoInst *arg1 = *arg1_ref;
469         MonoInst *arg2 = *arg2_ref;
470
471         if (cfg->r4fp &&
472                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
473                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
474                 MonoInst *conv;
475
476                 /* Mixing r4/r8 is allowed by the spec */
477                 if (arg1->type == STACK_R4) {
478                         int dreg = alloc_freg (cfg);
479
480                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
481                         conv->type = STACK_R8;
482                         ins->sreg1 = dreg;
483                         *arg1_ref = conv;
484                 }
485                 if (arg2->type == STACK_R4) {
486                         int dreg = alloc_freg (cfg);
487
488                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
489                         conv->type = STACK_R8;
490                         ins->sreg2 = dreg;
491                         *arg2_ref = conv;
492                 }
493         }
494
495 #if SIZEOF_REGISTER == 8
496         /* FIXME: Need to add many more cases */
497         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
498                 MonoInst *widen;
499
500                 int dr = alloc_preg (cfg);
501                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
502                 (ins)->sreg2 = widen->dreg;
503         }
504 #endif
505 }
506
507 #define ADD_BINOP(op) do {      \
508                 MONO_INST_NEW (cfg, ins, (op)); \
509                 sp -= 2;        \
510                 ins->sreg1 = sp [0]->dreg;      \
511                 ins->sreg2 = sp [1]->dreg;      \
512                 type_from_op (cfg, ins, sp [0], sp [1]);        \
513                 CHECK_TYPE (ins);       \
514                 /* Have to insert a widening op */               \
515         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
516         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
517         MONO_ADD_INS ((cfg)->cbb, (ins)); \
518         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
519         } while (0)
520
521 #define ADD_UNOP(op) do {       \
522                 MONO_INST_NEW (cfg, ins, (op)); \
523                 sp--;   \
524                 ins->sreg1 = sp [0]->dreg;      \
525                 type_from_op (cfg, ins, sp [0], NULL);  \
526                 CHECK_TYPE (ins);       \
527         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
528         MONO_ADD_INS ((cfg)->cbb, (ins)); \
529                 *sp++ = mono_decompose_opcode (cfg, ins);       \
530         } while (0)
531
532 #define ADD_BINCOND(next_block) do {    \
533                 MonoInst *cmp;  \
534                 sp -= 2; \
535                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
536                 cmp->sreg1 = sp [0]->dreg;      \
537                 cmp->sreg2 = sp [1]->dreg;      \
538                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
539                 CHECK_TYPE (cmp);       \
540                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
541                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
542                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
543                 GET_BBLOCK (cfg, tblock, target);               \
544                 link_bblock (cfg, cfg->cbb, tblock);    \
545                 ins->inst_true_bb = tblock;     \
546                 if ((next_block)) {     \
547                         link_bblock (cfg, cfg->cbb, (next_block));      \
548                         ins->inst_false_bb = (next_block);      \
549                         start_new_bblock = 1;   \
550                 } else {        \
551                         GET_BBLOCK (cfg, tblock, ip);           \
552                         link_bblock (cfg, cfg->cbb, tblock);    \
553                         ins->inst_false_bb = tblock;    \
554                         start_new_bblock = 2;   \
555                 }       \
556                 if (sp != stack_start) {                                                                        \
557                     handle_stack_args (cfg, stack_start, sp - stack_start); \
558                         CHECK_UNVERIFIABLE (cfg); \
559                 } \
560         MONO_ADD_INS (cfg->cbb, cmp); \
561                 MONO_ADD_INS (cfg->cbb, ins);   \
562         } while (0)
563
564 /* *
565  * link_bblock: Links two basic blocks
566  *
567  * links two basic blocks in the control flow graph, the 'from'
568  * argument is the starting block and the 'to' argument is the block
569  * the control flow ends to after 'from'.
570  */
571 static void
572 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
573 {
574         MonoBasicBlock **newa;
575         int i, found;
576
577 #if 0
578         if (from->cil_code) {
579                 if (to->cil_code)
580                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
581                 else
582                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
583         } else {
584                 if (to->cil_code)
585                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
586                 else
587                         printf ("edge from entry to exit\n");
588         }
589 #endif
590
591         found = FALSE;
592         for (i = 0; i < from->out_count; ++i) {
593                 if (to == from->out_bb [i]) {
594                         found = TRUE;
595                         break;
596                 }
597         }
598         if (!found) {
599                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
600                 for (i = 0; i < from->out_count; ++i) {
601                         newa [i] = from->out_bb [i];
602                 }
603                 newa [i] = to;
604                 from->out_count++;
605                 from->out_bb = newa;
606         }
607
608         found = FALSE;
609         for (i = 0; i < to->in_count; ++i) {
610                 if (from == to->in_bb [i]) {
611                         found = TRUE;
612                         break;
613                 }
614         }
615         if (!found) {
616                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
617                 for (i = 0; i < to->in_count; ++i) {
618                         newa [i] = to->in_bb [i];
619                 }
620                 newa [i] = from;
621                 to->in_count++;
622                 to->in_bb = newa;
623         }
624 }
625
626 void
627 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
628 {
629         link_bblock (cfg, from, to);
630 }
631
632 /**
633  * mono_find_block_region:
634  *
635  *   We mark each basic block with a region ID. We use that to avoid BB
636  *   optimizations when blocks are in different regions.
637  *
638  * Returns:
639  *   A region token that encodes where this region is, and information
640  *   about the clause owner for this block.
641  *
642  *   The region encodes the try/catch/filter clause that owns this block
643  *   as well as the type.  -1 is a special value that represents a block
644  *   that is in none of try/catch/filter.
645  */
646 static int
647 mono_find_block_region (MonoCompile *cfg, int offset)
648 {
649         MonoMethodHeader *header = cfg->header;
650         MonoExceptionClause *clause;
651         int i;
652
653         for (i = 0; i < header->num_clauses; ++i) {
654                 clause = &header->clauses [i];
655                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
656                     (offset < (clause->handler_offset)))
657                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
658                            
659                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
660                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
661                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
662                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
663                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
664                         else
665                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
666                 }
667         }
668         for (i = 0; i < header->num_clauses; ++i) {
669                 clause = &header->clauses [i];
670
671                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
672                         return ((i + 1) << 8) | clause->flags;
673         }
674
675         return -1;
676 }
677
678 static GList*
679 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
680 {
681         MonoMethodHeader *header = cfg->header;
682         MonoExceptionClause *clause;
683         int i;
684         GList *res = NULL;
685
686         for (i = 0; i < header->num_clauses; ++i) {
687                 clause = &header->clauses [i];
688                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
689                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
690                         if (clause->flags == type)
691                                 res = g_list_append (res, clause);
692                 }
693         }
694         return res;
695 }
696
697 static void
698 mono_create_spvar_for_region (MonoCompile *cfg, int region)
699 {
700         MonoInst *var;
701
702         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
703         if (var)
704                 return;
705
706         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
707         /* prevent it from being register allocated */
708         var->flags |= MONO_INST_VOLATILE;
709
710         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
711 }
712
713 MonoInst *
714 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
715 {
716         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
717 }
718
719 static MonoInst*
720 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
721 {
722         MonoInst *var;
723
724         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
725         if (var)
726                 return var;
727
728         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
729         /* prevent it from being register allocated */
730         var->flags |= MONO_INST_VOLATILE;
731
732         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
733
734         return var;
735 }
736
737 /*
738  * Returns the type used in the eval stack when @type is loaded.
739  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
740  */
741 void
742 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
743 {
744         MonoClass *klass;
745
746         type = mini_get_underlying_type (type);
747         inst->klass = klass = mono_class_from_mono_type (type);
748         if (type->byref) {
749                 inst->type = STACK_MP;
750                 return;
751         }
752
753 handle_enum:
754         switch (type->type) {
755         case MONO_TYPE_VOID:
756                 inst->type = STACK_INV;
757                 return;
758         case MONO_TYPE_I1:
759         case MONO_TYPE_U1:
760         case MONO_TYPE_I2:
761         case MONO_TYPE_U2:
762         case MONO_TYPE_I4:
763         case MONO_TYPE_U4:
764                 inst->type = STACK_I4;
765                 return;
766         case MONO_TYPE_I:
767         case MONO_TYPE_U:
768         case MONO_TYPE_PTR:
769         case MONO_TYPE_FNPTR:
770                 inst->type = STACK_PTR;
771                 return;
772         case MONO_TYPE_CLASS:
773         case MONO_TYPE_STRING:
774         case MONO_TYPE_OBJECT:
775         case MONO_TYPE_SZARRAY:
776         case MONO_TYPE_ARRAY:    
777                 inst->type = STACK_OBJ;
778                 return;
779         case MONO_TYPE_I8:
780         case MONO_TYPE_U8:
781                 inst->type = STACK_I8;
782                 return;
783         case MONO_TYPE_R4:
784                 inst->type = cfg->r4_stack_type;
785                 break;
786         case MONO_TYPE_R8:
787                 inst->type = STACK_R8;
788                 return;
789         case MONO_TYPE_VALUETYPE:
790                 if (type->data.klass->enumtype) {
791                         type = mono_class_enum_basetype (type->data.klass);
792                         goto handle_enum;
793                 } else {
794                         inst->klass = klass;
795                         inst->type = STACK_VTYPE;
796                         return;
797                 }
798         case MONO_TYPE_TYPEDBYREF:
799                 inst->klass = mono_defaults.typed_reference_class;
800                 inst->type = STACK_VTYPE;
801                 return;
802         case MONO_TYPE_GENERICINST:
803                 type = &type->data.generic_class->container_class->byval_arg;
804                 goto handle_enum;
805         case MONO_TYPE_VAR:
806         case MONO_TYPE_MVAR:
807                 g_assert (cfg->gshared);
808                 if (mini_is_gsharedvt_type (type)) {
809                         g_assert (cfg->gsharedvt);
810                         inst->type = STACK_VTYPE;
811                 } else {
812                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
813                 }
814                 return;
815         default:
816                 g_error ("unknown type 0x%02x in eval stack type", type->type);
817         }
818 }
819
820 /*
821  * The following tables are used to quickly validate the IL code in type_from_op ().
822  */
823 static const char
824 bin_num_table [STACK_MAX] [STACK_MAX] = {
825         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
826         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
827         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
828         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
829         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
830         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
831         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
832         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
834 };
835
836 static const char 
837 neg_table [] = {
838         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
839 };
840
841 /* reduce the size of this table */
842 static const char
843 bin_int_table [STACK_MAX] [STACK_MAX] = {
844         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
845         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
846         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
847         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
848         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
849         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
850         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
851         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
852 };
853
854 static const char
855 bin_comp_table [STACK_MAX] [STACK_MAX] = {
856 /*      Inv i  L  p  F  &  O  vt r4 */
857         {0},
858         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
859         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
860         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
861         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
862         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
863         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
864         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
865         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
866 };
867
868 /* reduce the size of this table */
869 static const char
870 shift_table [STACK_MAX] [STACK_MAX] = {
871         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
872         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
873         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
874         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
875         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
876         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
877         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
878         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
879 };
880
881 /*
882  * Tables to map from the non-specific opcode to the matching
883  * type-specific opcode.
884  */
885 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
886 static const guint16
887 binops_op_map [STACK_MAX] = {
888         0, OP_IADD-CEE_ADD, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD, 0, 0, OP_RADD-CEE_ADD
889 };
890
891 /* handles from CEE_NEG to CEE_CONV_U8 */
892 static const guint16
893 unops_op_map [STACK_MAX] = {
894         0, OP_INEG-CEE_NEG, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG, 0, 0, OP_RNEG-CEE_NEG
895 };
896
897 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
898 static const guint16
899 ovfops_op_map [STACK_MAX] = {
900         0, OP_ICONV_TO_U2-CEE_CONV_U2, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, 0, OP_RCONV_TO_U2-CEE_CONV_U2
901 };
902
903 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
904 static const guint16
905 ovf2ops_op_map [STACK_MAX] = {
906         0, OP_ICONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0, 0, OP_RCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
907 };
908
909 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
910 static const guint16
911 ovf3ops_op_map [STACK_MAX] = {
912         0, OP_ICONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0, 0, OP_RCONV_TO_OVF_I1-CEE_CONV_OVF_I1
913 };
914
915 /* handles from CEE_BEQ to CEE_BLT_UN */
916 static const guint16
917 beqops_op_map [STACK_MAX] = {
918         0, OP_IBEQ-CEE_BEQ, OP_LBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_FBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, 0, OP_FBEQ-CEE_BEQ
919 };
920
921 /* handles from CEE_CEQ to CEE_CLT_UN */
922 static const guint16
923 ceqops_op_map [STACK_MAX] = {
924         0, OP_ICEQ-OP_CEQ, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, 0, OP_RCEQ-OP_CEQ
925 };
926
927 /*
928  * Sets ins->type (the type on the eval stack) according to the
929  * type of the opcode and the arguments to it.
930  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
931  *
932  * FIXME: this function sets ins->type unconditionally in some cases, but
933  * it should set it to invalid for some types (a conv.x on an object)
934  */
935 static void
936 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
937 {
938         switch (ins->opcode) {
939         /* binops */
940         case CEE_ADD:
941         case CEE_SUB:
942         case CEE_MUL:
943         case CEE_DIV:
944         case CEE_REM:
945                 /* FIXME: check unverifiable args for STACK_MP */
946                 ins->type = bin_num_table [src1->type] [src2->type];
947                 ins->opcode += binops_op_map [ins->type];
948                 break;
949         case CEE_DIV_UN:
950         case CEE_REM_UN:
951         case CEE_AND:
952         case CEE_OR:
953         case CEE_XOR:
954                 ins->type = bin_int_table [src1->type] [src2->type];
955                 ins->opcode += binops_op_map [ins->type];
956                 break;
957         case CEE_SHL:
958         case CEE_SHR:
959         case CEE_SHR_UN:
960                 ins->type = shift_table [src1->type] [src2->type];
961                 ins->opcode += binops_op_map [ins->type];
962                 break;
963         case OP_COMPARE:
964         case OP_LCOMPARE:
965         case OP_ICOMPARE:
966                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
967                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
968                         ins->opcode = OP_LCOMPARE;
969                 else if (src1->type == STACK_R4)
970                         ins->opcode = OP_RCOMPARE;
971                 else if (src1->type == STACK_R8)
972                         ins->opcode = OP_FCOMPARE;
973                 else
974                         ins->opcode = OP_ICOMPARE;
975                 break;
976         case OP_ICOMPARE_IMM:
977                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
978                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
979                         ins->opcode = OP_LCOMPARE_IMM;          
980                 break;
981         case CEE_BEQ:
982         case CEE_BGE:
983         case CEE_BGT:
984         case CEE_BLE:
985         case CEE_BLT:
986         case CEE_BNE_UN:
987         case CEE_BGE_UN:
988         case CEE_BGT_UN:
989         case CEE_BLE_UN:
990         case CEE_BLT_UN:
991                 ins->opcode += beqops_op_map [src1->type];
992                 break;
993         case OP_CEQ:
994                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
995                 ins->opcode += ceqops_op_map [src1->type];
996                 break;
997         case OP_CGT:
998         case OP_CGT_UN:
999         case OP_CLT:
1000         case OP_CLT_UN:
1001                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1002                 ins->opcode += ceqops_op_map [src1->type];
1003                 break;
1004         /* unops */
1005         case CEE_NEG:
1006                 ins->type = neg_table [src1->type];
1007                 ins->opcode += unops_op_map [ins->type];
1008                 break;
1009         case CEE_NOT:
1010                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1011                         ins->type = src1->type;
1012                 else
1013                         ins->type = STACK_INV;
1014                 ins->opcode += unops_op_map [ins->type];
1015                 break;
1016         case CEE_CONV_I1:
1017         case CEE_CONV_I2:
1018         case CEE_CONV_I4:
1019         case CEE_CONV_U4:
1020                 ins->type = STACK_I4;
1021                 ins->opcode += unops_op_map [src1->type];
1022                 break;
1023         case CEE_CONV_R_UN:
1024                 ins->type = STACK_R8;
1025                 switch (src1->type) {
1026                 case STACK_I4:
1027                 case STACK_PTR:
1028                         ins->opcode = OP_ICONV_TO_R_UN;
1029                         break;
1030                 case STACK_I8:
1031                         ins->opcode = OP_LCONV_TO_R_UN; 
1032                         break;
1033                 }
1034                 break;
1035         case CEE_CONV_OVF_I1:
1036         case CEE_CONV_OVF_U1:
1037         case CEE_CONV_OVF_I2:
1038         case CEE_CONV_OVF_U2:
1039         case CEE_CONV_OVF_I4:
1040         case CEE_CONV_OVF_U4:
1041                 ins->type = STACK_I4;
1042                 ins->opcode += ovf3ops_op_map [src1->type];
1043                 break;
1044         case CEE_CONV_OVF_I_UN:
1045         case CEE_CONV_OVF_U_UN:
1046                 ins->type = STACK_PTR;
1047                 ins->opcode += ovf2ops_op_map [src1->type];
1048                 break;
1049         case CEE_CONV_OVF_I1_UN:
1050         case CEE_CONV_OVF_I2_UN:
1051         case CEE_CONV_OVF_I4_UN:
1052         case CEE_CONV_OVF_U1_UN:
1053         case CEE_CONV_OVF_U2_UN:
1054         case CEE_CONV_OVF_U4_UN:
1055                 ins->type = STACK_I4;
1056                 ins->opcode += ovf2ops_op_map [src1->type];
1057                 break;
1058         case CEE_CONV_U:
1059                 ins->type = STACK_PTR;
1060                 switch (src1->type) {
1061                 case STACK_I4:
1062                         ins->opcode = OP_ICONV_TO_U;
1063                         break;
1064                 case STACK_PTR:
1065                 case STACK_MP:
1066 #if SIZEOF_VOID_P == 8
1067                         ins->opcode = OP_LCONV_TO_U;
1068 #else
1069                         ins->opcode = OP_MOVE;
1070 #endif
1071                         break;
1072                 case STACK_I8:
1073                         ins->opcode = OP_LCONV_TO_U;
1074                         break;
1075                 case STACK_R8:
1076                         ins->opcode = OP_FCONV_TO_U;
1077                         break;
1078                 }
1079                 break;
1080         case CEE_CONV_I8:
1081         case CEE_CONV_U8:
1082                 ins->type = STACK_I8;
1083                 ins->opcode += unops_op_map [src1->type];
1084                 break;
1085         case CEE_CONV_OVF_I8:
1086         case CEE_CONV_OVF_U8:
1087                 ins->type = STACK_I8;
1088                 ins->opcode += ovf3ops_op_map [src1->type];
1089                 break;
1090         case CEE_CONV_OVF_U8_UN:
1091         case CEE_CONV_OVF_I8_UN:
1092                 ins->type = STACK_I8;
1093                 ins->opcode += ovf2ops_op_map [src1->type];
1094                 break;
1095         case CEE_CONV_R4:
1096                 ins->type = cfg->r4_stack_type;
1097                 ins->opcode += unops_op_map [src1->type];
1098                 break;
1099         case CEE_CONV_R8:
1100                 ins->type = STACK_R8;
1101                 ins->opcode += unops_op_map [src1->type];
1102                 break;
1103         case OP_CKFINITE:
1104                 ins->type = STACK_R8;           
1105                 break;
1106         case CEE_CONV_U2:
1107         case CEE_CONV_U1:
1108                 ins->type = STACK_I4;
1109                 ins->opcode += ovfops_op_map [src1->type];
1110                 break;
1111         case CEE_CONV_I:
1112         case CEE_CONV_OVF_I:
1113         case CEE_CONV_OVF_U:
1114                 ins->type = STACK_PTR;
1115                 ins->opcode += ovfops_op_map [src1->type];
1116                 break;
1117         case CEE_ADD_OVF:
1118         case CEE_ADD_OVF_UN:
1119         case CEE_MUL_OVF:
1120         case CEE_MUL_OVF_UN:
1121         case CEE_SUB_OVF:
1122         case CEE_SUB_OVF_UN:
1123                 ins->type = bin_num_table [src1->type] [src2->type];
1124                 ins->opcode += ovfops_op_map [src1->type];
1125                 if (ins->type == STACK_R8)
1126                         ins->type = STACK_INV;
1127                 break;
1128         case OP_LOAD_MEMBASE:
1129                 ins->type = STACK_PTR;
1130                 break;
1131         case OP_LOADI1_MEMBASE:
1132         case OP_LOADU1_MEMBASE:
1133         case OP_LOADI2_MEMBASE:
1134         case OP_LOADU2_MEMBASE:
1135         case OP_LOADI4_MEMBASE:
1136         case OP_LOADU4_MEMBASE:
1137                 ins->type = STACK_PTR;
1138                 break;
1139         case OP_LOADI8_MEMBASE:
1140                 ins->type = STACK_I8;
1141                 break;
1142         case OP_LOADR4_MEMBASE:
1143                 ins->type = cfg->r4_stack_type;
1144                 break;
1145         case OP_LOADR8_MEMBASE:
1146                 ins->type = STACK_R8;
1147                 break;
1148         default:
1149                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1150                 break;
1151         }
1152
1153         if (ins->type == STACK_MP)
1154                 ins->klass = mono_defaults.object_class;
1155 }
1156
1157 static const char 
1158 ldind_type [] = {
1159         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1160 };
1161
1162 #if 0
1163
1164 static const char
1165 param_table [STACK_MAX] [STACK_MAX] = {
1166         {0},
1167 };
1168
1169 static int
1170 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1171 {
1172         int i;
1173
1174         if (sig->hasthis) {
1175                 switch (args->type) {
1176                 case STACK_I4:
1177                 case STACK_I8:
1178                 case STACK_R8:
1179                 case STACK_VTYPE:
1180                 case STACK_INV:
1181                         return 0;
1182                 }
1183                 args++;
1184         }
1185         for (i = 0; i < sig->param_count; ++i) {
1186                 switch (args [i].type) {
1187                 case STACK_INV:
1188                         return 0;
1189                 case STACK_MP:
1190                         if (!sig->params [i]->byref)
1191                                 return 0;
1192                         continue;
1193                 case STACK_OBJ:
1194                         if (sig->params [i]->byref)
1195                                 return 0;
1196                         switch (sig->params [i]->type) {
1197                         case MONO_TYPE_CLASS:
1198                         case MONO_TYPE_STRING:
1199                         case MONO_TYPE_OBJECT:
1200                         case MONO_TYPE_SZARRAY:
1201                         case MONO_TYPE_ARRAY:
1202                                 break;
1203                         default:
1204                                 return 0;
1205                         }
1206                         continue;
1207                 case STACK_R8:
1208                         if (sig->params [i]->byref)
1209                                 return 0;
1210                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1211                                 return 0;
1212                         continue;
1213                 case STACK_PTR:
1214                 case STACK_I4:
1215                 case STACK_I8:
1216                 case STACK_VTYPE:
1217                         break;
1218                 }
1219                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1220                         return 0;*/
1221         }
1222         return 1;
1223 }
1224 #endif
1225
1226 /*
1227  * When we need a pointer to the current domain many times in a method, we
1228  * call mono_domain_get() once and we store the result in a local variable.
1229  * This function returns the variable that represents the MonoDomain*.
1230  */
1231 inline static MonoInst *
1232 mono_get_domainvar (MonoCompile *cfg)
1233 {
1234         if (!cfg->domainvar)
1235                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1236         return cfg->domainvar;
1237 }
1238
1239 /*
1240  * The got_var contains the address of the Global Offset Table when AOT 
1241  * compiling.
1242  */
1243 MonoInst *
1244 mono_get_got_var (MonoCompile *cfg)
1245 {
1246         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1247                 return NULL;
1248         if (!cfg->got_var) {
1249                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1250         }
1251         return cfg->got_var;
1252 }
1253
1254 static MonoInst *
1255 mono_get_vtable_var (MonoCompile *cfg)
1256 {
1257         g_assert (cfg->gshared);
1258
1259         if (!cfg->rgctx_var) {
1260                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1261                 /* force the var to be stack allocated */
1262                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1263         }
1264
1265         return cfg->rgctx_var;
1266 }
1267
1268 static MonoType*
1269 type_from_stack_type (MonoInst *ins) {
1270         switch (ins->type) {
1271         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1272         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1273         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1274         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1275         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1276         case STACK_MP:
1277                 return &ins->klass->this_arg;
1278         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1279         case STACK_VTYPE: return &ins->klass->byval_arg;
1280         default:
1281                 g_error ("stack type %d to monotype not handled\n", ins->type);
1282         }
1283         return NULL;
1284 }
1285
1286 static G_GNUC_UNUSED int
1287 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1288 {
1289         t = mono_type_get_underlying_type (t);
1290         switch (t->type) {
1291         case MONO_TYPE_I1:
1292         case MONO_TYPE_U1:
1293         case MONO_TYPE_I2:
1294         case MONO_TYPE_U2:
1295         case MONO_TYPE_I4:
1296         case MONO_TYPE_U4:
1297                 return STACK_I4;
1298         case MONO_TYPE_I:
1299         case MONO_TYPE_U:
1300         case MONO_TYPE_PTR:
1301         case MONO_TYPE_FNPTR:
1302                 return STACK_PTR;
1303         case MONO_TYPE_CLASS:
1304         case MONO_TYPE_STRING:
1305         case MONO_TYPE_OBJECT:
1306         case MONO_TYPE_SZARRAY:
1307         case MONO_TYPE_ARRAY:    
1308                 return STACK_OBJ;
1309         case MONO_TYPE_I8:
1310         case MONO_TYPE_U8:
1311                 return STACK_I8;
1312         case MONO_TYPE_R4:
1313                 return cfg->r4_stack_type;
1314         case MONO_TYPE_R8:
1315                 return STACK_R8;
1316         case MONO_TYPE_VALUETYPE:
1317         case MONO_TYPE_TYPEDBYREF:
1318                 return STACK_VTYPE;
1319         case MONO_TYPE_GENERICINST:
1320                 if (mono_type_generic_inst_is_valuetype (t))
1321                         return STACK_VTYPE;
1322                 else
1323                         return STACK_OBJ;
1324                 break;
1325         default:
1326                 g_assert_not_reached ();
1327         }
1328
1329         return -1;
1330 }
1331
1332 static MonoClass*
1333 array_access_to_klass (int opcode)
1334 {
1335         switch (opcode) {
1336         case CEE_LDELEM_U1:
1337                 return mono_defaults.byte_class;
1338         case CEE_LDELEM_U2:
1339                 return mono_defaults.uint16_class;
1340         case CEE_LDELEM_I:
1341         case CEE_STELEM_I:
1342                 return mono_defaults.int_class;
1343         case CEE_LDELEM_I1:
1344         case CEE_STELEM_I1:
1345                 return mono_defaults.sbyte_class;
1346         case CEE_LDELEM_I2:
1347         case CEE_STELEM_I2:
1348                 return mono_defaults.int16_class;
1349         case CEE_LDELEM_I4:
1350         case CEE_STELEM_I4:
1351                 return mono_defaults.int32_class;
1352         case CEE_LDELEM_U4:
1353                 return mono_defaults.uint32_class;
1354         case CEE_LDELEM_I8:
1355         case CEE_STELEM_I8:
1356                 return mono_defaults.int64_class;
1357         case CEE_LDELEM_R4:
1358         case CEE_STELEM_R4:
1359                 return mono_defaults.single_class;
1360         case CEE_LDELEM_R8:
1361         case CEE_STELEM_R8:
1362                 return mono_defaults.double_class;
1363         case CEE_LDELEM_REF:
1364         case CEE_STELEM_REF:
1365                 return mono_defaults.object_class;
1366         default:
1367                 g_assert_not_reached ();
1368         }
1369         return NULL;
1370 }
1371
1372 /*
1373  * We try to share variables when possible
1374  */
1375 static MonoInst *
1376 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1377 {
1378         MonoInst *res;
1379         int pos, vnum;
1380
1381         /* inlining can result in deeper stacks */ 
1382         if (slot >= cfg->header->max_stack)
1383                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1384
1385         pos = ins->type - 1 + slot * STACK_MAX;
1386
1387         switch (ins->type) {
1388         case STACK_I4:
1389         case STACK_I8:
1390         case STACK_R8:
1391         case STACK_PTR:
1392         case STACK_MP:
1393         case STACK_OBJ:
1394                 if ((vnum = cfg->intvars [pos]))
1395                         return cfg->varinfo [vnum];
1396                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1397                 cfg->intvars [pos] = res->inst_c0;
1398                 break;
1399         default:
1400                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1401         }
1402         return res;
1403 }
1404
1405 static void
1406 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1407 {
1408         /* 
1409          * Don't use this if a generic_context is set, since that means AOT can't
1410          * look up the method using just the image+token.
1411          * table == 0 means this is a reference made from a wrapper.
1412          */
1413         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1414                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1415                 jump_info_token->image = image;
1416                 jump_info_token->token = token;
1417                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1418         }
1419 }
1420
1421 /*
1422  * This function is called to handle items that are left on the evaluation stack
1423  * at basic block boundaries. What happens is that we save the values to local variables
1424  * and we reload them later when first entering the target basic block (with the
1425  * handle_loaded_temps () function).
1426  * A single joint point will use the same variables (stored in the array bb->out_stack or
1427  * bb->in_stack, if the basic block is before or after the joint point).
1428  *
1429  * This function needs to be called _before_ emitting the last instruction of
1430  * the bb (i.e. before emitting a branch).
1431  * If the stack merge fails at a join point, cfg->unverifiable is set.
1432  */
1433 static void
1434 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1435 {
1436         int i, bindex;
1437         MonoBasicBlock *bb = cfg->cbb;
1438         MonoBasicBlock *outb;
1439         MonoInst *inst, **locals;
1440         gboolean found;
1441
1442         if (!count)
1443                 return;
1444         if (cfg->verbose_level > 3)
1445                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1446         if (!bb->out_scount) {
1447                 bb->out_scount = count;
1448                 //printf ("bblock %d has out:", bb->block_num);
1449                 found = FALSE;
1450                 for (i = 0; i < bb->out_count; ++i) {
1451                         outb = bb->out_bb [i];
1452                         /* exception handlers are linked, but they should not be considered for stack args */
1453                         if (outb->flags & BB_EXCEPTION_HANDLER)
1454                                 continue;
1455                         //printf (" %d", outb->block_num);
1456                         if (outb->in_stack) {
1457                                 found = TRUE;
1458                                 bb->out_stack = outb->in_stack;
1459                                 break;
1460                         }
1461                 }
1462                 //printf ("\n");
1463                 if (!found) {
1464                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1465                         for (i = 0; i < count; ++i) {
1466                                 /* 
1467                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1468                                  * stack slot and if they are of the same type.
1469                                  * This won't cause conflicts since if 'local' is used to 
1470                                  * store one of the values in the in_stack of a bblock, then
1471                                  * the same variable will be used for the same outgoing stack 
1472                                  * slot as well. 
1473                                  * This doesn't work when inlining methods, since the bblocks
1474                                  * in the inlined methods do not inherit their in_stack from
1475                                  * the bblock they are inlined to. See bug #58863 for an
1476                                  * example.
1477                                  */
1478                                 if (cfg->inlined_method)
1479                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1480                                 else
1481                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1482                         }
1483                 }
1484         }
1485
1486         for (i = 0; i < bb->out_count; ++i) {
1487                 outb = bb->out_bb [i];
1488                 /* exception handlers are linked, but they should not be considered for stack args */
1489                 if (outb->flags & BB_EXCEPTION_HANDLER)
1490                         continue;
1491                 if (outb->in_scount) {
1492                         if (outb->in_scount != bb->out_scount) {
1493                                 cfg->unverifiable = TRUE;
1494                                 return;
1495                         }
1496                         continue; /* check they are the same locals */
1497                 }
1498                 outb->in_scount = count;
1499                 outb->in_stack = bb->out_stack;
1500         }
1501
1502         locals = bb->out_stack;
1503         cfg->cbb = bb;
1504         for (i = 0; i < count; ++i) {
1505                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1506                 inst->cil_code = sp [i]->cil_code;
1507                 sp [i] = locals [i];
1508                 if (cfg->verbose_level > 3)
1509                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1510         }
1511
1512         /*
1513          * It is possible that the out bblocks already have in_stack assigned, and
1514          * the in_stacks differ. In this case, we will store to all the different 
1515          * in_stacks.
1516          */
1517
1518         found = TRUE;
1519         bindex = 0;
1520         while (found) {
1521                 /* Find a bblock which has a different in_stack */
1522                 found = FALSE;
1523                 while (bindex < bb->out_count) {
1524                         outb = bb->out_bb [bindex];
1525                         /* exception handlers are linked, but they should not be considered for stack args */
1526                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1527                                 bindex++;
1528                                 continue;
1529                         }
1530                         if (outb->in_stack != locals) {
1531                                 for (i = 0; i < count; ++i) {
1532                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1533                                         inst->cil_code = sp [i]->cil_code;
1534                                         sp [i] = locals [i];
1535                                         if (cfg->verbose_level > 3)
1536                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1537                                 }
1538                                 locals = outb->in_stack;
1539                                 found = TRUE;
1540                                 break;
1541                         }
1542                         bindex ++;
1543                 }
1544         }
1545 }
1546
1547 static MonoInst*
1548 emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1549 {
1550         MonoInst *ins;
1551
1552         if (cfg->compile_aot) {
1553                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1554         } else {
1555                 MonoJumpInfo ji;
1556                 gpointer target;
1557                 MonoError error;
1558
1559                 ji.type = patch_type;
1560                 ji.data.target = data;
1561                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1562                 mono_error_assert_ok (&error);
1563
1564                 EMIT_NEW_PCONST (cfg, ins, target);
1565         }
1566         return ins;
1567 }
1568
1569 static void
1570 mini_emit_interface_bitmap_check (MonoCompile *cfg, int intf_bit_reg, int base_reg, int offset, MonoClass *klass)
1571 {
1572         int ibitmap_reg = alloc_preg (cfg);
1573 #ifdef COMPRESSED_INTERFACE_BITMAP
1574         MonoInst *args [2];
1575         MonoInst *res, *ins;
1576         NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, ibitmap_reg, base_reg, offset);
1577         MONO_ADD_INS (cfg->cbb, ins);
1578         args [0] = ins;
1579         args [1] = emit_runtime_constant (cfg, MONO_PATCH_INFO_IID, klass);
1580         res = mono_emit_jit_icall (cfg, mono_class_interface_match, args);
1581         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, intf_bit_reg, res->dreg);
1582 #else
1583         int ibitmap_byte_reg = alloc_preg (cfg);
1584
1585         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, ibitmap_reg, base_reg, offset);
1586
1587         if (cfg->compile_aot) {
1588                 int iid_reg = alloc_preg (cfg);
1589                 int shifted_iid_reg = alloc_preg (cfg);
1590                 int ibitmap_byte_address_reg = alloc_preg (cfg);
1591                 int masked_iid_reg = alloc_preg (cfg);
1592                 int iid_one_bit_reg = alloc_preg (cfg);
1593                 int iid_bit_reg = alloc_preg (cfg);
1594                 MONO_EMIT_NEW_AOTCONST (cfg, iid_reg, klass, MONO_PATCH_INFO_IID);
1595                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, shifted_iid_reg, iid_reg, 3);
1596                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, ibitmap_byte_address_reg, ibitmap_reg, shifted_iid_reg);
1597                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, ibitmap_byte_reg, ibitmap_byte_address_reg, 0);
1598                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, masked_iid_reg, iid_reg, 7);
1599                 MONO_EMIT_NEW_ICONST (cfg, iid_one_bit_reg, 1);
1600                 MONO_EMIT_NEW_BIALU (cfg, OP_ISHL, iid_bit_reg, iid_one_bit_reg, masked_iid_reg);
1601                 MONO_EMIT_NEW_BIALU (cfg, OP_IAND, intf_bit_reg, ibitmap_byte_reg, iid_bit_reg);
1602         } else {
1603                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, ibitmap_byte_reg, ibitmap_reg, klass->interface_id >> 3);
1604                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_AND_IMM, intf_bit_reg, ibitmap_byte_reg, 1 << (klass->interface_id & 7));
1605         }
1606 #endif
1607 }
1608
1609 /* 
1610  * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoClass
1611  * stored in "klass_reg" implements the interface "klass".
1612  */
1613 static void
1614 mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass_reg, MonoClass *klass)
1615 {
1616         mini_emit_interface_bitmap_check (cfg, intf_bit_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, interface_bitmap), klass);
1617 }
1618
1619 /* 
1620  * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoVTable
1621  * stored in "vtable_reg" implements the interface "klass".
1622  */
1623 static void
1624 mini_emit_load_intf_bit_reg_vtable (MonoCompile *cfg, int intf_bit_reg, int vtable_reg, MonoClass *klass)
1625 {
1626         mini_emit_interface_bitmap_check (cfg, intf_bit_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap), klass);
1627 }
1628
1629 /* 
1630  * Emit code which checks whenever the interface id of @klass is smaller than
1631  * than the value given by max_iid_reg.
1632 */
1633 static void
1634 mini_emit_max_iid_check (MonoCompile *cfg, int max_iid_reg, MonoClass *klass,
1635                                                  MonoBasicBlock *false_target)
1636 {
1637         if (cfg->compile_aot) {
1638                 int iid_reg = alloc_preg (cfg);
1639                 MONO_EMIT_NEW_AOTCONST (cfg, iid_reg, klass, MONO_PATCH_INFO_IID);
1640                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, max_iid_reg, iid_reg);
1641         }
1642         else
1643                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, max_iid_reg, klass->interface_id);
1644         if (false_target)
1645                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBLT_UN, false_target);
1646         else
1647                 MONO_EMIT_NEW_COND_EXC (cfg, LT_UN, "InvalidCastException");
1648 }
1649
1650 /* Same as above, but obtains max_iid from a vtable */
1651 static void
1652 mini_emit_max_iid_check_vtable (MonoCompile *cfg, int vtable_reg, MonoClass *klass,
1653                                                                  MonoBasicBlock *false_target)
1654 {
1655         int max_iid_reg = alloc_preg (cfg);
1656                 
1657         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, max_iid_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
1658         mini_emit_max_iid_check (cfg, max_iid_reg, klass, false_target);
1659 }
1660
1661 /* Same as above, but obtains max_iid from a klass */
1662 static void
1663 mini_emit_max_iid_check_class (MonoCompile *cfg, int klass_reg, MonoClass *klass,
1664                                                                  MonoBasicBlock *false_target)
1665 {
1666         int max_iid_reg = alloc_preg (cfg);
1667
1668         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, max_iid_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, max_interface_id));
1669         mini_emit_max_iid_check (cfg, max_iid_reg, klass, false_target);
1670 }
1671
1672 static void
1673 mini_emit_isninst_cast_inst (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoInst *klass_ins, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1674 {
1675         int idepth_reg = alloc_preg (cfg);
1676         int stypes_reg = alloc_preg (cfg);
1677         int stype = alloc_preg (cfg);
1678
1679         mono_class_setup_supertypes (klass);
1680
1681         if (klass->idepth > MONO_DEFAULT_SUPERTABLE_SIZE) {
1682                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, idepth_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, idepth));
1683                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, idepth_reg, klass->idepth);
1684                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBLT_UN, false_target);
1685         }
1686         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stypes_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, supertypes));
1687         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stype, stypes_reg, ((klass->idepth - 1) * SIZEOF_VOID_P));
1688         if (klass_ins) {
1689                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, stype, klass_ins->dreg);
1690         } else if (cfg->compile_aot) {
1691                 int const_reg = alloc_preg (cfg);
1692                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
1693                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, stype, const_reg);
1694         } else {
1695                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, stype, klass);
1696         }
1697         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, true_target);
1698 }
1699
1700 static void
1701 mini_emit_isninst_cast (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1702 {
1703         mini_emit_isninst_cast_inst (cfg, klass_reg, klass, NULL, false_target, true_target);
1704 }
1705
1706 static void
1707 mini_emit_iface_cast (MonoCompile *cfg, int vtable_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1708 {
1709         int intf_reg = alloc_preg (cfg);
1710
1711         mini_emit_max_iid_check_vtable (cfg, vtable_reg, klass, false_target);
1712         mini_emit_load_intf_bit_reg_vtable (cfg, intf_reg, vtable_reg, klass);
1713         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, intf_reg, 0);
1714         if (true_target)
1715                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, true_target);
1716         else
1717                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");               
1718 }
1719
1720 /*
1721  * Variant of the above that takes a register to the class, not the vtable.
1722  */
1723 static void
1724 mini_emit_iface_class_cast (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoBasicBlock *false_target, MonoBasicBlock *true_target)
1725 {
1726         int intf_bit_reg = alloc_preg (cfg);
1727
1728         mini_emit_max_iid_check_class (cfg, klass_reg, klass, false_target);
1729         mini_emit_load_intf_bit_reg_class (cfg, intf_bit_reg, klass_reg, klass);
1730         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, intf_bit_reg, 0);
1731         if (true_target)
1732                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, true_target);
1733         else
1734                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");
1735 }
1736
1737 static inline void
1738 mini_emit_class_check_inst (MonoCompile *cfg, int klass_reg, MonoClass *klass, MonoInst *klass_inst)
1739 {
1740         if (klass_inst) {
1741                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_inst->dreg);
1742         } else {
1743                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
1744                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, ins->dreg);
1745         }
1746         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1747 }
1748
1749 static inline void
1750 mini_emit_class_check (MonoCompile *cfg, int klass_reg, MonoClass *klass)
1751 {
1752         mini_emit_class_check_inst (cfg, klass_reg, klass, NULL);
1753 }
1754
1755 static inline void
1756 mini_emit_class_check_branch (MonoCompile *cfg, int klass_reg, MonoClass *klass, int branch_op, MonoBasicBlock *target)
1757 {
1758         if (cfg->compile_aot) {
1759                 int const_reg = alloc_preg (cfg);
1760                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
1761                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, const_reg);
1762         } else {
1763                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
1764         }
1765         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, branch_op, target);
1766 }
1767
1768 static void
1769 mini_emit_castclass (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoBasicBlock *object_is_null);
1770         
1771 static void
1772 mini_emit_castclass_inst (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoInst *klass_inst, MonoBasicBlock *object_is_null)
1773 {
1774         if (klass->rank) {
1775                 int rank_reg = alloc_preg (cfg);
1776                 int eclass_reg = alloc_preg (cfg);
1777
1778                 g_assert (!klass_inst);
1779                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, rank));
1780                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, klass->rank);
1781                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1782                 //              MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
1783                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, cast_class));
1784                 if (klass->cast_class == mono_defaults.object_class) {
1785                         int parent_reg = alloc_preg (cfg);
1786                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, parent_reg, eclass_reg, MONO_STRUCT_OFFSET (MonoClass, parent));
1787                         mini_emit_class_check_branch (cfg, parent_reg, mono_defaults.enum_class->parent, OP_PBNE_UN, object_is_null);
1788                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1789                 } else if (klass->cast_class == mono_defaults.enum_class->parent) {
1790                         mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class->parent, OP_PBEQ, object_is_null);
1791                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1792                 } else if (klass->cast_class == mono_defaults.enum_class) {
1793                         mini_emit_class_check (cfg, eclass_reg, mono_defaults.enum_class);
1794                 } else if (klass->cast_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
1795                         mini_emit_iface_class_cast (cfg, eclass_reg, klass->cast_class, NULL, NULL);
1796                 } else {
1797                         // Pass -1 as obj_reg to skip the check below for arrays of arrays
1798                         mini_emit_castclass (cfg, -1, eclass_reg, klass->cast_class, object_is_null);
1799                 }
1800
1801                 if ((klass->rank == 1) && (klass->byval_arg.type == MONO_TYPE_SZARRAY) && (obj_reg != -1)) {
1802                         /* Check that the object is a vector too */
1803                         int bounds_reg = alloc_preg (cfg);
1804                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, obj_reg, MONO_STRUCT_OFFSET (MonoArray, bounds));
1805                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
1806                         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
1807                 }
1808         } else {
1809                 int idepth_reg = alloc_preg (cfg);
1810                 int stypes_reg = alloc_preg (cfg);
1811                 int stype = alloc_preg (cfg);
1812
1813                 mono_class_setup_supertypes (klass);
1814
1815                 if (klass->idepth > MONO_DEFAULT_SUPERTABLE_SIZE) {
1816                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, idepth_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, idepth));
1817                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, idepth_reg, klass->idepth);
1818                         MONO_EMIT_NEW_COND_EXC (cfg, LT_UN, "InvalidCastException");
1819                 }
1820                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stypes_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, supertypes));
1821                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, stype, stypes_reg, ((klass->idepth - 1) * SIZEOF_VOID_P));
1822                 mini_emit_class_check_inst (cfg, stype, klass, klass_inst);
1823         }
1824 }
1825
1826 static void
1827 mini_emit_castclass (MonoCompile *cfg, int obj_reg, int klass_reg, MonoClass *klass, MonoBasicBlock *object_is_null)
1828 {
1829         mini_emit_castclass_inst (cfg, obj_reg, klass_reg, klass, NULL, object_is_null);
1830 }
1831
1832 static void 
1833 mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, int align)
1834 {
1835         int val_reg;
1836
1837         g_assert (val == 0);
1838
1839         if (align == 0)
1840                 align = 4;
1841
1842         if ((size <= SIZEOF_REGISTER) && (size <= align)) {
1843                 switch (size) {
1844                 case 1:
1845                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, destreg, offset, val);
1846                         return;
1847                 case 2:
1848                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI2_MEMBASE_IMM, destreg, offset, val);
1849                         return;
1850                 case 4:
1851                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, destreg, offset, val);
1852                         return;
1853 #if SIZEOF_REGISTER == 8
1854                 case 8:
1855                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI8_MEMBASE_IMM, destreg, offset, val);
1856                         return;
1857 #endif
1858                 }
1859         }
1860
1861         val_reg = alloc_preg (cfg);
1862
1863         if (SIZEOF_REGISTER == 8)
1864                 MONO_EMIT_NEW_I8CONST (cfg, val_reg, val);
1865         else
1866                 MONO_EMIT_NEW_ICONST (cfg, val_reg, val);
1867
1868         if (align < 4) {
1869                 /* This could be optimized further if neccesary */
1870                 while (size >= 1) {
1871                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1872                         offset += 1;
1873                         size -= 1;
1874                 }
1875                 return;
1876         }       
1877
1878         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1879                 if (offset % 8) {
1880                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1881                         offset += 4;
1882                         size -= 4;
1883                 }
1884                 while (size >= 8) {
1885                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, offset, val_reg);
1886                         offset += 8;
1887                         size -= 8;
1888                 }
1889         }       
1890
1891         while (size >= 4) {
1892                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1893                 offset += 4;
1894                 size -= 4;
1895         }
1896         while (size >= 2) {
1897                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, val_reg);
1898                 offset += 2;
1899                 size -= 2;
1900         }
1901         while (size >= 1) {
1902                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1903                 offset += 1;
1904                 size -= 1;
1905         }
1906 }
1907
1908 void 
1909 mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
1910 {
1911         int cur_reg;
1912
1913         if (align == 0)
1914                 align = 4;
1915
1916         /*FIXME arbitrary hack to avoid unbound code expansion.*/
1917         g_assert (size < 10000);
1918
1919         if (align < 4) {
1920                 /* This could be optimized further if neccesary */
1921                 while (size >= 1) {
1922                         cur_reg = alloc_preg (cfg);
1923                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1924                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1925                         doffset += 1;
1926                         soffset += 1;
1927                         size -= 1;
1928                 }
1929         }
1930
1931         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1932                 while (size >= 8) {
1933                         cur_reg = alloc_preg (cfg);
1934                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI8_MEMBASE, cur_reg, srcreg, soffset);
1935                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, doffset, cur_reg);
1936                         doffset += 8;
1937                         soffset += 8;
1938                         size -= 8;
1939                 }
1940         }       
1941
1942         while (size >= 4) {
1943                 cur_reg = alloc_preg (cfg);
1944                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, cur_reg, srcreg, soffset);
1945                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, doffset, cur_reg);
1946                 doffset += 4;
1947                 soffset += 4;
1948                 size -= 4;
1949         }
1950         while (size >= 2) {
1951                 cur_reg = alloc_preg (cfg);
1952                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, cur_reg, srcreg, soffset);
1953                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, doffset, cur_reg);
1954                 doffset += 2;
1955                 soffset += 2;
1956                 size -= 2;
1957         }
1958         while (size >= 1) {
1959                 cur_reg = alloc_preg (cfg);
1960                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1961                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1962                 doffset += 1;
1963                 soffset += 1;
1964                 size -= 1;
1965         }
1966 }
1967
1968 static void
1969 emit_tls_set (MonoCompile *cfg, int sreg1, MonoTlsKey tls_key)
1970 {
1971         MonoInst *ins, *c;
1972
1973         if (cfg->compile_aot) {
1974                 EMIT_NEW_TLS_OFFSETCONST (cfg, c, tls_key);
1975                 MONO_INST_NEW (cfg, ins, OP_TLS_SET_REG);
1976                 ins->sreg1 = sreg1;
1977                 ins->sreg2 = c->dreg;
1978                 MONO_ADD_INS (cfg->cbb, ins);
1979         } else {
1980                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1981                 ins->sreg1 = sreg1;
1982                 ins->inst_offset = mini_get_tls_offset (tls_key);
1983                 MONO_ADD_INS (cfg->cbb, ins);
1984         }
1985 }
1986
1987 /*
1988  * emit_push_lmf:
1989  *
1990  *   Emit IR to push the current LMF onto the LMF stack.
1991  */
1992 static void
1993 emit_push_lmf (MonoCompile *cfg)
1994 {
1995         /*
1996          * Emit IR to push the LMF:
1997          * lmf_addr = <lmf_addr from tls>
1998          * lmf->lmf_addr = lmf_addr
1999          * lmf->prev_lmf = *lmf_addr
2000          * *lmf_addr = lmf
2001          */
2002         int lmf_reg, prev_lmf_reg;
2003         MonoInst *ins, *lmf_ins;
2004
2005         if (!cfg->lmf_ir)
2006                 return;
2007
2008         if (cfg->lmf_ir_mono_lmf && mini_tls_get_supported (cfg, TLS_KEY_LMF)) {
2009                 /* Load current lmf */
2010                 lmf_ins = mono_get_lmf_intrinsic (cfg);
2011                 g_assert (lmf_ins);
2012                 MONO_ADD_INS (cfg->cbb, lmf_ins);
2013                 EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2014                 lmf_reg = ins->dreg;
2015                 /* Save previous_lmf */
2016                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), lmf_ins->dreg);
2017                 /* Set new LMF */
2018                 emit_tls_set (cfg, lmf_reg, TLS_KEY_LMF);
2019         } else {
2020                 /*
2021                  * Store lmf_addr in a variable, so it can be allocated to a global register.
2022                  */
2023                 if (!cfg->lmf_addr_var)
2024                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2025
2026 #ifdef HOST_WIN32
2027                 ins = mono_get_jit_tls_intrinsic (cfg);
2028                 if (ins) {
2029                         int jit_tls_dreg = ins->dreg;
2030
2031                         MONO_ADD_INS (cfg->cbb, ins);
2032                         lmf_reg = alloc_preg (cfg);
2033                         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
2034                 } else {
2035                         lmf_ins = mono_emit_jit_icall (cfg, mono_get_lmf_addr, NULL);
2036                 }
2037 #else
2038                 lmf_ins = mono_get_lmf_addr_intrinsic (cfg);
2039                 if (lmf_ins) {
2040                         MONO_ADD_INS (cfg->cbb, lmf_ins);
2041                 } else {
2042 #ifdef TARGET_IOS
2043                         MonoInst *args [16], *jit_tls_ins, *ins;
2044
2045                         /* Inline mono_get_lmf_addr () */
2046                         /* jit_tls = pthread_getspecific (mono_jit_tls_id); lmf_addr = &jit_tls->lmf; */
2047
2048                         /* Load mono_jit_tls_id */
2049                         if (cfg->compile_aot)
2050                                 EMIT_NEW_AOTCONST (cfg, args [0], MONO_PATCH_INFO_JIT_TLS_ID, NULL);
2051                         else
2052                                 EMIT_NEW_ICONST (cfg, args [0], mono_jit_tls_id);
2053                         /* call pthread_getspecific () */
2054                         jit_tls_ins = mono_emit_jit_icall (cfg, pthread_getspecific, args);
2055                         /* lmf_addr = &jit_tls->lmf */
2056                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, cfg->lmf_addr_var->dreg, jit_tls_ins->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
2057                         lmf_ins = ins;
2058 #else
2059                         lmf_ins = mono_emit_jit_icall (cfg, mono_get_lmf_addr, NULL);
2060 #endif
2061                 }
2062 #endif
2063                 lmf_ins->dreg = cfg->lmf_addr_var->dreg;
2064
2065                 EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2066                 lmf_reg = ins->dreg;
2067
2068                 prev_lmf_reg = alloc_preg (cfg);
2069                 /* Save previous_lmf */
2070                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
2071                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
2072                 /* Set new lmf */
2073                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
2074         }
2075 }
2076
2077 /*
2078  * emit_pop_lmf:
2079  *
2080  *   Emit IR to pop the current LMF from the LMF stack.
2081  */
2082 static void
2083 emit_pop_lmf (MonoCompile *cfg)
2084 {
2085         int lmf_reg, lmf_addr_reg, prev_lmf_reg;
2086         MonoInst *ins;
2087
2088         if (!cfg->lmf_ir)
2089                 return;
2090
2091         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
2092         lmf_reg = ins->dreg;
2093
2094         if (cfg->lmf_ir_mono_lmf && mini_tls_get_supported (cfg, TLS_KEY_LMF)) {
2095                 /* Load previous_lmf */
2096                 prev_lmf_reg = alloc_preg (cfg);
2097                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
2098                 /* Set new LMF */
2099                 emit_tls_set (cfg, prev_lmf_reg, TLS_KEY_LMF);
2100         } else {
2101                 /*
2102                  * Emit IR to pop the LMF:
2103                  * *(lmf->lmf_addr) = lmf->prev_lmf
2104                  */
2105                 /* This could be called before emit_push_lmf () */
2106                 if (!cfg->lmf_addr_var)
2107                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2108                 lmf_addr_reg = cfg->lmf_addr_var->dreg;
2109
2110                 prev_lmf_reg = alloc_preg (cfg);
2111                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
2112                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
2113         }
2114 }
2115
2116 static void
2117 emit_instrumentation_call (MonoCompile *cfg, void *func)
2118 {
2119         MonoInst *iargs [1];
2120
2121         /*
2122          * Avoid instrumenting inlined methods since it can
2123          * distort profiling results.
2124          */
2125         if (cfg->method != cfg->current_method)
2126                 return;
2127
2128         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
2129                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
2130                 mono_emit_jit_icall (cfg, func, iargs);
2131         }
2132 }
2133
2134 static int
2135 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
2136 {
2137 handle_enum:
2138         type = mini_get_underlying_type (type);
2139         switch (type->type) {
2140         case MONO_TYPE_VOID:
2141                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
2142         case MONO_TYPE_I1:
2143         case MONO_TYPE_U1:
2144         case MONO_TYPE_I2:
2145         case MONO_TYPE_U2:
2146         case MONO_TYPE_I4:
2147         case MONO_TYPE_U4:
2148                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2149         case MONO_TYPE_I:
2150         case MONO_TYPE_U:
2151         case MONO_TYPE_PTR:
2152         case MONO_TYPE_FNPTR:
2153                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2154         case MONO_TYPE_CLASS:
2155         case MONO_TYPE_STRING:
2156         case MONO_TYPE_OBJECT:
2157         case MONO_TYPE_SZARRAY:
2158         case MONO_TYPE_ARRAY:    
2159                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
2160         case MONO_TYPE_I8:
2161         case MONO_TYPE_U8:
2162                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
2163         case MONO_TYPE_R4:
2164                 if (cfg->r4fp)
2165                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
2166                 else
2167                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
2168         case MONO_TYPE_R8:
2169                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
2170         case MONO_TYPE_VALUETYPE:
2171                 if (type->data.klass->enumtype) {
2172                         type = mono_class_enum_basetype (type->data.klass);
2173                         goto handle_enum;
2174                 } else
2175                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2176         case MONO_TYPE_TYPEDBYREF:
2177                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2178         case MONO_TYPE_GENERICINST:
2179                 type = &type->data.generic_class->container_class->byval_arg;
2180                 goto handle_enum;
2181         case MONO_TYPE_VAR:
2182         case MONO_TYPE_MVAR:
2183                 /* gsharedvt */
2184                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
2185         default:
2186                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2187         }
2188         return -1;
2189 }
2190
2191 //XXX this ignores if t is byref
2192 #define MONO_TYPE_IS_PRIMITIVE_SCALAR(t) ((((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_U8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
2193
2194 /*
2195  * target_type_is_incompatible:
2196  * @cfg: MonoCompile context
2197  *
2198  * Check that the item @arg on the evaluation stack can be stored
2199  * in the target type (can be a local, or field, etc).
2200  * The cfg arg can be used to check if we need verification or just
2201  * validity checks.
2202  *
2203  * Returns: non-0 value if arg can't be stored on a target.
2204  */
2205 static int
2206 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2207 {
2208         MonoType *simple_type;
2209         MonoClass *klass;
2210
2211         if (target->byref) {
2212                 /* FIXME: check that the pointed to types match */
2213                 if (arg->type == STACK_MP) {
2214                         if (cfg->verbose_level) printf ("ok\n");
2215                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
2216                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
2217                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
2218
2219                         /* if the target is native int& or same type */
2220                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
2221                                 return 0;
2222
2223                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
2224                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
2225                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
2226                                 return 0;
2227                         return 1;
2228                 }
2229                 if (arg->type == STACK_PTR)
2230                         return 0;
2231                 return 1;
2232         }
2233
2234         simple_type = mini_get_underlying_type (target);
2235         switch (simple_type->type) {
2236         case MONO_TYPE_VOID:
2237                 return 1;
2238         case MONO_TYPE_I1:
2239         case MONO_TYPE_U1:
2240         case MONO_TYPE_I2:
2241         case MONO_TYPE_U2:
2242         case MONO_TYPE_I4:
2243         case MONO_TYPE_U4:
2244                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2245                         return 1;
2246                 return 0;
2247         case MONO_TYPE_PTR:
2248                 /* STACK_MP is needed when setting pinned locals */
2249                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2250                         return 1;
2251                 return 0;
2252         case MONO_TYPE_I:
2253         case MONO_TYPE_U:
2254         case MONO_TYPE_FNPTR:
2255                 /* 
2256                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
2257                  * in native int. (#688008).
2258                  */
2259                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2260                         return 1;
2261                 return 0;
2262         case MONO_TYPE_CLASS:
2263         case MONO_TYPE_STRING:
2264         case MONO_TYPE_OBJECT:
2265         case MONO_TYPE_SZARRAY:
2266         case MONO_TYPE_ARRAY:    
2267                 if (arg->type != STACK_OBJ)
2268                         return 1;
2269                 /* FIXME: check type compatibility */
2270                 return 0;
2271         case MONO_TYPE_I8:
2272         case MONO_TYPE_U8:
2273                 if (arg->type != STACK_I8)
2274                         return 1;
2275                 return 0;
2276         case MONO_TYPE_R4:
2277                 if (arg->type != cfg->r4_stack_type)
2278                         return 1;
2279                 return 0;
2280         case MONO_TYPE_R8:
2281                 if (arg->type != STACK_R8)
2282                         return 1;
2283                 return 0;
2284         case MONO_TYPE_VALUETYPE:
2285                 if (arg->type != STACK_VTYPE)
2286                         return 1;
2287                 klass = mono_class_from_mono_type (simple_type);
2288                 if (klass != arg->klass)
2289                         return 1;
2290                 return 0;
2291         case MONO_TYPE_TYPEDBYREF:
2292                 if (arg->type != STACK_VTYPE)
2293                         return 1;
2294                 klass = mono_class_from_mono_type (simple_type);
2295                 if (klass != arg->klass)
2296                         return 1;
2297                 return 0;
2298         case MONO_TYPE_GENERICINST:
2299                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2300                         MonoClass *target_class;
2301                         if (arg->type != STACK_VTYPE)
2302                                 return 1;
2303                         klass = mono_class_from_mono_type (simple_type);
2304                         target_class = mono_class_from_mono_type (target);
2305                         /* The second cases is needed when doing partial sharing */
2306                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
2307                                 return 1;
2308                         return 0;
2309                 } else {
2310                         if (arg->type != STACK_OBJ)
2311                                 return 1;
2312                         /* FIXME: check type compatibility */
2313                         return 0;
2314                 }
2315         case MONO_TYPE_VAR:
2316         case MONO_TYPE_MVAR:
2317                 g_assert (cfg->gshared);
2318                 if (mini_type_var_is_vt (simple_type)) {
2319                         if (arg->type != STACK_VTYPE)
2320                                 return 1;
2321                 } else {
2322                         if (arg->type != STACK_OBJ)
2323                                 return 1;
2324                 }
2325                 return 0;
2326         default:
2327                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2328         }
2329         return 1;
2330 }
2331
2332 /*
2333  * Prepare arguments for passing to a function call.
2334  * Return a non-zero value if the arguments can't be passed to the given
2335  * signature.
2336  * The type checks are not yet complete and some conversions may need
2337  * casts on 32 or 64 bit architectures.
2338  *
2339  * FIXME: implement this using target_type_is_incompatible ()
2340  */
2341 static int
2342 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2343 {
2344         MonoType *simple_type;
2345         int i;
2346
2347         if (sig->hasthis) {
2348                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2349                         return 1;
2350                 args++;
2351         }
2352         for (i = 0; i < sig->param_count; ++i) {
2353                 if (sig->params [i]->byref) {
2354                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2355                                 return 1;
2356                         continue;
2357                 }
2358                 simple_type = mini_get_underlying_type (sig->params [i]);
2359 handle_enum:
2360                 switch (simple_type->type) {
2361                 case MONO_TYPE_VOID:
2362                         return 1;
2363                         continue;
2364                 case MONO_TYPE_I1:
2365                 case MONO_TYPE_U1:
2366                 case MONO_TYPE_I2:
2367                 case MONO_TYPE_U2:
2368                 case MONO_TYPE_I4:
2369                 case MONO_TYPE_U4:
2370                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2371                                 return 1;
2372                         continue;
2373                 case MONO_TYPE_I:
2374                 case MONO_TYPE_U:
2375                 case MONO_TYPE_PTR:
2376                 case MONO_TYPE_FNPTR:
2377                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2378                                 return 1;
2379                         continue;
2380                 case MONO_TYPE_CLASS:
2381                 case MONO_TYPE_STRING:
2382                 case MONO_TYPE_OBJECT:
2383                 case MONO_TYPE_SZARRAY:
2384                 case MONO_TYPE_ARRAY:    
2385                         if (args [i]->type != STACK_OBJ)
2386                                 return 1;
2387                         continue;
2388                 case MONO_TYPE_I8:
2389                 case MONO_TYPE_U8:
2390                         if (args [i]->type != STACK_I8)
2391                                 return 1;
2392                         continue;
2393                 case MONO_TYPE_R4:
2394                         if (args [i]->type != cfg->r4_stack_type)
2395                                 return 1;
2396                         continue;
2397                 case MONO_TYPE_R8:
2398                         if (args [i]->type != STACK_R8)
2399                                 return 1;
2400                         continue;
2401                 case MONO_TYPE_VALUETYPE:
2402                         if (simple_type->data.klass->enumtype) {
2403                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2404                                 goto handle_enum;
2405                         }
2406                         if (args [i]->type != STACK_VTYPE)
2407                                 return 1;
2408                         continue;
2409                 case MONO_TYPE_TYPEDBYREF:
2410                         if (args [i]->type != STACK_VTYPE)
2411                                 return 1;
2412                         continue;
2413                 case MONO_TYPE_GENERICINST:
2414                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2415                         goto handle_enum;
2416                 case MONO_TYPE_VAR:
2417                 case MONO_TYPE_MVAR:
2418                         /* gsharedvt */
2419                         if (args [i]->type != STACK_VTYPE)
2420                                 return 1;
2421                         continue;
2422                 default:
2423                         g_error ("unknown type 0x%02x in check_call_signature",
2424                                  simple_type->type);
2425                 }
2426         }
2427         return 0;
2428 }
2429
2430 static int
2431 callvirt_to_call (int opcode)
2432 {
2433         switch (opcode) {
2434         case OP_CALL_MEMBASE:
2435                 return OP_CALL;
2436         case OP_VOIDCALL_MEMBASE:
2437                 return OP_VOIDCALL;
2438         case OP_FCALL_MEMBASE:
2439                 return OP_FCALL;
2440         case OP_RCALL_MEMBASE:
2441                 return OP_RCALL;
2442         case OP_VCALL_MEMBASE:
2443                 return OP_VCALL;
2444         case OP_LCALL_MEMBASE:
2445                 return OP_LCALL;
2446         default:
2447                 g_assert_not_reached ();
2448         }
2449
2450         return -1;
2451 }
2452
2453 static int
2454 callvirt_to_call_reg (int opcode)
2455 {
2456         switch (opcode) {
2457         case OP_CALL_MEMBASE:
2458                 return OP_CALL_REG;
2459         case OP_VOIDCALL_MEMBASE:
2460                 return OP_VOIDCALL_REG;
2461         case OP_FCALL_MEMBASE:
2462                 return OP_FCALL_REG;
2463         case OP_RCALL_MEMBASE:
2464                 return OP_RCALL_REG;
2465         case OP_VCALL_MEMBASE:
2466                 return OP_VCALL_REG;
2467         case OP_LCALL_MEMBASE:
2468                 return OP_LCALL_REG;
2469         default:
2470                 g_assert_not_reached ();
2471         }
2472
2473         return -1;
2474 }
2475
2476 /* Either METHOD or IMT_ARG needs to be set */
2477 static void
2478 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2479 {
2480         int method_reg;
2481
2482         if (COMPILE_LLVM (cfg)) {
2483                 if (imt_arg) {
2484                         method_reg = alloc_preg (cfg);
2485                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2486                 } else {
2487                         MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2488                         method_reg = ins->dreg;
2489                 }
2490
2491 #ifdef ENABLE_LLVM
2492                 call->imt_arg_reg = method_reg;
2493 #endif
2494                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2495                 return;
2496         }
2497
2498         if (imt_arg) {
2499                 method_reg = alloc_preg (cfg);
2500                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2501         } else {
2502                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2503                 method_reg = ins->dreg;
2504         }
2505
2506         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2507 }
2508
2509 static MonoJumpInfo *
2510 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2511 {
2512         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2513
2514         ji->ip.i = ip;
2515         ji->type = type;
2516         ji->data.target = target;
2517
2518         return ji;
2519 }
2520
2521 static int
2522 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2523 {
2524         if (cfg->gshared)
2525                 return mono_class_check_context_used (klass);
2526         else
2527                 return 0;
2528 }
2529
2530 static int
2531 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2532 {
2533         if (cfg->gshared)
2534                 return mono_method_check_context_used (method);
2535         else
2536                 return 0;
2537 }
2538
2539 /*
2540  * check_method_sharing:
2541  *
2542  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2543  */
2544 static void
2545 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2546 {
2547         gboolean pass_vtable = FALSE;
2548         gboolean pass_mrgctx = FALSE;
2549
2550         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2551                 (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
2552                 gboolean sharable = FALSE;
2553
2554                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2555                         sharable = TRUE;
2556
2557                 /*
2558                  * Pass vtable iff target method might
2559                  * be shared, which means that sharing
2560                  * is enabled for its class and its
2561                  * context is sharable (and it's not a
2562                  * generic method).
2563                  */
2564                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2565                         pass_vtable = TRUE;
2566         }
2567
2568         if (mini_method_get_context (cmethod) &&
2569                 mini_method_get_context (cmethod)->method_inst) {
2570                 g_assert (!pass_vtable);
2571
2572                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2573                         pass_mrgctx = TRUE;
2574                 } else {
2575                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2576                                 pass_mrgctx = TRUE;
2577                 }
2578         }
2579
2580         if (out_pass_vtable)
2581                 *out_pass_vtable = pass_vtable;
2582         if (out_pass_mrgctx)
2583                 *out_pass_mrgctx = pass_mrgctx;
2584 }
2585
2586 inline static MonoCallInst *
2587 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2588                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2589 {
2590         MonoType *sig_ret;
2591         MonoCallInst *call;
2592 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2593         int i;
2594 #endif
2595
2596         if (cfg->llvm_only)
2597                 tail = FALSE;
2598
2599         if (tail) {
2600                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2601
2602                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2603         } else
2604                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2605
2606         call->args = args;
2607         call->signature = sig;
2608         call->rgctx_reg = rgctx;
2609         sig_ret = mini_get_underlying_type (sig->ret);
2610
2611         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2612
2613         if (tail) {
2614                 if (mini_type_is_vtype (sig_ret)) {
2615                         call->vret_var = cfg->vret_addr;
2616                         //g_assert_not_reached ();
2617                 }
2618         } else if (mini_type_is_vtype (sig_ret)) {
2619                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2620                 MonoInst *loada;
2621
2622                 temp->backend.is_pinvoke = sig->pinvoke;
2623
2624                 /*
2625                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2626                  * address of return value to increase optimization opportunities.
2627                  * Before vtype decomposition, the dreg of the call ins itself represents the
2628                  * fact the call modifies the return value. After decomposition, the call will
2629                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2630                  * will be transformed into an LDADDR.
2631                  */
2632                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2633                 loada->dreg = alloc_preg (cfg);
2634                 loada->inst_p0 = temp;
2635                 /* We reference the call too since call->dreg could change during optimization */
2636                 loada->inst_p1 = call;
2637                 MONO_ADD_INS (cfg->cbb, loada);
2638
2639                 call->inst.dreg = temp->dreg;
2640
2641                 call->vret_var = loada;
2642         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2643                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2644
2645 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2646         if (COMPILE_SOFT_FLOAT (cfg)) {
2647                 /* 
2648                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2649                  * an icall, but that cannot be done during the call sequence since it would clobber
2650                  * the call registers + the stack. So we do it before emitting the call.
2651                  */
2652                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2653                         MonoType *t;
2654                         MonoInst *in = call->args [i];
2655
2656                         if (i >= sig->hasthis)
2657                                 t = sig->params [i - sig->hasthis];
2658                         else
2659                                 t = &mono_defaults.int_class->byval_arg;
2660                         t = mono_type_get_underlying_type (t);
2661
2662                         if (!t->byref && t->type == MONO_TYPE_R4) {
2663                                 MonoInst *iargs [1];
2664                                 MonoInst *conv;
2665
2666                                 iargs [0] = in;
2667                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2668
2669                                 /* The result will be in an int vreg */
2670                                 call->args [i] = conv;
2671                         }
2672                 }
2673         }
2674 #endif
2675
2676         call->need_unbox_trampoline = unbox_trampoline;
2677
2678 #ifdef ENABLE_LLVM
2679         if (COMPILE_LLVM (cfg))
2680                 mono_llvm_emit_call (cfg, call);
2681         else
2682                 mono_arch_emit_call (cfg, call);
2683 #else
2684         mono_arch_emit_call (cfg, call);
2685 #endif
2686
2687         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2688         cfg->flags |= MONO_CFG_HAS_CALLS;
2689         
2690         return call;
2691 }
2692
2693 static void
2694 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2695 {
2696         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2697         cfg->uses_rgctx_reg = TRUE;
2698         call->rgctx_reg = TRUE;
2699 #ifdef ENABLE_LLVM
2700         call->rgctx_arg_reg = rgctx_reg;
2701 #endif
2702 }       
2703
2704 inline static MonoInst*
2705 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2706 {
2707         MonoCallInst *call;
2708         MonoInst *ins;
2709         int rgctx_reg = -1;
2710         gboolean check_sp = FALSE;
2711
2712         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2713                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2714
2715                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2716                         check_sp = TRUE;
2717         }
2718
2719         if (rgctx_arg) {
2720                 rgctx_reg = mono_alloc_preg (cfg);
2721                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2722         }
2723
2724         if (check_sp) {
2725                 if (!cfg->stack_inbalance_var)
2726                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2727
2728                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2729                 ins->dreg = cfg->stack_inbalance_var->dreg;
2730                 MONO_ADD_INS (cfg->cbb, ins);
2731         }
2732
2733         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2734
2735         call->inst.sreg1 = addr->dreg;
2736
2737         if (imt_arg)
2738                 emit_imt_argument (cfg, call, NULL, imt_arg);
2739
2740         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2741
2742         if (check_sp) {
2743                 int sp_reg;
2744
2745                 sp_reg = mono_alloc_preg (cfg);
2746
2747                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2748                 ins->dreg = sp_reg;
2749                 MONO_ADD_INS (cfg->cbb, ins);
2750
2751                 /* Restore the stack so we don't crash when throwing the exception */
2752                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2753                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2754                 MONO_ADD_INS (cfg->cbb, ins);
2755
2756                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2757                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2758         }
2759
2760         if (rgctx_arg)
2761                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2762
2763         return (MonoInst*)call;
2764 }
2765
2766 static MonoInst*
2767 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2768
2769 static MonoInst*
2770 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2771 static MonoInst*
2772 emit_get_rgctx_klass (MonoCompile *cfg, int context_used, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2773
2774 static MonoInst*
2775 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2776                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2777 {
2778 #ifndef DISABLE_REMOTING
2779         gboolean might_be_remote = FALSE;
2780 #endif
2781         gboolean virtual_ = this_ins != NULL;
2782         gboolean enable_for_aot = TRUE;
2783         int context_used;
2784         MonoCallInst *call;
2785         MonoInst *call_target = NULL;
2786         int rgctx_reg = 0;
2787         gboolean need_unbox_trampoline;
2788
2789         if (!sig)
2790                 sig = mono_method_signature (method);
2791
2792         if (cfg->llvm_only && (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE))
2793                 g_assert_not_reached ();
2794
2795         if (rgctx_arg) {
2796                 rgctx_reg = mono_alloc_preg (cfg);
2797                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2798         }
2799
2800         if (method->string_ctor) {
2801                 /* Create the real signature */
2802                 /* FIXME: Cache these */
2803                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2804                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2805
2806                 sig = ctor_sig;
2807         }
2808
2809         context_used = mini_method_check_context_used (cfg, method);
2810
2811 #ifndef DISABLE_REMOTING
2812         might_be_remote = this_ins && sig->hasthis &&
2813                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2814                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2815
2816         if (might_be_remote && context_used) {
2817                 MonoInst *addr;
2818
2819                 g_assert (cfg->gshared);
2820
2821                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2822
2823                 return mono_emit_calli (cfg, sig, args, addr, NULL, NULL);
2824         }
2825 #endif
2826
2827         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2828                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2829
2830         need_unbox_trampoline = method->klass == mono_defaults.object_class || (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE);
2831
2832         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2833
2834 #ifndef DISABLE_REMOTING
2835         if (might_be_remote)
2836                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2837         else
2838 #endif
2839                 call->method = method;
2840         call->inst.flags |= MONO_INST_HAS_METHOD;
2841         call->inst.inst_left = this_ins;
2842         call->tail_call = tail;
2843
2844         if (virtual_) {
2845                 int vtable_reg, slot_reg, this_reg;
2846                 int offset;
2847
2848                 this_reg = this_ins->dreg;
2849
2850                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2851                         MonoInst *dummy_use;
2852
2853                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2854
2855                         /* Make a call to delegate->invoke_impl */
2856                         call->inst.inst_basereg = this_reg;
2857                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2858                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2859
2860                         /* We must emit a dummy use here because the delegate trampoline will
2861                         replace the 'this' argument with the delegate target making this activation
2862                         no longer a root for the delegate.
2863                         This is an issue for delegates that target collectible code such as dynamic
2864                         methods of GC'able assemblies.
2865
2866                         For a test case look into #667921.
2867
2868                         FIXME: a dummy use is not the best way to do it as the local register allocator
2869                         will put it on a caller save register and spil it around the call. 
2870                         Ideally, we would either put it on a callee save register or only do the store part.  
2871                          */
2872                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2873
2874                         return (MonoInst*)call;
2875                 }
2876
2877                 if ((!cfg->compile_aot || enable_for_aot) && 
2878                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2879                          (MONO_METHOD_IS_FINAL (method) &&
2880                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2881                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2882                         /* 
2883                          * the method is not virtual, we just need to ensure this is not null
2884                          * and then we can call the method directly.
2885                          */
2886 #ifndef DISABLE_REMOTING
2887                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2888                                 /* 
2889                                  * The check above ensures method is not gshared, this is needed since
2890                                  * gshared methods can't have wrappers.
2891                                  */
2892                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2893                         }
2894 #endif
2895
2896                         if (!method->string_ctor)
2897                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2898
2899                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2900                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2901                         /*
2902                          * the method is virtual, but we can statically dispatch since either
2903                          * it's class or the method itself are sealed.
2904                          * But first we need to ensure it's not a null reference.
2905                          */
2906                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2907
2908                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2909                 } else if (call_target) {
2910                         vtable_reg = alloc_preg (cfg);
2911                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2912
2913                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2914                         call->inst.sreg1 = call_target->dreg;
2915                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2916                 } else {
2917                         vtable_reg = alloc_preg (cfg);
2918                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2919                         if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
2920                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2921                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2922                                 slot_reg = vtable_reg;
2923                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2924                         } else {
2925                                 slot_reg = vtable_reg;
2926                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2927                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2928                                 if (imt_arg) {
2929                                         g_assert (mono_method_signature (method)->generic_param_count);
2930                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2931                                 }
2932                         }
2933
2934                         call->inst.sreg1 = slot_reg;
2935                         call->inst.inst_offset = offset;
2936                         call->is_virtual = TRUE;
2937                 }
2938         }
2939
2940         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2941
2942         if (rgctx_arg)
2943                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2944
2945         return (MonoInst*)call;
2946 }
2947
2948 MonoInst*
2949 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2950 {
2951         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2952 }
2953
2954 MonoInst*
2955 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2956                                            MonoInst **args)
2957 {
2958         MonoCallInst *call;
2959
2960         g_assert (sig);
2961
2962         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2963         call->fptr = func;
2964
2965         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2966
2967         return (MonoInst*)call;
2968 }
2969
2970 MonoInst*
2971 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2972 {
2973         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2974
2975         g_assert (info);
2976
2977         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2978 }
2979
2980 /*
2981  * mono_emit_abs_call:
2982  *
2983  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2984  */
2985 inline static MonoInst*
2986 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2987                                         MonoMethodSignature *sig, MonoInst **args)
2988 {
2989         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2990         MonoInst *ins;
2991
2992         /* 
2993          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2994          * handle it.
2995          */
2996         if (cfg->abs_patches == NULL)
2997                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2998         g_hash_table_insert (cfg->abs_patches, ji, ji);
2999         ins = mono_emit_native_call (cfg, ji, sig, args);
3000         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
3001         return ins;
3002 }
3003
3004 static MonoMethodSignature*
3005 sig_to_rgctx_sig (MonoMethodSignature *sig)
3006 {
3007         // FIXME: memory allocation
3008         MonoMethodSignature *res;
3009         int i;
3010
3011         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
3012         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
3013         res->param_count = sig->param_count + 1;
3014         for (i = 0; i < sig->param_count; ++i)
3015                 res->params [i] = sig->params [i];
3016         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
3017         return res;
3018 }
3019
3020 /* Make an indirect call to FSIG passing an additional argument */
3021 static MonoInst*
3022 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
3023 {
3024         MonoMethodSignature *csig;
3025         MonoInst *args_buf [16];
3026         MonoInst **args;
3027         int i, pindex, tmp_reg;
3028
3029         /* Make a call with an rgctx/extra arg */
3030         if (fsig->param_count + 2 < 16)
3031                 args = args_buf;
3032         else
3033                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
3034         pindex = 0;
3035         if (fsig->hasthis)
3036                 args [pindex ++] = orig_args [0];
3037         for (i = 0; i < fsig->param_count; ++i)
3038                 args [pindex ++] = orig_args [fsig->hasthis + i];
3039         tmp_reg = alloc_preg (cfg);
3040         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
3041         csig = sig_to_rgctx_sig (fsig);
3042         return mono_emit_calli (cfg, csig, args, call_target, NULL, NULL);
3043 }
3044
3045 /* Emit an indirect call to the function descriptor ADDR */
3046 static MonoInst*
3047 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
3048 {
3049         int addr_reg, arg_reg;
3050         MonoInst *call_target;
3051
3052         g_assert (cfg->llvm_only);
3053
3054         /*
3055          * addr points to a <addr, arg> pair, load both of them, and
3056          * make a call to addr, passing arg as an extra arg.
3057          */
3058         addr_reg = alloc_preg (cfg);
3059         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
3060         arg_reg = alloc_preg (cfg);
3061         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
3062
3063         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
3064 }
3065
3066 static gboolean
3067 direct_icalls_enabled (MonoCompile *cfg)
3068 {
3069         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
3070 #ifdef TARGET_AMD64
3071         if (cfg->compile_llvm && !cfg->llvm_only)
3072                 return FALSE;
3073 #endif
3074         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
3075                 return FALSE;
3076         return TRUE;
3077 }
3078
3079 MonoInst*
3080 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
3081 {
3082         /*
3083          * Call the jit icall without a wrapper if possible.
3084          * The wrapper is needed for the following reasons:
3085          * - to handle exceptions thrown using mono_raise_exceptions () from the
3086          *   icall function. The EH code needs the lmf frame pushed by the
3087          *   wrapper to be able to unwind back to managed code.
3088          * - to be able to do stack walks for asynchronously suspended
3089          *   threads when debugging.
3090          */
3091         if (info->no_raise && direct_icalls_enabled (cfg)) {
3092                 char *name;
3093                 int costs;
3094
3095                 if (!info->wrapper_method) {
3096                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
3097                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
3098                         g_free (name);
3099                         mono_memory_barrier ();
3100                 }
3101
3102                 /*
3103                  * Inline the wrapper method, which is basically a call to the C icall, and
3104                  * an exception check.
3105                  */
3106                 costs = inline_method (cfg, info->wrapper_method, NULL,
3107                                                            args, NULL, il_offset, TRUE);
3108                 g_assert (costs > 0);
3109                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
3110
3111                 return args [0];
3112         } else {
3113                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
3114         }
3115 }
3116  
3117 static MonoInst*
3118 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
3119 {
3120         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3121                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
3122                         int widen_op = -1;
3123
3124                         /* 
3125                          * Native code might return non register sized integers 
3126                          * without initializing the upper bits.
3127                          */
3128                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
3129                         case OP_LOADI1_MEMBASE:
3130                                 widen_op = OP_ICONV_TO_I1;
3131                                 break;
3132                         case OP_LOADU1_MEMBASE:
3133                                 widen_op = OP_ICONV_TO_U1;
3134                                 break;
3135                         case OP_LOADI2_MEMBASE:
3136                                 widen_op = OP_ICONV_TO_I2;
3137                                 break;
3138                         case OP_LOADU2_MEMBASE:
3139                                 widen_op = OP_ICONV_TO_U2;
3140                                 break;
3141                         default:
3142                                 break;
3143                         }
3144
3145                         if (widen_op != -1) {
3146                                 int dreg = alloc_preg (cfg);
3147                                 MonoInst *widen;
3148
3149                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
3150                                 widen->type = ins->type;
3151                                 ins = widen;
3152                         }
3153                 }
3154         }
3155
3156         return ins;
3157 }
3158
3159 static MonoMethod*
3160 get_memcpy_method (void)
3161 {
3162         static MonoMethod *memcpy_method = NULL;
3163         if (!memcpy_method) {
3164                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
3165                 if (!memcpy_method)
3166                         g_error ("Old corlib found. Install a new one");
3167         }
3168         return memcpy_method;
3169 }
3170
3171 static void
3172 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
3173 {
3174         MonoClassField *field;
3175         gpointer iter = NULL;
3176
3177         while ((field = mono_class_get_fields (klass, &iter))) {
3178                 int foffset;
3179
3180                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
3181                         continue;
3182                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
3183                 if (mini_type_is_reference (mono_field_get_type (field))) {
3184                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
3185                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
3186                 } else {
3187                         MonoClass *field_class = mono_class_from_mono_type (field->type);
3188                         if (field_class->has_references)
3189                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
3190                 }
3191         }
3192 }
3193
3194 static void
3195 emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
3196 {
3197         int card_table_shift_bits;
3198         gpointer card_table_mask;
3199         guint8 *card_table;
3200         MonoInst *dummy_use;
3201         int nursery_shift_bits;
3202         size_t nursery_size;
3203
3204         if (!cfg->gen_write_barriers)
3205                 return;
3206
3207         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3208
3209         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
3210
3211         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
3212                 MonoInst *wbarrier;
3213
3214                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
3215                 wbarrier->sreg1 = ptr->dreg;
3216                 wbarrier->sreg2 = value->dreg;
3217                 MONO_ADD_INS (cfg->cbb, wbarrier);
3218         } else if (card_table && !cfg->compile_aot && !mono_gc_card_table_nursery_check ()) {
3219                 int offset_reg = alloc_preg (cfg);
3220                 int card_reg;
3221                 MonoInst *ins;
3222
3223                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
3224                 if (card_table_mask)
3225                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
3226
3227                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
3228                  * IMM's larger than 32bits.
3229                  */
3230                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
3231                 card_reg = ins->dreg;
3232
3233                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
3234                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
3235         } else {
3236                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
3237                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
3238         }
3239
3240         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
3241 }
3242
3243 static gboolean
3244 mono_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
3245 {
3246         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
3247         unsigned need_wb = 0;
3248
3249         if (align == 0)
3250                 align = 4;
3251
3252         /*types with references can't have alignment smaller than sizeof(void*) */
3253         if (align < SIZEOF_VOID_P)
3254                 return FALSE;
3255
3256         /*This value cannot be bigger than 32 due to the way we calculate the required wb bitmap.*/
3257         if (size > 32 * SIZEOF_VOID_P)
3258                 return FALSE;
3259
3260         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
3261
3262         /* We don't unroll more than 5 stores to avoid code bloat. */
3263         if (size > 5 * SIZEOF_VOID_P) {
3264                 /*This is harmless and simplify mono_gc_wbarrier_value_copy_bitmap */
3265                 size += (SIZEOF_VOID_P - 1);
3266                 size &= ~(SIZEOF_VOID_P - 1);
3267
3268                 EMIT_NEW_ICONST (cfg, iargs [2], size);
3269                 EMIT_NEW_ICONST (cfg, iargs [3], need_wb);
3270                 mono_emit_jit_icall (cfg, mono_gc_wbarrier_value_copy_bitmap, iargs);
3271                 return TRUE;
3272         }
3273
3274         destreg = iargs [0]->dreg;
3275         srcreg = iargs [1]->dreg;
3276         offset = 0;
3277
3278         dest_ptr_reg = alloc_preg (cfg);
3279         tmp_reg = alloc_preg (cfg);
3280
3281         /*tmp = dreg*/
3282         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
3283
3284         while (size >= SIZEOF_VOID_P) {
3285                 MonoInst *load_inst;
3286                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
3287                 load_inst->dreg = tmp_reg;
3288                 load_inst->inst_basereg = srcreg;
3289                 load_inst->inst_offset = offset;
3290                 MONO_ADD_INS (cfg->cbb, load_inst);
3291
3292                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
3293
3294                 if (need_wb & 0x1)
3295                         emit_write_barrier (cfg, iargs [0], load_inst);
3296
3297                 offset += SIZEOF_VOID_P;
3298                 size -= SIZEOF_VOID_P;
3299                 need_wb >>= 1;
3300
3301                 /*tmp += sizeof (void*)*/
3302                 if (size >= SIZEOF_VOID_P) {
3303                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
3304                         MONO_ADD_INS (cfg->cbb, iargs [0]);
3305                 }
3306         }
3307
3308         /* Those cannot be references since size < sizeof (void*) */
3309         while (size >= 4) {
3310                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
3311                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
3312                 offset += 4;
3313                 size -= 4;
3314         }
3315
3316         while (size >= 2) {
3317                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
3318                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
3319                 offset += 2;
3320                 size -= 2;
3321         }
3322
3323         while (size >= 1) {
3324                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
3325                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
3326                 offset += 1;
3327                 size -= 1;
3328         }
3329
3330         return TRUE;
3331 }
3332
3333 /*
3334  * Emit code to copy a valuetype of type @klass whose address is stored in
3335  * @src->dreg to memory whose address is stored at @dest->dreg.
3336  */
3337 void
3338 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
3339 {
3340         MonoInst *iargs [4];
3341         int n;
3342         guint32 align = 0;
3343         MonoMethod *memcpy_method;
3344         MonoInst *size_ins = NULL;
3345         MonoInst *memcpy_ins = NULL;
3346
3347         g_assert (klass);
3348         if (cfg->gshared)
3349                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3350
3351         /*
3352          * This check breaks with spilled vars... need to handle it during verification anyway.
3353          * g_assert (klass && klass == src->klass && klass == dest->klass);
3354          */
3355
3356         if (mini_is_gsharedvt_klass (klass)) {
3357                 g_assert (!native);
3358                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3359                 memcpy_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3360         }
3361
3362         if (native)
3363                 n = mono_class_native_size (klass, &align);
3364         else
3365                 n = mono_class_value_size (klass, &align);
3366
3367         /* if native is true there should be no references in the struct */
3368         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3369                 /* Avoid barriers when storing to the stack */
3370                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3371                           (dest->opcode == OP_LDADDR))) {
3372                         int context_used;
3373
3374                         iargs [0] = dest;
3375                         iargs [1] = src;
3376
3377                         context_used = mini_class_check_context_used (cfg, klass);
3378
3379                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3380                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mono_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3381                                 return;
3382                         } else if (context_used) {
3383                                 iargs [2] = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3384                         }  else {
3385                                 iargs [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3386                                 if (!cfg->compile_aot)
3387                                         mono_class_compute_gc_descriptor (klass);
3388                         }
3389
3390                         if (size_ins)
3391                                 mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3392                         else
3393                                 mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3394                         return;
3395                 }
3396         }
3397
3398         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3399                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3400                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3401         } else {
3402                 iargs [0] = dest;
3403                 iargs [1] = src;
3404                 if (size_ins)
3405                         iargs [2] = size_ins;
3406                 else
3407                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3408                 
3409                 memcpy_method = get_memcpy_method ();
3410                 if (memcpy_ins)
3411                         mono_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3412                 else
3413                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3414         }
3415 }
3416
3417 static MonoMethod*
3418 get_memset_method (void)
3419 {
3420         static MonoMethod *memset_method = NULL;
3421         if (!memset_method) {
3422                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3423                 if (!memset_method)
3424                         g_error ("Old corlib found. Install a new one");
3425         }
3426         return memset_method;
3427 }
3428
3429 void
3430 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3431 {
3432         MonoInst *iargs [3];
3433         int n;
3434         guint32 align;
3435         MonoMethod *memset_method;
3436         MonoInst *size_ins = NULL;
3437         MonoInst *bzero_ins = NULL;
3438         static MonoMethod *bzero_method;
3439
3440         /* FIXME: Optimize this for the case when dest is an LDADDR */
3441         mono_class_init (klass);
3442         if (mini_is_gsharedvt_klass (klass)) {
3443                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3444                 bzero_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3445                 if (!bzero_method)
3446                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3447                 g_assert (bzero_method);
3448                 iargs [0] = dest;
3449                 iargs [1] = size_ins;
3450                 mono_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3451                 return;
3452         }
3453
3454         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3455
3456         n = mono_class_value_size (klass, &align);
3457
3458         if (n <= sizeof (gpointer) * 8) {
3459                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3460         }
3461         else {
3462                 memset_method = get_memset_method ();
3463                 iargs [0] = dest;
3464                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3465                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3466                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3467         }
3468 }
3469
3470 /*
3471  * emit_get_rgctx:
3472  *
3473  *   Emit IR to return either the this pointer for instance method,
3474  * or the mrgctx for static methods.
3475  */
3476 static MonoInst*
3477 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3478 {
3479         MonoInst *this_ins = NULL;
3480
3481         g_assert (cfg->gshared);
3482
3483         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3484                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3485                         !method->klass->valuetype)
3486                 EMIT_NEW_ARGLOAD (cfg, this_ins, 0);
3487
3488         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3489                 MonoInst *mrgctx_loc, *mrgctx_var;
3490
3491                 g_assert (!this_ins);
3492                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3493
3494                 mrgctx_loc = mono_get_vtable_var (cfg);
3495                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3496
3497                 return mrgctx_var;
3498         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3499                 MonoInst *vtable_loc, *vtable_var;
3500
3501                 g_assert (!this_ins);
3502
3503                 vtable_loc = mono_get_vtable_var (cfg);
3504                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3505
3506                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3507                         MonoInst *mrgctx_var = vtable_var;
3508                         int vtable_reg;
3509
3510                         vtable_reg = alloc_preg (cfg);
3511                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3512                         vtable_var->type = STACK_PTR;
3513                 }
3514
3515                 return vtable_var;
3516         } else {
3517                 MonoInst *ins;
3518                 int vtable_reg;
3519         
3520                 vtable_reg = alloc_preg (cfg);
3521                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3522                 return ins;
3523         }
3524 }
3525
3526 static MonoJumpInfoRgctxEntry *
3527 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3528 {
3529         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3530         res->method = method;
3531         res->in_mrgctx = in_mrgctx;
3532         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3533         res->data->type = patch_type;
3534         res->data->data.target = patch_data;
3535         res->info_type = info_type;
3536
3537         return res;
3538 }
3539
3540 static inline MonoInst*
3541 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3542 {
3543         MonoInst *args [16];
3544         MonoInst *call;
3545
3546         // FIXME: No fastpath since the slot is not a compile time constant
3547         args [0] = rgctx;
3548         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3549         if (entry->in_mrgctx)
3550                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3551         else
3552                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3553         return call;
3554 #if 0
3555         /*
3556          * FIXME: This can be called during decompose, which is a problem since it creates
3557          * new bblocks.
3558          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3559          */
3560         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3561         gboolean mrgctx;
3562         MonoBasicBlock *is_null_bb, *end_bb;
3563         MonoInst *res, *ins, *call;
3564         MonoInst *args[16];
3565
3566         slot = mini_get_rgctx_entry_slot (entry);
3567
3568         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3569         index = MONO_RGCTX_SLOT_INDEX (slot);
3570         if (mrgctx)
3571                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3572         for (depth = 0; ; ++depth) {
3573                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3574
3575                 if (index < size - 1)
3576                         break;
3577                 index -= size - 1;
3578         }
3579
3580         NEW_BBLOCK (cfg, end_bb);
3581         NEW_BBLOCK (cfg, is_null_bb);
3582
3583         if (mrgctx) {
3584                 rgctx_reg = rgctx->dreg;
3585         } else {
3586                 rgctx_reg = alloc_preg (cfg);
3587
3588                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3589                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3590                 NEW_BBLOCK (cfg, is_null_bb);
3591
3592                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3593                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3594         }
3595
3596         for (i = 0; i < depth; ++i) {
3597                 int array_reg = alloc_preg (cfg);
3598
3599                 /* load ptr to next array */
3600                 if (mrgctx && i == 0)
3601                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3602                 else
3603                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3604                 rgctx_reg = array_reg;
3605                 /* is the ptr null? */
3606                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3607                 /* if yes, jump to actual trampoline */
3608                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3609         }
3610
3611         /* fetch slot */
3612         val_reg = alloc_preg (cfg);
3613         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3614         /* is the slot null? */
3615         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3616         /* if yes, jump to actual trampoline */
3617         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3618
3619         /* Fastpath */
3620         res_reg = alloc_preg (cfg);
3621         MONO_INST_NEW (cfg, ins, OP_MOVE);
3622         ins->dreg = res_reg;
3623         ins->sreg1 = val_reg;
3624         MONO_ADD_INS (cfg->cbb, ins);
3625         res = ins;
3626         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3627
3628         /* Slowpath */
3629         MONO_START_BB (cfg, is_null_bb);
3630         args [0] = rgctx;
3631         EMIT_NEW_ICONST (cfg, args [1], index);
3632         if (mrgctx)
3633                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3634         else
3635                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3636         MONO_INST_NEW (cfg, ins, OP_MOVE);
3637         ins->dreg = res_reg;
3638         ins->sreg1 = call->dreg;
3639         MONO_ADD_INS (cfg->cbb, ins);
3640         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3641
3642         MONO_START_BB (cfg, end_bb);
3643
3644         return res;
3645 #endif
3646 }
3647
3648 /*
3649  * emit_rgctx_fetch:
3650  *
3651  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3652  * given by RGCTX.
3653  */
3654 static inline MonoInst*
3655 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3656 {
3657         if (cfg->llvm_only)
3658                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3659         else
3660                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3661 }
3662
3663 static MonoInst*
3664 emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3665                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3666 {
3667         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3668         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3669
3670         return emit_rgctx_fetch (cfg, rgctx, entry);
3671 }
3672
3673 static MonoInst*
3674 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3675                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3676 {
3677         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3678         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3679
3680         return emit_rgctx_fetch (cfg, rgctx, entry);
3681 }
3682
3683 static MonoInst*
3684 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3685                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3686 {
3687         MonoJumpInfoGSharedVtCall *call_info;
3688         MonoJumpInfoRgctxEntry *entry;
3689         MonoInst *rgctx;
3690
3691         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3692         call_info->sig = sig;
3693         call_info->method = cmethod;
3694
3695         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3696         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3697
3698         return emit_rgctx_fetch (cfg, rgctx, entry);
3699 }
3700
3701 /*
3702  * emit_get_rgctx_virt_method:
3703  *
3704  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3705  */
3706 static MonoInst*
3707 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3708                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3709 {
3710         MonoJumpInfoVirtMethod *info;
3711         MonoJumpInfoRgctxEntry *entry;
3712         MonoInst *rgctx;
3713
3714         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3715         info->klass = klass;
3716         info->method = virt_method;
3717
3718         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3719         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3720
3721         return emit_rgctx_fetch (cfg, rgctx, entry);
3722 }
3723
3724 static MonoInst*
3725 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3726                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3727 {
3728         MonoJumpInfoRgctxEntry *entry;
3729         MonoInst *rgctx;
3730
3731         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3732         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3733
3734         return emit_rgctx_fetch (cfg, rgctx, entry);
3735 }
3736
3737 /*
3738  * emit_get_rgctx_method:
3739  *
3740  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3741  * normal constants, else emit a load from the rgctx.
3742  */
3743 static MonoInst*
3744 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3745                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3746 {
3747         if (!context_used) {
3748                 MonoInst *ins;
3749
3750                 switch (rgctx_type) {
3751                 case MONO_RGCTX_INFO_METHOD:
3752                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3753                         return ins;
3754                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3755                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3756                         return ins;
3757                 default:
3758                         g_assert_not_reached ();
3759                 }
3760         } else {
3761                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3762                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3763
3764                 return emit_rgctx_fetch (cfg, rgctx, entry);
3765         }
3766 }
3767
3768 static MonoInst*
3769 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3770                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3771 {
3772         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->current_method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3773         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
3774
3775         return emit_rgctx_fetch (cfg, rgctx, entry);
3776 }
3777
3778 static int
3779 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3780 {
3781         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3782         MonoRuntimeGenericContextInfoTemplate *template_;
3783         int i, idx;
3784
3785         g_assert (info);
3786
3787         for (i = 0; i < info->num_entries; ++i) {
3788                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3789
3790                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3791                         return i;
3792         }
3793
3794         if (info->num_entries == info->count_entries) {
3795                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3796                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3797
3798                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3799
3800                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3801                 info->entries = new_entries;
3802                 info->count_entries = new_count_entries;
3803         }
3804
3805         idx = info->num_entries;
3806         template_ = &info->entries [idx];
3807         template_->info_type = rgctx_type;
3808         template_->data = data;
3809
3810         info->num_entries ++;
3811
3812         return idx;
3813 }
3814
3815 /*
3816  * emit_get_gsharedvt_info:
3817  *
3818  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3819  */
3820 static MonoInst*
3821 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3822 {
3823         MonoInst *ins;
3824         int idx, dreg;
3825
3826         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3827         /* Load info->entries [idx] */
3828         dreg = alloc_preg (cfg);
3829         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3830
3831         return ins;
3832 }
3833
3834 static MonoInst*
3835 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3836 {
3837         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3838 }
3839
3840 /*
3841  * On return the caller must check @klass for load errors.
3842  */
3843 static void
3844 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3845 {
3846         MonoInst *vtable_arg;
3847         int context_used;
3848
3849         context_used = mini_class_check_context_used (cfg, klass);
3850
3851         if (context_used) {
3852                 vtable_arg = emit_get_rgctx_klass (cfg, context_used,
3853                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3854         } else {
3855                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3856
3857                 if (!vtable)
3858                         return;
3859                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3860         }
3861
3862         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3863                 MonoInst *ins;
3864
3865                 /*
3866                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3867                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3868                  */
3869                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3870                 ins->sreg1 = vtable_arg->dreg;
3871                 MONO_ADD_INS (cfg->cbb, ins);
3872         } else {
3873                 static int byte_offset = -1;
3874                 static guint8 bitmask;
3875                 int bits_reg, inited_reg;
3876                 MonoBasicBlock *inited_bb;
3877                 MonoInst *args [16];
3878
3879                 if (byte_offset < 0)
3880                         mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
3881
3882                 bits_reg = alloc_ireg (cfg);
3883                 inited_reg = alloc_ireg (cfg);
3884
3885                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, bits_reg, vtable_arg->dreg, byte_offset);
3886                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, inited_reg, bits_reg, bitmask);
3887
3888                 NEW_BBLOCK (cfg, inited_bb);
3889
3890                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3891                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3892
3893                 args [0] = vtable_arg;
3894                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3895
3896                 MONO_START_BB (cfg, inited_bb);
3897         }
3898 }
3899
3900 static void
3901 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3902 {
3903         MonoInst *ins;
3904
3905         if (cfg->gen_seq_points && cfg->method == method) {
3906                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3907                 if (nonempty_stack)
3908                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3909                 MONO_ADD_INS (cfg->cbb, ins);
3910         }
3911 }
3912
3913 static void
3914 save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3915 {
3916         if (mini_get_debug_options ()->better_cast_details) {
3917                 int vtable_reg = alloc_preg (cfg);
3918                 int klass_reg = alloc_preg (cfg);
3919                 MonoBasicBlock *is_null_bb = NULL;
3920                 MonoInst *tls_get;
3921                 int to_klass_reg, context_used;
3922
3923                 if (null_check) {
3924                         NEW_BBLOCK (cfg, is_null_bb);
3925
3926                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3927                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3928                 }
3929
3930                 tls_get = mono_get_jit_tls_intrinsic (cfg);
3931                 if (!tls_get) {
3932                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3933                         exit (1);
3934                 }
3935
3936                 MONO_ADD_INS (cfg->cbb, tls_get);
3937                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3938                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3939
3940                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3941
3942                 context_used = mini_class_check_context_used (cfg, klass);
3943                 if (context_used) {
3944                         MonoInst *class_ins;
3945
3946                         class_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3947                         to_klass_reg = class_ins->dreg;
3948                 } else {
3949                         to_klass_reg = alloc_preg (cfg);
3950                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3951                 }
3952                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3953
3954                 if (null_check)
3955                         MONO_START_BB (cfg, is_null_bb);
3956         }
3957 }
3958
3959 static void
3960 reset_cast_details (MonoCompile *cfg)
3961 {
3962         /* Reset the variables holding the cast details */
3963         if (mini_get_debug_options ()->better_cast_details) {
3964                 MonoInst *tls_get = mono_get_jit_tls_intrinsic (cfg);
3965
3966                 MONO_ADD_INS (cfg->cbb, tls_get);
3967                 /* It is enough to reset the from field */
3968                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3969         }
3970 }
3971
3972 /*
3973  * On return the caller must check @array_class for load errors
3974  */
3975 static void
3976 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3977 {
3978         int vtable_reg = alloc_preg (cfg);
3979         int context_used;
3980
3981         context_used = mini_class_check_context_used (cfg, array_class);
3982
3983         save_cast_details (cfg, array_class, obj->dreg, FALSE);
3984
3985         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3986
3987         if (cfg->opt & MONO_OPT_SHARED) {
3988                 int class_reg = alloc_preg (cfg);
3989                 MonoInst *ins;
3990
3991                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3992                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3993                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3994         } else if (context_used) {
3995                 MonoInst *vtable_ins;
3996
3997                 vtable_ins = emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3998                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3999         } else {
4000                 if (cfg->compile_aot) {
4001                         int vt_reg;
4002                         MonoVTable *vtable;
4003
4004                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
4005                                 return;
4006                         vt_reg = alloc_preg (cfg);
4007                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
4008                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
4009                 } else {
4010                         MonoVTable *vtable;
4011                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
4012                                 return;
4013                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
4014                 }
4015         }
4016         
4017         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
4018
4019         reset_cast_details (cfg);
4020 }
4021
4022 /**
4023  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
4024  * generic code is generated.
4025  */
4026 static MonoInst*
4027 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
4028 {
4029         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
4030
4031         if (context_used) {
4032                 MonoInst *rgctx, *addr;
4033
4034                 /* FIXME: What if the class is shared?  We might not
4035                    have to get the address of the method from the
4036                    RGCTX. */
4037                 addr = emit_get_rgctx_method (cfg, context_used, method,
4038                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4039                 if (cfg->llvm_only && cfg->gsharedvt) {
4040                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4041                 } else {
4042                         rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
4043
4044                         return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4045                 }
4046         } else {
4047                 gboolean pass_vtable, pass_mrgctx;
4048                 MonoInst *rgctx_arg = NULL;
4049
4050                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4051                 g_assert (!pass_mrgctx);
4052
4053                 if (pass_vtable) {
4054                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4055
4056                         g_assert (vtable);
4057                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4058                 }
4059
4060                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4061         }
4062 }
4063
4064 static MonoInst*
4065 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
4066 {
4067         MonoInst *add;
4068         int obj_reg;
4069         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
4070         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
4071         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
4072         int rank_reg = alloc_dreg (cfg ,STACK_I4);
4073
4074         obj_reg = sp [0]->dreg;
4075         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4076         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
4077
4078         /* FIXME: generics */
4079         g_assert (klass->rank == 0);
4080                         
4081         // Check rank == 0
4082         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
4083         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4084
4085         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4086         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
4087
4088         if (context_used) {
4089                 MonoInst *element_class;
4090
4091                 /* This assertion is from the unboxcast insn */
4092                 g_assert (klass->rank == 0);
4093
4094                 element_class = emit_get_rgctx_klass (cfg, context_used,
4095                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
4096
4097                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
4098                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4099         } else {
4100                 save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
4101                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
4102                 reset_cast_details (cfg);
4103         }
4104
4105         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
4106         MONO_ADD_INS (cfg->cbb, add);
4107         add->type = STACK_MP;
4108         add->klass = klass;
4109
4110         return add;
4111 }
4112
4113 static MonoInst*
4114 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
4115 {
4116         MonoInst *addr, *klass_inst, *is_ref, *args[16];
4117         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4118         MonoInst *ins;
4119         int dreg, addr_reg;
4120
4121         klass_inst = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
4122
4123         /* obj */
4124         args [0] = obj;
4125
4126         /* klass */
4127         args [1] = klass_inst;
4128
4129         /* CASTCLASS */
4130         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
4131
4132         NEW_BBLOCK (cfg, is_ref_bb);
4133         NEW_BBLOCK (cfg, is_nullable_bb);
4134         NEW_BBLOCK (cfg, end_bb);
4135         is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4136         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4137         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4138
4139         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4140         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4141
4142         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
4143         addr_reg = alloc_dreg (cfg, STACK_MP);
4144
4145         /* Non-ref case */
4146         /* UNBOX */
4147         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
4148         MONO_ADD_INS (cfg->cbb, addr);
4149
4150         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4151
4152         /* Ref case */
4153         MONO_START_BB (cfg, is_ref_bb);
4154
4155         /* Save the ref to a temporary */
4156         dreg = alloc_ireg (cfg);
4157         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
4158         addr->dreg = addr_reg;
4159         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
4160         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4161
4162         /* Nullable case */
4163         MONO_START_BB (cfg, is_nullable_bb);
4164
4165         {
4166                 MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
4167                 MonoInst *unbox_call;
4168                 MonoMethodSignature *unbox_sig;
4169
4170                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4171                 unbox_sig->ret = &klass->byval_arg;
4172                 unbox_sig->param_count = 1;
4173                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
4174
4175                 if (cfg->llvm_only)
4176                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
4177                 else
4178                         unbox_call = mono_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
4179
4180                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
4181                 addr->dreg = addr_reg;
4182         }
4183
4184         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4185
4186         /* End */
4187         MONO_START_BB (cfg, end_bb);
4188
4189         /* LDOBJ */
4190         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
4191
4192         return ins;
4193 }
4194
4195 /*
4196  * Returns NULL and set the cfg exception on error.
4197  */
4198 static MonoInst*
4199 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
4200 {
4201         MonoInst *iargs [2];
4202         void *alloc_ftn;
4203
4204         if (context_used) {
4205                 MonoInst *data;
4206                 MonoRgctxInfoType rgctx_info;
4207                 MonoInst *iargs [2];
4208                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
4209
4210                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
4211
4212                 if (cfg->opt & MONO_OPT_SHARED)
4213                         rgctx_info = MONO_RGCTX_INFO_KLASS;
4214                 else
4215                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
4216                 data = emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
4217
4218                 if (cfg->opt & MONO_OPT_SHARED) {
4219                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4220                         iargs [1] = data;
4221                         alloc_ftn = ves_icall_object_new;
4222                 } else {
4223                         iargs [0] = data;
4224                         alloc_ftn = ves_icall_object_new_specific;
4225                 }
4226
4227                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
4228                         if (known_instance_size) {
4229                                 int size = mono_class_instance_size (klass);
4230                                 if (size < sizeof (MonoObject))
4231                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4232
4233                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
4234                         }
4235                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4236                 }
4237
4238                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4239         }
4240
4241         if (cfg->opt & MONO_OPT_SHARED) {
4242                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4243                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
4244
4245                 alloc_ftn = ves_icall_object_new;
4246         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !klass->generic_class) {
4247                 /* This happens often in argument checking code, eg. throw new FooException... */
4248                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
4249                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
4250                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
4251         } else {
4252                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4253                 MonoMethod *managed_alloc = NULL;
4254                 gboolean pass_lw;
4255
4256                 if (!vtable) {
4257                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4258                         cfg->exception_ptr = klass;
4259                         return NULL;
4260                 }
4261
4262                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
4263
4264                 if (managed_alloc) {
4265                         int size = mono_class_instance_size (klass);
4266                         if (size < sizeof (MonoObject))
4267                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4268
4269                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4270                         EMIT_NEW_ICONST (cfg, iargs [1], size);
4271                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4272                 }
4273                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
4274                 if (pass_lw) {
4275                         guint32 lw = vtable->klass->instance_size;
4276                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
4277                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
4278                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
4279                 }
4280                 else {
4281                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4282                 }
4283         }
4284
4285         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4286 }
4287         
4288 /*
4289  * Returns NULL and set the cfg exception on error.
4290  */     
4291 static MonoInst*
4292 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
4293 {
4294         MonoInst *alloc, *ins;
4295
4296         if (mono_class_is_nullable (klass)) {
4297                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4298
4299                 if (context_used) {
4300                         if (cfg->llvm_only && cfg->gsharedvt) {
4301                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4302                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4303                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4304                         } else {
4305                                 /* FIXME: What if the class is shared?  We might not
4306                                    have to get the method address from the RGCTX. */
4307                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4308                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4309                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
4310
4311                                 return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4312                         }
4313                 } else {
4314                         gboolean pass_vtable, pass_mrgctx;
4315                         MonoInst *rgctx_arg = NULL;
4316
4317                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4318                         g_assert (!pass_mrgctx);
4319
4320                         if (pass_vtable) {
4321                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4322
4323                                 g_assert (vtable);
4324                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4325                         }
4326
4327                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4328                 }
4329         }
4330
4331         if (mini_is_gsharedvt_klass (klass)) {
4332                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4333                 MonoInst *res, *is_ref, *src_var, *addr;
4334                 int dreg;
4335
4336                 dreg = alloc_ireg (cfg);
4337
4338                 NEW_BBLOCK (cfg, is_ref_bb);
4339                 NEW_BBLOCK (cfg, is_nullable_bb);
4340                 NEW_BBLOCK (cfg, end_bb);
4341                 is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4342                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4343                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4344
4345                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4346                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4347
4348                 /* Non-ref case */
4349                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4350                 if (!alloc)
4351                         return NULL;
4352                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4353                 ins->opcode = OP_STOREV_MEMBASE;
4354
4355                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4356                 res->type = STACK_OBJ;
4357                 res->klass = klass;
4358                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4359                 
4360                 /* Ref case */
4361                 MONO_START_BB (cfg, is_ref_bb);
4362
4363                 /* val is a vtype, so has to load the value manually */
4364                 src_var = get_vreg_to_inst (cfg, val->dreg);
4365                 if (!src_var)
4366                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4367                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4368                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4369                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4370
4371                 /* Nullable case */
4372                 MONO_START_BB (cfg, is_nullable_bb);
4373
4374                 {
4375                         MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass,
4376                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4377                         MonoInst *box_call;
4378                         MonoMethodSignature *box_sig;
4379
4380                         /*
4381                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4382                          * construct that method at JIT time, so have to do things by hand.
4383                          */
4384                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4385                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4386                         box_sig->param_count = 1;
4387                         box_sig->params [0] = &klass->byval_arg;
4388
4389                         if (cfg->llvm_only)
4390                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4391                         else
4392                                 box_call = mono_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4393                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4394                         res->type = STACK_OBJ;
4395                         res->klass = klass;
4396                 }
4397
4398                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4399
4400                 MONO_START_BB (cfg, end_bb);
4401
4402                 return res;
4403         } else {
4404                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4405                 if (!alloc)
4406                         return NULL;
4407
4408                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4409                 return alloc;
4410         }
4411 }
4412
4413 static gboolean
4414 mini_class_has_reference_variant_generic_argument (MonoCompile *cfg, MonoClass *klass, int context_used)
4415 {
4416         int i;
4417         MonoGenericContainer *container;
4418         MonoGenericInst *ginst;
4419
4420         if (klass->generic_class) {
4421                 container = klass->generic_class->container_class->generic_container;
4422                 ginst = klass->generic_class->context.class_inst;
4423         } else if (klass->generic_container && context_used) {
4424                 container = klass->generic_container;
4425                 ginst = container->context.class_inst;
4426         } else {
4427                 return FALSE;
4428         }
4429
4430         for (i = 0; i < container->type_argc; ++i) {
4431                 MonoType *type;
4432                 if (!(mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT)))
4433                         continue;
4434                 type = ginst->type_argv [i];
4435                 if (mini_type_is_reference (type))
4436                         return TRUE;
4437         }
4438         return FALSE;
4439 }
4440
4441 static GHashTable* direct_icall_type_hash;
4442
4443 static gboolean
4444 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4445 {
4446         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4447         if (!direct_icalls_enabled (cfg))
4448                 return FALSE;
4449
4450         /*
4451          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4452          * Whitelist a few icalls for now.
4453          */
4454         if (!direct_icall_type_hash) {
4455                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4456
4457                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4458                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4459                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4460                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4461                 mono_memory_barrier ();
4462                 direct_icall_type_hash = h;
4463         }
4464
4465         if (cmethod->klass == mono_defaults.math_class)
4466                 return TRUE;
4467         /* No locking needed */
4468         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4469                 return TRUE;
4470         return FALSE;
4471 }
4472
4473 #define is_complex_isinst(klass) ((klass->flags & TYPE_ATTRIBUTE_INTERFACE) || klass->rank || mono_class_is_nullable (klass) || mono_class_is_marshalbyref (klass) || (klass->flags & TYPE_ATTRIBUTE_SEALED) || klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR)
4474
4475 static MonoInst*
4476 emit_castclass_with_cache (MonoCompile *cfg, MonoClass *klass, MonoInst **args)
4477 {
4478         MonoMethod *mono_castclass;
4479         MonoInst *res;
4480
4481         mono_castclass = mono_marshal_get_castclass_with_cache ();
4482
4483         save_cast_details (cfg, klass, args [0]->dreg, TRUE);
4484         res = mono_emit_method_call (cfg, mono_castclass, args, NULL);
4485         reset_cast_details (cfg);
4486
4487         return res;
4488 }
4489
4490 static int
4491 get_castclass_cache_idx (MonoCompile *cfg)
4492 {
4493         /* Each CASTCLASS_CACHE patch needs a unique index which identifies the call site */
4494         cfg->castclass_cache_index ++;
4495         return (cfg->method_index << 16) | cfg->castclass_cache_index;
4496 }
4497
4498 static MonoInst*
4499 emit_castclass_with_cache_nonshared (MonoCompile *cfg, MonoInst *obj, MonoClass *klass)
4500 {
4501         MonoInst *args [3];
4502         int idx;
4503
4504         /* obj */
4505         args [0] = obj;
4506
4507         /* klass */
4508         EMIT_NEW_CLASSCONST (cfg, args [1], klass);
4509
4510         /* inline cache*/
4511         idx = get_castclass_cache_idx (cfg);
4512         args [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CASTCLASS_CACHE, GINT_TO_POINTER (idx));
4513
4514         /*The wrapper doesn't inline well so the bloat of inlining doesn't pay off.*/
4515         return emit_castclass_with_cache (cfg, klass, args);
4516 }
4517
4518 /*
4519  * Returns NULL and set the cfg exception on error.
4520  */
4521 static MonoInst*
4522 handle_castclass (MonoCompile *cfg, MonoClass *klass, MonoInst *src, guint8 *ip, int *inline_costs)
4523 {
4524         MonoBasicBlock *is_null_bb;
4525         int obj_reg = src->dreg;
4526         int vtable_reg = alloc_preg (cfg);
4527         int context_used;
4528         MonoInst *klass_inst = NULL, *res;
4529
4530         if (src->opcode == OP_PCONST && src->inst_p0 == 0)
4531                 return src;
4532
4533         context_used = mini_class_check_context_used (cfg, klass);
4534
4535         if (!context_used && mini_class_has_reference_variant_generic_argument (cfg, klass, context_used)) {
4536                 res = emit_castclass_with_cache_nonshared (cfg, src, klass);
4537                 (*inline_costs) += 2;
4538                 return res;
4539         } else if (!context_used && (mono_class_is_marshalbyref (klass) || klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
4540                 MonoMethod *mono_castclass;
4541                 MonoInst *iargs [1];
4542                 int costs;
4543
4544                 mono_castclass = mono_marshal_get_castclass (klass); 
4545                 iargs [0] = src;
4546                                 
4547                 save_cast_details (cfg, klass, src->dreg, TRUE);
4548                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), 
4549                                                            iargs, ip, cfg->real_offset, TRUE);
4550                 reset_cast_details (cfg);
4551                 CHECK_CFG_EXCEPTION;
4552                 g_assert (costs > 0);
4553                                 
4554                 cfg->real_offset += 5;
4555
4556                 (*inline_costs) += costs;
4557
4558                 return src;
4559         }
4560
4561         if (context_used) {
4562                 MonoInst *args [3];
4563
4564                 if (mini_class_has_reference_variant_generic_argument (cfg, klass, context_used) || is_complex_isinst (klass)) {
4565                         MonoInst *cache_ins;
4566
4567                         cache_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_CAST_CACHE);
4568
4569                         /* obj */
4570                         args [0] = src;
4571
4572                         /* klass - it's the second element of the cache entry*/
4573                         EMIT_NEW_LOAD_MEMBASE (cfg, args [1], OP_LOAD_MEMBASE, alloc_preg (cfg), cache_ins->dreg, sizeof (gpointer));
4574
4575                         /* cache */
4576                         args [2] = cache_ins;
4577
4578                         return emit_castclass_with_cache (cfg, klass, args);
4579                 }
4580
4581                 klass_inst = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
4582         }
4583
4584         NEW_BBLOCK (cfg, is_null_bb);
4585
4586         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4587         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
4588
4589         save_cast_details (cfg, klass, obj_reg, FALSE);
4590
4591         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4592                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4593                 mini_emit_iface_cast (cfg, vtable_reg, klass, NULL, NULL);
4594         } else {
4595                 int klass_reg = alloc_preg (cfg);
4596
4597                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4598
4599                 if (!klass->rank && !cfg->compile_aot && !(cfg->opt & MONO_OPT_SHARED) && (klass->flags & TYPE_ATTRIBUTE_SEALED)) {
4600                         /* the remoting code is broken, access the class for now */
4601                         if (0) { /*FIXME what exactly is broken? This change refers to r39380 from 2005 and mention some remoting fixes were due.*/
4602                                 MonoVTable *vt = mono_class_vtable (cfg->domain, klass);
4603                                 if (!vt) {
4604                                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4605                                         cfg->exception_ptr = klass;
4606                                         return NULL;
4607                                 }
4608                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vt);
4609                         } else {
4610                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4611                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
4612                         }
4613                         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
4614                 } else {
4615                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4616                         mini_emit_castclass_inst (cfg, obj_reg, klass_reg, klass, klass_inst, is_null_bb);
4617                 }
4618         }
4619
4620         MONO_START_BB (cfg, is_null_bb);
4621
4622         reset_cast_details (cfg);
4623
4624         return src;
4625
4626 exception_exit:
4627         return NULL;
4628 }
4629
4630 /*
4631  * Returns NULL and set the cfg exception on error.
4632  */
4633 static MonoInst*
4634 handle_isinst (MonoCompile *cfg, MonoClass *klass, MonoInst *src, int context_used)
4635 {
4636         MonoInst *ins;
4637         MonoBasicBlock *is_null_bb, *false_bb, *end_bb;
4638         int obj_reg = src->dreg;
4639         int vtable_reg = alloc_preg (cfg);
4640         int res_reg = alloc_ireg_ref (cfg);
4641         MonoInst *klass_inst = NULL;
4642
4643         if (context_used) {
4644                 MonoInst *args [3];
4645
4646                 if(mini_class_has_reference_variant_generic_argument (cfg, klass, context_used) || is_complex_isinst (klass)) {
4647                         MonoMethod *mono_isinst = mono_marshal_get_isinst_with_cache ();
4648                         MonoInst *cache_ins;
4649
4650                         cache_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_CAST_CACHE);
4651
4652                         /* obj */
4653                         args [0] = src;
4654
4655                         /* klass - it's the second element of the cache entry*/
4656                         EMIT_NEW_LOAD_MEMBASE (cfg, args [1], OP_LOAD_MEMBASE, alloc_preg (cfg), cache_ins->dreg, sizeof (gpointer));
4657
4658                         /* cache */
4659                         args [2] = cache_ins;
4660
4661                         return mono_emit_method_call (cfg, mono_isinst, args, NULL);
4662                 }
4663
4664                 klass_inst = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
4665         }
4666
4667         NEW_BBLOCK (cfg, is_null_bb);
4668         NEW_BBLOCK (cfg, false_bb);
4669         NEW_BBLOCK (cfg, end_bb);
4670
4671         /* Do the assignment at the beginning, so the other assignment can be if converted */
4672         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, res_reg, obj_reg);
4673         ins->type = STACK_OBJ;
4674         ins->klass = klass;
4675
4676         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4677         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_null_bb);
4678
4679         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4680
4681         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4682                 g_assert (!context_used);
4683                 /* the is_null_bb target simply copies the input register to the output */
4684                 mini_emit_iface_cast (cfg, vtable_reg, klass, false_bb, is_null_bb);
4685         } else {
4686                 int klass_reg = alloc_preg (cfg);
4687
4688                 if (klass->rank) {
4689                         int rank_reg = alloc_preg (cfg);
4690                         int eclass_reg = alloc_preg (cfg);
4691
4692                         g_assert (!context_used);
4693                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
4694                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, klass->rank);
4695                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4696                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4697                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, cast_class));
4698                         if (klass->cast_class == mono_defaults.object_class) {
4699                                 int parent_reg = alloc_preg (cfg);
4700                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, parent_reg, eclass_reg, MONO_STRUCT_OFFSET (MonoClass, parent));
4701                                 mini_emit_class_check_branch (cfg, parent_reg, mono_defaults.enum_class->parent, OP_PBNE_UN, is_null_bb);
4702                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);
4703                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4704                         } else if (klass->cast_class == mono_defaults.enum_class->parent) {
4705                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class->parent, OP_PBEQ, is_null_bb);
4706                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);                          
4707                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4708                         } else if (klass->cast_class == mono_defaults.enum_class) {
4709                                 mini_emit_class_check_branch (cfg, eclass_reg, mono_defaults.enum_class, OP_PBEQ, is_null_bb);
4710                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false_bb);
4711                         } else if (klass->cast_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
4712                                 mini_emit_iface_class_cast (cfg, eclass_reg, klass->cast_class, false_bb, is_null_bb);
4713                         } else {
4714                                 if ((klass->rank == 1) && (klass->byval_arg.type == MONO_TYPE_SZARRAY)) {
4715                                         /* Check that the object is a vector too */
4716                                         int bounds_reg = alloc_preg (cfg);
4717                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, obj_reg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4718                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
4719                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4720                                 }
4721
4722                                 /* the is_null_bb target simply copies the input register to the output */
4723                                 mini_emit_isninst_cast (cfg, eclass_reg, klass->cast_class, false_bb, is_null_bb);
4724                         }
4725                 } else if (mono_class_is_nullable (klass)) {
4726                         g_assert (!context_used);
4727                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4728                         /* the is_null_bb target simply copies the input register to the output */
4729                         mini_emit_isninst_cast (cfg, klass_reg, klass->cast_class, false_bb, is_null_bb);
4730                 } else {
4731                         if (!cfg->compile_aot && !(cfg->opt & MONO_OPT_SHARED) && (klass->flags & TYPE_ATTRIBUTE_SEALED)) {
4732                                 g_assert (!context_used);
4733                                 /* the remoting code is broken, access the class for now */
4734                                 if (0) {/*FIXME what exactly is broken? This change refers to r39380 from 2005 and mention some remoting fixes were due.*/
4735                                         MonoVTable *vt = mono_class_vtable (cfg->domain, klass);
4736                                         if (!vt) {
4737                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4738                                                 cfg->exception_ptr = klass;
4739                                                 return NULL;
4740                                         }
4741                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vt);
4742                                 } else {
4743                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4744                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, klass_reg, klass);
4745                                 }
4746                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false_bb);
4747                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, is_null_bb);
4748                         } else {
4749                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4750                                 /* the is_null_bb target simply copies the input register to the output */
4751                                 mini_emit_isninst_cast_inst (cfg, klass_reg, klass, klass_inst, false_bb, is_null_bb);
4752                         }
4753                 }
4754         }
4755
4756         MONO_START_BB (cfg, false_bb);
4757
4758         MONO_EMIT_NEW_PCONST (cfg, res_reg, 0);
4759         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4760
4761         MONO_START_BB (cfg, is_null_bb);
4762
4763         MONO_START_BB (cfg, end_bb);
4764
4765         return ins;
4766 }
4767
4768 static MonoInst*
4769 handle_cisinst (MonoCompile *cfg, MonoClass *klass, MonoInst *src)
4770 {
4771         /* This opcode takes as input an object reference and a class, and returns:
4772         0) if the object is an instance of the class,
4773         1) if the object is not instance of the class,
4774         2) if the object is a proxy whose type cannot be determined */
4775
4776         MonoInst *ins;
4777 #ifndef DISABLE_REMOTING
4778         MonoBasicBlock *true_bb, *false_bb, *false2_bb, *end_bb, *no_proxy_bb, *interface_fail_bb;
4779 #else
4780         MonoBasicBlock *true_bb, *false_bb, *end_bb;
4781 #endif
4782         int obj_reg = src->dreg;
4783         int dreg = alloc_ireg (cfg);
4784         int tmp_reg;
4785 #ifndef DISABLE_REMOTING
4786         int klass_reg = alloc_preg (cfg);
4787 #endif
4788
4789         NEW_BBLOCK (cfg, true_bb);
4790         NEW_BBLOCK (cfg, false_bb);
4791         NEW_BBLOCK (cfg, end_bb);
4792 #ifndef DISABLE_REMOTING
4793         NEW_BBLOCK (cfg, false2_bb);
4794         NEW_BBLOCK (cfg, no_proxy_bb);
4795 #endif
4796
4797         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4798         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, false_bb);
4799
4800         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4801 #ifndef DISABLE_REMOTING
4802                 NEW_BBLOCK (cfg, interface_fail_bb);
4803 #endif
4804
4805                 tmp_reg = alloc_preg (cfg);
4806                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4807 #ifndef DISABLE_REMOTING
4808                 mini_emit_iface_cast (cfg, tmp_reg, klass, interface_fail_bb, true_bb);
4809                 MONO_START_BB (cfg, interface_fail_bb);
4810                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4811                 
4812                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, false_bb);
4813
4814                 tmp_reg = alloc_preg (cfg);
4815                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4816                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4817                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, false2_bb);                
4818 #else
4819                 mini_emit_iface_cast (cfg, tmp_reg, klass, false_bb, true_bb);
4820 #endif
4821         } else {
4822 #ifndef DISABLE_REMOTING
4823                 tmp_reg = alloc_preg (cfg);
4824                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4825                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4826
4827                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, no_proxy_bb);          
4828                 tmp_reg = alloc_preg (cfg);
4829                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
4830                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
4831
4832                 tmp_reg = alloc_preg (cfg);             
4833                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4834                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4835                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, no_proxy_bb);
4836                 
4837                 mini_emit_isninst_cast (cfg, klass_reg, klass, false2_bb, true_bb);
4838                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, false2_bb);
4839
4840                 MONO_START_BB (cfg, no_proxy_bb);
4841
4842                 mini_emit_isninst_cast (cfg, klass_reg, klass, false_bb, true_bb);
4843 #else
4844                 g_error ("transparent proxy support is disabled while trying to JIT code that uses it");
4845 #endif
4846         }
4847
4848         MONO_START_BB (cfg, false_bb);
4849
4850         MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4851         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4852
4853 #ifndef DISABLE_REMOTING
4854         MONO_START_BB (cfg, false2_bb);
4855
4856         MONO_EMIT_NEW_ICONST (cfg, dreg, 2);
4857         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4858 #endif
4859
4860         MONO_START_BB (cfg, true_bb);
4861
4862         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4863
4864         MONO_START_BB (cfg, end_bb);
4865
4866         /* FIXME: */
4867         MONO_INST_NEW (cfg, ins, OP_ICONST);
4868         ins->dreg = dreg;
4869         ins->type = STACK_I4;
4870
4871         return ins;
4872 }
4873
4874 static MonoInst*
4875 handle_ccastclass (MonoCompile *cfg, MonoClass *klass, MonoInst *src)
4876 {
4877         /* This opcode takes as input an object reference and a class, and returns:
4878         0) if the object is an instance of the class,
4879         1) if the object is a proxy whose type cannot be determined
4880         an InvalidCastException exception is thrown otherwhise*/
4881         
4882         MonoInst *ins;
4883 #ifndef DISABLE_REMOTING
4884         MonoBasicBlock *end_bb, *ok_result_bb, *no_proxy_bb, *interface_fail_bb, *fail_1_bb;
4885 #else
4886         MonoBasicBlock *ok_result_bb;
4887 #endif
4888         int obj_reg = src->dreg;
4889         int dreg = alloc_ireg (cfg);
4890         int tmp_reg = alloc_preg (cfg);
4891
4892 #ifndef DISABLE_REMOTING
4893         int klass_reg = alloc_preg (cfg);
4894         NEW_BBLOCK (cfg, end_bb);
4895 #endif
4896
4897         NEW_BBLOCK (cfg, ok_result_bb);
4898
4899         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
4900         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, ok_result_bb);
4901
4902         save_cast_details (cfg, klass, obj_reg, FALSE);
4903
4904         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4905 #ifndef DISABLE_REMOTING
4906                 NEW_BBLOCK (cfg, interface_fail_bb);
4907         
4908                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4909                 mini_emit_iface_cast (cfg, tmp_reg, klass, interface_fail_bb, ok_result_bb);
4910                 MONO_START_BB (cfg, interface_fail_bb);
4911                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4912
4913                 mini_emit_class_check (cfg, klass_reg, mono_defaults.transparent_proxy_class);
4914
4915                 tmp_reg = alloc_preg (cfg);             
4916                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4917                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4918                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "InvalidCastException");
4919                 
4920                 MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4921                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4922 #else
4923                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4924                 mini_emit_iface_cast (cfg, tmp_reg, klass, NULL, NULL);
4925                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, ok_result_bb);
4926 #endif
4927         } else {
4928 #ifndef DISABLE_REMOTING
4929                 NEW_BBLOCK (cfg, no_proxy_bb);
4930
4931                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4932                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
4933                 mini_emit_class_check_branch (cfg, klass_reg, mono_defaults.transparent_proxy_class, OP_PBNE_UN, no_proxy_bb);          
4934
4935                 tmp_reg = alloc_preg (cfg);
4936                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
4937                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, tmp_reg, MONO_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
4938
4939                 tmp_reg = alloc_preg (cfg);
4940                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, tmp_reg, obj_reg, MONO_STRUCT_OFFSET (MonoTransparentProxy, custom_type_info));
4941                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, tmp_reg, 0);
4942                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, no_proxy_bb);
4943
4944                 NEW_BBLOCK (cfg, fail_1_bb);
4945                 
4946                 mini_emit_isninst_cast (cfg, klass_reg, klass, fail_1_bb, ok_result_bb);
4947
4948                 MONO_START_BB (cfg, fail_1_bb);
4949
4950                 MONO_EMIT_NEW_ICONST (cfg, dreg, 1);
4951                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4952
4953                 MONO_START_BB (cfg, no_proxy_bb);
4954
4955                 mini_emit_castclass (cfg, obj_reg, klass_reg, klass, ok_result_bb);
4956 #else
4957                 g_error ("Transparent proxy support is disabled while trying to JIT code that uses it");
4958 #endif
4959         }
4960
4961         MONO_START_BB (cfg, ok_result_bb);
4962
4963         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4964
4965 #ifndef DISABLE_REMOTING
4966         MONO_START_BB (cfg, end_bb);
4967 #endif
4968
4969         /* FIXME: */
4970         MONO_INST_NEW (cfg, ins, OP_ICONST);
4971         ins->dreg = dreg;
4972         ins->type = STACK_I4;
4973
4974         return ins;
4975 }
4976
4977 static G_GNUC_UNUSED MonoInst*
4978 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4979 {
4980         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4981         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4982         gboolean is_i4;
4983
4984         switch (enum_type->type) {
4985         case MONO_TYPE_I8:
4986         case MONO_TYPE_U8:
4987 #if SIZEOF_REGISTER == 8
4988         case MONO_TYPE_I:
4989         case MONO_TYPE_U:
4990 #endif
4991                 is_i4 = FALSE;
4992                 break;
4993         default:
4994                 is_i4 = TRUE;
4995                 break;
4996         }
4997
4998         {
4999                 MonoInst *load, *and_, *cmp, *ceq;
5000                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
5001                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
5002                 int dest_reg = alloc_ireg (cfg);
5003
5004                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
5005                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
5006                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
5007                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
5008
5009                 ceq->type = STACK_I4;
5010
5011                 if (!is_i4) {
5012                         load = mono_decompose_opcode (cfg, load);
5013                         and_ = mono_decompose_opcode (cfg, and_);
5014                         cmp = mono_decompose_opcode (cfg, cmp);
5015                         ceq = mono_decompose_opcode (cfg, ceq);
5016                 }
5017
5018                 return ceq;
5019         }
5020 }
5021
5022 /*
5023  * Returns NULL and set the cfg exception on error.
5024  */
5025 static G_GNUC_UNUSED MonoInst*
5026 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
5027 {
5028         MonoInst *ptr;
5029         int dreg;
5030         gpointer trampoline;
5031         MonoInst *obj, *method_ins, *tramp_ins;
5032         MonoDomain *domain;
5033         guint8 **code_slot;
5034
5035         if (virtual_ && !cfg->llvm_only) {
5036                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
5037                 g_assert (invoke);
5038
5039                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
5040                         return NULL;
5041         }
5042
5043         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
5044         if (!obj)
5045                 return NULL;
5046
5047         /* Inline the contents of mono_delegate_ctor */
5048
5049         /* Set target field */
5050         /* Optimize away setting of NULL target */
5051         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
5052                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
5053                 if (cfg->gen_write_barriers) {
5054                         dreg = alloc_preg (cfg);
5055                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
5056                         emit_write_barrier (cfg, ptr, target);
5057                 }
5058         }
5059
5060         /* Set method field */
5061         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
5062         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
5063
5064         /* 
5065          * To avoid looking up the compiled code belonging to the target method
5066          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
5067          * store it, and we fill it after the method has been compiled.
5068          */
5069         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
5070                 MonoInst *code_slot_ins;
5071
5072                 if (context_used) {
5073                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
5074                 } else {
5075                         domain = mono_domain_get ();
5076                         mono_domain_lock (domain);
5077                         if (!domain_jit_info (domain)->method_code_hash)
5078                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
5079                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
5080                         if (!code_slot) {
5081                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
5082                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
5083                         }
5084                         mono_domain_unlock (domain);
5085
5086                         code_slot_ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
5087                 }
5088                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
5089         }
5090
5091         if (cfg->llvm_only) {
5092                 MonoInst *args [16];
5093
5094                 if (virtual_) {
5095                         args [0] = obj;
5096                         args [1] = target;
5097                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
5098                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
5099                 } else {
5100                         args [0] = obj;
5101                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
5102                 }
5103
5104                 return obj;
5105         }
5106
5107         if (cfg->compile_aot) {
5108                 MonoDelegateClassMethodPair *del_tramp;
5109
5110                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
5111                 del_tramp->klass = klass;
5112                 del_tramp->method = context_used ? NULL : method;
5113                 del_tramp->is_virtual = virtual_;
5114                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
5115         } else {
5116                 if (virtual_)
5117                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
5118                 else
5119                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
5120                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
5121         }
5122
5123         /* Set invoke_impl field */
5124         if (virtual_) {
5125                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
5126         } else {
5127                 dreg = alloc_preg (cfg);
5128                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
5129                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
5130
5131                 dreg = alloc_preg (cfg);
5132                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
5133                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
5134         }
5135
5136         dreg = alloc_preg (cfg);
5137         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
5138         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
5139
5140         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
5141
5142         return obj;
5143 }
5144
5145 static MonoInst*
5146 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
5147 {
5148         MonoJitICallInfo *info;
5149
5150         /* Need to register the icall so it gets an icall wrapper */
5151         info = mono_get_array_new_va_icall (rank);
5152
5153         cfg->flags |= MONO_CFG_HAS_VARARGS;
5154
5155         /* mono_array_new_va () needs a vararg calling convention */
5156         cfg->exception_message = g_strdup ("array-new");
5157         cfg->disable_llvm = TRUE;
5158
5159         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
5160         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
5161 }
5162
5163 /*
5164  * handle_constrained_gsharedvt_call:
5165  *
5166  *   Handle constrained calls where the receiver is a gsharedvt type.
5167  * Return the instruction representing the call. Set the cfg exception on failure.
5168  */
5169 static MonoInst*
5170 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
5171                                                                    gboolean *ref_emit_widen)
5172 {
5173         MonoInst *ins = NULL;
5174         gboolean emit_widen = *ref_emit_widen;
5175
5176         /*
5177          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
5178          * This is hard to do with the current call code, since we would have to emit a branch and two different calls. So instead, we
5179          * pack the arguments into an array, and do the rest of the work in in an icall.
5180          */
5181         if (((cmethod->klass == mono_defaults.object_class) || (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
5182                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mini_is_gsharedvt_type (fsig->ret)) &&
5183                 (fsig->param_count == 0 || (!fsig->hasthis && fsig->param_count == 1) || (fsig->param_count == 1 && (MONO_TYPE_IS_REFERENCE (fsig->params [0]) || fsig->params [0]->byref || mini_is_gsharedvt_type (fsig->params [0]))))) {
5184                 MonoInst *args [16];
5185
5186                 /*
5187                  * This case handles calls to
5188                  * - object:ToString()/Equals()/GetHashCode(),
5189                  * - System.IComparable<T>:CompareTo()
5190                  * - System.IEquatable<T>:Equals ()
5191                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
5192                  */
5193
5194                 args [0] = sp [0];
5195                 if (mono_method_check_context_used (cmethod))
5196                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
5197                 else
5198                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
5199                 args [2] = emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
5200
5201                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
5202                 if (fsig->hasthis && fsig->param_count) {
5203                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
5204                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
5205                         ins->dreg = alloc_preg (cfg);
5206                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
5207                         MONO_ADD_INS (cfg->cbb, ins);
5208                         args [4] = ins;
5209
5210                         if (mini_is_gsharedvt_type (fsig->params [0])) {
5211                                 int addr_reg, deref_arg_reg;
5212
5213                                 ins = emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
5214                                 deref_arg_reg = alloc_preg (cfg);
5215                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
5216                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
5217
5218                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
5219                                 addr_reg = ins->dreg;
5220                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
5221                         } else {
5222                                 EMIT_NEW_ICONST (cfg, args [3], 0);
5223                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
5224                         }
5225                 } else {
5226                         EMIT_NEW_ICONST (cfg, args [3], 0);
5227                         EMIT_NEW_ICONST (cfg, args [4], 0);
5228                 }
5229                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
5230                 emit_widen = FALSE;
5231
5232                 if (mini_is_gsharedvt_type (fsig->ret)) {
5233                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
5234                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret)) {
5235                         MonoInst *add;
5236
5237                         /* Unbox */
5238                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
5239                         MONO_ADD_INS (cfg->cbb, add);
5240                         /* Load value */
5241                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
5242                         MONO_ADD_INS (cfg->cbb, ins);
5243                         /* ins represents the call result */
5244                 }
5245         } else {
5246                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
5247         }
5248
5249         *ref_emit_widen = emit_widen;
5250
5251         return ins;
5252
5253  exception_exit:
5254         return NULL;
5255 }
5256
5257 static void
5258 mono_emit_load_got_addr (MonoCompile *cfg)
5259 {
5260         MonoInst *getaddr, *dummy_use;
5261
5262         if (!cfg->got_var || cfg->got_var_allocated)
5263                 return;
5264
5265         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
5266         getaddr->cil_code = cfg->header->code;
5267         getaddr->dreg = cfg->got_var->dreg;
5268
5269         /* Add it to the start of the first bblock */
5270         if (cfg->bb_entry->code) {
5271                 getaddr->next = cfg->bb_entry->code;
5272                 cfg->bb_entry->code = getaddr;
5273         }
5274         else
5275                 MONO_ADD_INS (cfg->bb_entry, getaddr);
5276
5277         cfg->got_var_allocated = TRUE;
5278
5279         /* 
5280          * Add a dummy use to keep the got_var alive, since real uses might
5281          * only be generated by the back ends.
5282          * Add it to end_bblock, so the variable's lifetime covers the whole
5283          * method.
5284          * It would be better to make the usage of the got var explicit in all
5285          * cases when the backend needs it (i.e. calls, throw etc.), so this
5286          * wouldn't be needed.
5287          */
5288         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
5289         MONO_ADD_INS (cfg->bb_exit, dummy_use);
5290 }
5291
5292 static int inline_limit;
5293 static gboolean inline_limit_inited;
5294
5295 static gboolean
5296 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
5297 {
5298         MonoMethodHeaderSummary header;
5299         MonoVTable *vtable;
5300 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
5301         MonoMethodSignature *sig = mono_method_signature (method);
5302         int i;
5303 #endif
5304
5305         if (cfg->disable_inline)
5306                 return FALSE;
5307         if (cfg->gshared)
5308                 return FALSE;
5309
5310         if (cfg->inline_depth > 10)
5311                 return FALSE;
5312
5313         if (!mono_method_get_header_summary (method, &header))
5314                 return FALSE;
5315
5316         /*runtime, icall and pinvoke are checked by summary call*/
5317         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
5318             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
5319             (mono_class_is_marshalbyref (method->klass)) ||
5320             header.has_clauses)
5321                 return FALSE;
5322
5323         /* also consider num_locals? */
5324         /* Do the size check early to avoid creating vtables */
5325         if (!inline_limit_inited) {
5326                 if (g_getenv ("MONO_INLINELIMIT"))
5327                         inline_limit = atoi (g_getenv ("MONO_INLINELIMIT"));
5328                 else
5329                         inline_limit = INLINE_LENGTH_LIMIT;
5330                 inline_limit_inited = TRUE;
5331         }
5332         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
5333                 return FALSE;
5334
5335         /*
5336          * if we can initialize the class of the method right away, we do,
5337          * otherwise we don't allow inlining if the class needs initialization,
5338          * since it would mean inserting a call to mono_runtime_class_init()
5339          * inside the inlined code
5340          */
5341         if (!(cfg->opt & MONO_OPT_SHARED)) {
5342                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
5343                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
5344                         vtable = mono_class_vtable (cfg->domain, method->klass);
5345                         if (!vtable)
5346                                 return FALSE;
5347                         if (!cfg->compile_aot) {
5348                                 MonoError error;
5349                                 if (!mono_runtime_class_init_full (vtable, &error)) {
5350                                         mono_error_cleanup (&error);
5351                                         return FALSE;
5352                                 }
5353                         }
5354                 } else if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
5355                         if (cfg->run_cctors && method->klass->has_cctor) {
5356                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
5357                                 if (!method->klass->runtime_info)
5358                                         /* No vtable created yet */
5359                                         return FALSE;
5360                                 vtable = mono_class_vtable (cfg->domain, method->klass);
5361                                 if (!vtable)
5362                                         return FALSE;
5363                                 /* This makes so that inline cannot trigger */
5364                                 /* .cctors: too many apps depend on them */
5365                                 /* running with a specific order... */
5366                                 if (! vtable->initialized)
5367                                         return FALSE;
5368                                 MonoError error;
5369                                 if (!mono_runtime_class_init_full (vtable, &error)) {
5370                                         mono_error_cleanup (&error);
5371                                         return FALSE;
5372                                 }
5373                         }
5374                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
5375                         if (!method->klass->runtime_info)
5376                                 /* No vtable created yet */
5377                                 return FALSE;
5378                         vtable = mono_class_vtable (cfg->domain, method->klass);
5379                         if (!vtable)
5380                                 return FALSE;
5381                         if (!vtable->initialized)
5382                                 return FALSE;
5383                 }
5384         } else {
5385                 /* 
5386                  * If we're compiling for shared code
5387                  * the cctor will need to be run at aot method load time, for example,
5388                  * or at the end of the compilation of the inlining method.
5389                  */
5390                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5391                         return FALSE;
5392         }
5393
5394 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
5395         if (mono_arch_is_soft_float ()) {
5396                 /* FIXME: */
5397                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
5398                         return FALSE;
5399                 for (i = 0; i < sig->param_count; ++i)
5400                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
5401                                 return FALSE;
5402         }
5403 #endif
5404
5405         if (g_list_find (cfg->dont_inline, method))
5406                 return FALSE;
5407
5408         return TRUE;
5409 }
5410
5411 static gboolean
5412 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
5413 {
5414         if (!cfg->compile_aot) {
5415                 g_assert (vtable);
5416                 if (vtable->initialized)
5417                         return FALSE;
5418         }
5419
5420         if (klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
5421                 if (cfg->method == method)
5422                         return FALSE;
5423         }
5424
5425         if (!mono_class_needs_cctor_run (klass, method))
5426                 return FALSE;
5427
5428         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
5429                 /* The initialization is already done before the method is called */
5430                 return FALSE;
5431
5432         return TRUE;
5433 }
5434
5435 static MonoInst*
5436 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
5437 {
5438         MonoInst *ins;
5439         guint32 size;
5440         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
5441         int context_used;
5442
5443         if (mini_is_gsharedvt_variable_klass (klass)) {
5444                 size = -1;
5445         } else {
5446                 mono_class_init (klass);
5447                 size = mono_class_array_element_size (klass);
5448         }
5449
5450         mult_reg = alloc_preg (cfg);
5451         array_reg = arr->dreg;
5452         index_reg = index->dreg;
5453
5454 #if SIZEOF_REGISTER == 8
5455         /* The array reg is 64 bits but the index reg is only 32 */
5456         if (COMPILE_LLVM (cfg)) {
5457                 /* Not needed */
5458                 index2_reg = index_reg;
5459         } else {
5460                 index2_reg = alloc_preg (cfg);
5461                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
5462         }
5463 #else
5464         if (index->type == STACK_I8) {
5465                 index2_reg = alloc_preg (cfg);
5466                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
5467         } else {
5468                 index2_reg = index_reg;
5469         }
5470 #endif
5471
5472         if (bcheck)
5473                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
5474
5475 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5476         if (size == 1 || size == 2 || size == 4 || size == 8) {
5477                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
5478
5479                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
5480                 ins->klass = mono_class_get_element_class (klass);
5481                 ins->type = STACK_MP;
5482
5483                 return ins;
5484         }
5485 #endif          
5486
5487         add_reg = alloc_ireg_mp (cfg);
5488
5489         if (size == -1) {
5490                 MonoInst *rgctx_ins;
5491
5492                 /* gsharedvt */
5493                 g_assert (cfg->gshared);
5494                 context_used = mini_class_check_context_used (cfg, klass);
5495                 g_assert (context_used);
5496                 rgctx_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
5497                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
5498         } else {
5499                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
5500         }
5501         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
5502         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
5503         ins->klass = mono_class_get_element_class (klass);
5504         ins->type = STACK_MP;
5505         MONO_ADD_INS (cfg->cbb, ins);
5506
5507         return ins;
5508 }
5509
5510 static MonoInst*
5511 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
5512 {
5513         int bounds_reg = alloc_preg (cfg);
5514         int add_reg = alloc_ireg_mp (cfg);
5515         int mult_reg = alloc_preg (cfg);
5516         int mult2_reg = alloc_preg (cfg);
5517         int low1_reg = alloc_preg (cfg);
5518         int low2_reg = alloc_preg (cfg);
5519         int high1_reg = alloc_preg (cfg);
5520         int high2_reg = alloc_preg (cfg);
5521         int realidx1_reg = alloc_preg (cfg);
5522         int realidx2_reg = alloc_preg (cfg);
5523         int sum_reg = alloc_preg (cfg);
5524         int index1, index2, tmpreg;
5525         MonoInst *ins;
5526         guint32 size;
5527
5528         mono_class_init (klass);
5529         size = mono_class_array_element_size (klass);
5530
5531         index1 = index_ins1->dreg;
5532         index2 = index_ins2->dreg;
5533
5534 #if SIZEOF_REGISTER == 8
5535         /* The array reg is 64 bits but the index reg is only 32 */
5536         if (COMPILE_LLVM (cfg)) {
5537                 /* Not needed */
5538         } else {
5539                 tmpreg = alloc_preg (cfg);
5540                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
5541                 index1 = tmpreg;
5542                 tmpreg = alloc_preg (cfg);
5543                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
5544                 index2 = tmpreg;
5545         }
5546 #else
5547         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
5548         tmpreg = -1;
5549 #endif
5550
5551         /* range checking */
5552         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
5553                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5554
5555         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
5556                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5557         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
5558         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
5559                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5560         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
5561         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
5562
5563         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
5564                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5565         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
5566         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
5567                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5568         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
5569         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
5570
5571         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
5572         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
5573         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
5574         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
5575         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
5576
5577         ins->type = STACK_MP;
5578         ins->klass = klass;
5579         MONO_ADD_INS (cfg->cbb, ins);
5580
5581         return ins;
5582 }
5583
5584 static MonoInst*
5585 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
5586 {
5587         int rank;
5588         MonoInst *addr;
5589         MonoMethod *addr_method;
5590         int element_size;
5591         MonoClass *eclass = cmethod->klass->element_class;
5592
5593         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
5594
5595         if (rank == 1)
5596                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
5597
5598         /* emit_ldelema_2 depends on OP_LMUL */
5599         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
5600                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
5601         }
5602
5603         if (mini_is_gsharedvt_variable_klass (eclass))
5604                 element_size = 0;
5605         else
5606                 element_size = mono_class_array_element_size (eclass);
5607         addr_method = mono_marshal_get_array_address (rank, element_size);
5608         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
5609
5610         return addr;
5611 }
5612
5613 static MonoBreakPolicy
5614 always_insert_breakpoint (MonoMethod *method)
5615 {
5616         return MONO_BREAK_POLICY_ALWAYS;
5617 }
5618
5619 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
5620
5621 /**
5622  * mono_set_break_policy:
5623  * policy_callback: the new callback function
5624  *
5625  * Allow embedders to decide wherther to actually obey breakpoint instructions
5626  * (both break IL instructions and Debugger.Break () method calls), for example
5627  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
5628  * untrusted or semi-trusted code.
5629  *
5630  * @policy_callback will be called every time a break point instruction needs to
5631  * be inserted with the method argument being the method that calls Debugger.Break()
5632  * or has the IL break instruction. The callback should return #MONO_BREAK_POLICY_NEVER
5633  * if it wants the breakpoint to not be effective in the given method.
5634  * #MONO_BREAK_POLICY_ALWAYS is the default.
5635  */
5636 void
5637 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
5638 {
5639         if (policy_callback)
5640                 break_policy_func = policy_callback;
5641         else
5642                 break_policy_func = always_insert_breakpoint;
5643 }
5644
5645 static gboolean
5646 should_insert_brekpoint (MonoMethod *method) {
5647         switch (break_policy_func (method)) {
5648         case MONO_BREAK_POLICY_ALWAYS:
5649                 return TRUE;
5650         case MONO_BREAK_POLICY_NEVER:
5651                 return FALSE;
5652         case MONO_BREAK_POLICY_ON_DBG:
5653                 g_warning ("mdb no longer supported");
5654                 return FALSE;
5655         default:
5656                 g_warning ("Incorrect value returned from break policy callback");
5657                 return FALSE;
5658         }
5659 }
5660
5661 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
5662 static MonoInst*
5663 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5664 {
5665         MonoInst *addr, *store, *load;
5666         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
5667
5668         /* the bounds check is already done by the callers */
5669         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5670         if (is_set) {
5671                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
5672                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
5673                 if (mini_type_is_reference (fsig->params [2]))
5674                         emit_write_barrier (cfg, addr, load);
5675         } else {
5676                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
5677                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
5678         }
5679         return store;
5680 }
5681
5682
5683 static gboolean
5684 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
5685 {
5686         return mini_type_is_reference (&klass->byval_arg);
5687 }
5688
5689 static MonoInst*
5690 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
5691 {
5692         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
5693                 !(sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL)) {
5694                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
5695                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
5696                 MonoInst *iargs [3];
5697
5698                 if (!helper->slot)
5699                         mono_class_setup_vtable (obj_array);
5700                 g_assert (helper->slot);
5701
5702                 if (sp [0]->type != STACK_OBJ)
5703                         return NULL;
5704                 if (sp [2]->type != STACK_OBJ)
5705                         return NULL;
5706
5707                 iargs [2] = sp [2];
5708                 iargs [1] = sp [1];
5709                 iargs [0] = sp [0];
5710
5711                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
5712         } else {
5713                 MonoInst *ins;
5714
5715                 if (mini_is_gsharedvt_variable_klass (klass)) {
5716                         MonoInst *addr;
5717
5718                         // FIXME-VT: OP_ICONST optimization
5719                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
5720                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5721                         ins->opcode = OP_STOREV_MEMBASE;
5722                 } else if (sp [1]->opcode == OP_ICONST) {
5723                         int array_reg = sp [0]->dreg;
5724                         int index_reg = sp [1]->dreg;
5725                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
5726
5727                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
5728                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
5729
5730                         if (safety_checks)
5731                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
5732                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
5733                 } else {
5734                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
5735                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5736                         if (generic_class_is_reference_type (cfg, klass))
5737                                 emit_write_barrier (cfg, addr, sp [2]);
5738                 }
5739                 return ins;
5740         }
5741 }
5742
5743 static MonoInst*
5744 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5745 {
5746         MonoClass *eklass;
5747         
5748         if (is_set)
5749                 eklass = mono_class_from_mono_type (fsig->params [2]);
5750         else
5751                 eklass = mono_class_from_mono_type (fsig->ret);
5752
5753         if (is_set) {
5754                 return emit_array_store (cfg, eklass, args, FALSE);
5755         } else {
5756                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5757                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
5758                 return ins;
5759         }
5760 }
5761
5762 static gboolean
5763 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
5764 {
5765         uint32_t align;
5766         int param_size, return_size;
5767
5768         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
5769         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
5770
5771         if (cfg->verbose_level > 3)
5772                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
5773
5774         //Don't allow mixing reference types with value types
5775         if (param_klass->valuetype != return_klass->valuetype) {
5776                 if (cfg->verbose_level > 3)
5777                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
5778                 return FALSE;
5779         }
5780
5781         if (!param_klass->valuetype) {
5782                 if (cfg->verbose_level > 3)
5783                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
5784                 return TRUE;
5785         }
5786
5787         //That are blitable
5788         if (param_klass->has_references || return_klass->has_references)
5789                 return FALSE;
5790
5791         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
5792         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
5793                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
5794                         if (cfg->verbose_level > 3)
5795                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
5796                 return FALSE;
5797         }
5798
5799         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
5800                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
5801                 if (cfg->verbose_level > 3)
5802                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
5803                 return FALSE;
5804         }
5805
5806         param_size = mono_class_value_size (param_klass, &align);
5807         return_size = mono_class_value_size (return_klass, &align);
5808
5809         //We can do it if sizes match
5810         if (param_size == return_size) {
5811                 if (cfg->verbose_level > 3)
5812                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
5813                 return TRUE;
5814         }
5815
5816         //No simple way to handle struct if sizes don't match
5817         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
5818                 if (cfg->verbose_level > 3)
5819                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
5820                 return FALSE;
5821         }
5822
5823         /*
5824          * Same reg size category.
5825          * A quick note on why we don't require widening here.
5826          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
5827          *
5828          * Since the source value comes from a function argument, the JIT will already have
5829          * the value in a VREG and performed any widening needed before (say, when loading from a field).
5830          */
5831         if (param_size <= 4 && return_size <= 4) {
5832                 if (cfg->verbose_level > 3)
5833                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
5834                 return TRUE;
5835         }
5836
5837         return FALSE;
5838 }
5839
5840 static MonoInst*
5841 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
5842 {
5843         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
5844         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
5845
5846         if (mini_is_gsharedvt_variable_type (fsig->ret))
5847                 return NULL;
5848
5849         //Valuetypes that are semantically equivalent or numbers than can be widened to
5850         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5851                 return args [0];
5852
5853         //Arrays of valuetypes that are semantically equivalent
5854         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5855                 return args [0];
5856
5857         return NULL;
5858 }
5859
5860 static MonoInst*
5861 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5862 {
5863 #ifdef MONO_ARCH_SIMD_INTRINSICS
5864         MonoInst *ins = NULL;
5865
5866         if (cfg->opt & MONO_OPT_SIMD) {
5867                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5868                 if (ins)
5869                         return ins;
5870         }
5871 #endif
5872
5873         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5874 }
5875
5876 static MonoInst*
5877 emit_memory_barrier (MonoCompile *cfg, int kind)
5878 {
5879         MonoInst *ins = NULL;
5880         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5881         MONO_ADD_INS (cfg->cbb, ins);
5882         ins->backend.memory_barrier_kind = kind;
5883
5884         return ins;
5885 }
5886
5887 static MonoInst*
5888 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5889 {
5890         MonoInst *ins = NULL;
5891         int opcode = 0;
5892
5893         /* The LLVM backend supports these intrinsics */
5894         if (cmethod->klass == mono_defaults.math_class) {
5895                 if (strcmp (cmethod->name, "Sin") == 0) {
5896                         opcode = OP_SIN;
5897                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5898                         opcode = OP_COS;
5899                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5900                         opcode = OP_SQRT;
5901                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5902                         opcode = OP_ABS;
5903                 }
5904
5905                 if (opcode && fsig->param_count == 1) {
5906                         MONO_INST_NEW (cfg, ins, opcode);
5907                         ins->type = STACK_R8;
5908                         ins->dreg = mono_alloc_freg (cfg);
5909                         ins->sreg1 = args [0]->dreg;
5910                         MONO_ADD_INS (cfg->cbb, ins);
5911                 }
5912
5913                 opcode = 0;
5914                 if (cfg->opt & MONO_OPT_CMOV) {
5915                         if (strcmp (cmethod->name, "Min") == 0) {
5916                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5917                                         opcode = OP_IMIN;
5918                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5919                                         opcode = OP_IMIN_UN;
5920                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5921                                         opcode = OP_LMIN;
5922                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5923                                         opcode = OP_LMIN_UN;
5924                         } else if (strcmp (cmethod->name, "Max") == 0) {
5925                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5926                                         opcode = OP_IMAX;
5927                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5928                                         opcode = OP_IMAX_UN;
5929                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5930                                         opcode = OP_LMAX;
5931                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5932                                         opcode = OP_LMAX_UN;
5933                         }
5934                 }
5935
5936                 if (opcode && fsig->param_count == 2) {
5937                         MONO_INST_NEW (cfg, ins, opcode);
5938                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5939                         ins->dreg = mono_alloc_ireg (cfg);
5940                         ins->sreg1 = args [0]->dreg;
5941                         ins->sreg2 = args [1]->dreg;
5942                         MONO_ADD_INS (cfg->cbb, ins);
5943                 }
5944         }
5945
5946         return ins;
5947 }
5948
5949 static MonoInst*
5950 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5951 {
5952         if (cmethod->klass == mono_defaults.array_class) {
5953                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5954                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5955                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5956                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5957                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5958                         return emit_array_unsafe_mov (cfg, fsig, args);
5959         }
5960
5961         return NULL;
5962 }
5963
5964 static MonoInst*
5965 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5966 {
5967         MonoInst *ins = NULL;
5968
5969          MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5970
5971         if (cmethod->klass == mono_defaults.string_class) {
5972                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5973                         int dreg = alloc_ireg (cfg);
5974                         int index_reg = alloc_preg (cfg);
5975                         int add_reg = alloc_preg (cfg);
5976
5977 #if SIZEOF_REGISTER == 8
5978                         if (COMPILE_LLVM (cfg)) {
5979                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5980                         } else {
5981                                 /* The array reg is 64 bits but the index reg is only 32 */
5982                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5983                         }
5984 #else
5985                         index_reg = args [1]->dreg;
5986 #endif  
5987                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5988
5989 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5990                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5991                         add_reg = ins->dreg;
5992                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5993                                                                    add_reg, 0);
5994 #else
5995                         int mult_reg = alloc_preg (cfg);
5996                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5997                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5998                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5999                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
6000 #endif
6001                         type_from_op (cfg, ins, NULL, NULL);
6002                         return ins;
6003                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
6004                         int dreg = alloc_ireg (cfg);
6005                         /* Decompose later to allow more optimizations */
6006                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
6007                         ins->type = STACK_I4;
6008                         ins->flags |= MONO_INST_FAULT;
6009                         cfg->cbb->has_array_access = TRUE;
6010                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
6011
6012                         return ins;
6013                 } else 
6014                         return NULL;
6015         } else if (cmethod->klass == mono_defaults.object_class) {
6016                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
6017                         int dreg = alloc_ireg_ref (cfg);
6018                         int vt_reg = alloc_preg (cfg);
6019                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6020                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
6021                         type_from_op (cfg, ins, NULL, NULL);
6022
6023                         return ins;
6024                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
6025                         int dreg = alloc_ireg (cfg);
6026                         int t1 = alloc_ireg (cfg);
6027         
6028                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
6029                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
6030                         ins->type = STACK_I4;
6031
6032                         return ins;
6033                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
6034                         MONO_INST_NEW (cfg, ins, OP_NOP);
6035                         MONO_ADD_INS (cfg->cbb, ins);
6036                         return ins;
6037                 } else
6038                         return NULL;
6039         } else if (cmethod->klass == mono_defaults.array_class) {
6040                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
6041                         return emit_array_generic_access (cfg, fsig, args, FALSE);
6042                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
6043                         return emit_array_generic_access (cfg, fsig, args, TRUE);
6044
6045 #ifndef MONO_BIG_ARRAYS
6046                 /*
6047                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
6048                  * Array methods.
6049                  */
6050                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
6051                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
6052                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
6053                         int dreg = alloc_ireg (cfg);
6054                         int bounds_reg = alloc_ireg_mp (cfg);
6055                         MonoBasicBlock *end_bb, *szarray_bb;
6056                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
6057
6058                         NEW_BBLOCK (cfg, end_bb);
6059                         NEW_BBLOCK (cfg, szarray_bb);
6060
6061                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
6062                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
6063                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
6064                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
6065                         /* Non-szarray case */
6066                         if (get_length)
6067                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6068                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
6069                         else
6070                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6071                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
6072                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6073                         MONO_START_BB (cfg, szarray_bb);
6074                         /* Szarray case */
6075                         if (get_length)
6076                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
6077                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
6078                         else
6079                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6080                         MONO_START_BB (cfg, end_bb);
6081
6082                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
6083                         ins->type = STACK_I4;
6084                         
6085                         return ins;
6086                 }
6087 #endif
6088
6089                 if (cmethod->name [0] != 'g')
6090                         return NULL;
6091
6092                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
6093                         int dreg = alloc_ireg (cfg);
6094                         int vtable_reg = alloc_preg (cfg);
6095                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
6096                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6097                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
6098                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
6099                         type_from_op (cfg, ins, NULL, NULL);
6100
6101                         return ins;
6102                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
6103                         int dreg = alloc_ireg (cfg);
6104
6105                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
6106                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
6107                         type_from_op (cfg, ins, NULL, NULL);
6108
6109                         return ins;
6110                 } else
6111                         return NULL;
6112         } else if (cmethod->klass == runtime_helpers_class) {
6113                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
6114                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
6115                         return ins;
6116                 } else
6117                         return NULL;
6118         } else if (cmethod->klass == mono_defaults.monitor_class) {
6119                 gboolean is_enter = FALSE;
6120
6121                 if (!strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1)
6122                         is_enter = TRUE;
6123
6124                 if (is_enter) {
6125                         /*
6126                          * To make async stack traces work, icalls which can block should have a wrapper.
6127                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
6128                          */
6129                         MonoBasicBlock *end_bb;
6130
6131                         NEW_BBLOCK (cfg, end_bb);
6132
6133                         ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter_fast, args);
6134                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
6135                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
6136                         ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter, args);
6137                         MONO_START_BB (cfg, end_bb);
6138                         return ins;
6139                 }
6140         } else if (cmethod->klass == mono_defaults.thread_class) {
6141                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
6142                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
6143                         MONO_ADD_INS (cfg->cbb, ins);
6144                         return ins;
6145                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
6146                         return emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6147                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
6148                         guint32 opcode = 0;
6149                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6150
6151                         if (fsig->params [0]->type == MONO_TYPE_I1)
6152                                 opcode = OP_LOADI1_MEMBASE;
6153                         else if (fsig->params [0]->type == MONO_TYPE_U1)
6154                                 opcode = OP_LOADU1_MEMBASE;
6155                         else if (fsig->params [0]->type == MONO_TYPE_I2)
6156                                 opcode = OP_LOADI2_MEMBASE;
6157                         else if (fsig->params [0]->type == MONO_TYPE_U2)
6158                                 opcode = OP_LOADU2_MEMBASE;
6159                         else if (fsig->params [0]->type == MONO_TYPE_I4)
6160                                 opcode = OP_LOADI4_MEMBASE;
6161                         else if (fsig->params [0]->type == MONO_TYPE_U4)
6162                                 opcode = OP_LOADU4_MEMBASE;
6163                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
6164                                 opcode = OP_LOADI8_MEMBASE;
6165                         else if (fsig->params [0]->type == MONO_TYPE_R4)
6166                                 opcode = OP_LOADR4_MEMBASE;
6167                         else if (fsig->params [0]->type == MONO_TYPE_R8)
6168                                 opcode = OP_LOADR8_MEMBASE;
6169                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
6170                                 opcode = OP_LOAD_MEMBASE;
6171
6172                         if (opcode) {
6173                                 MONO_INST_NEW (cfg, ins, opcode);
6174                                 ins->inst_basereg = args [0]->dreg;
6175                                 ins->inst_offset = 0;
6176                                 MONO_ADD_INS (cfg->cbb, ins);
6177
6178                                 switch (fsig->params [0]->type) {
6179                                 case MONO_TYPE_I1:
6180                                 case MONO_TYPE_U1:
6181                                 case MONO_TYPE_I2:
6182                                 case MONO_TYPE_U2:
6183                                 case MONO_TYPE_I4:
6184                                 case MONO_TYPE_U4:
6185                                         ins->dreg = mono_alloc_ireg (cfg);
6186                                         ins->type = STACK_I4;
6187                                         break;
6188                                 case MONO_TYPE_I8:
6189                                 case MONO_TYPE_U8:
6190                                         ins->dreg = mono_alloc_lreg (cfg);
6191                                         ins->type = STACK_I8;
6192                                         break;
6193                                 case MONO_TYPE_I:
6194                                 case MONO_TYPE_U:
6195                                         ins->dreg = mono_alloc_ireg (cfg);
6196 #if SIZEOF_REGISTER == 8
6197                                         ins->type = STACK_I8;
6198 #else
6199                                         ins->type = STACK_I4;
6200 #endif
6201                                         break;
6202                                 case MONO_TYPE_R4:
6203                                 case MONO_TYPE_R8:
6204                                         ins->dreg = mono_alloc_freg (cfg);
6205                                         ins->type = STACK_R8;
6206                                         break;
6207                                 default:
6208                                         g_assert (mini_type_is_reference (fsig->params [0]));
6209                                         ins->dreg = mono_alloc_ireg_ref (cfg);
6210                                         ins->type = STACK_OBJ;
6211                                         break;
6212                                 }
6213
6214                                 if (opcode == OP_LOADI8_MEMBASE)
6215                                         ins = mono_decompose_opcode (cfg, ins);
6216
6217                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6218
6219                                 return ins;
6220                         }
6221                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
6222                         guint32 opcode = 0;
6223                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6224
6225                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
6226                                 opcode = OP_STOREI1_MEMBASE_REG;
6227                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
6228                                 opcode = OP_STOREI2_MEMBASE_REG;
6229                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
6230                                 opcode = OP_STOREI4_MEMBASE_REG;
6231                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
6232                                 opcode = OP_STOREI8_MEMBASE_REG;
6233                         else if (fsig->params [0]->type == MONO_TYPE_R4)
6234                                 opcode = OP_STORER4_MEMBASE_REG;
6235                         else if (fsig->params [0]->type == MONO_TYPE_R8)
6236                                 opcode = OP_STORER8_MEMBASE_REG;
6237                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
6238                                 opcode = OP_STORE_MEMBASE_REG;
6239
6240                         if (opcode) {
6241                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6242
6243                                 MONO_INST_NEW (cfg, ins, opcode);
6244                                 ins->sreg1 = args [1]->dreg;
6245                                 ins->inst_destbasereg = args [0]->dreg;
6246                                 ins->inst_offset = 0;
6247                                 MONO_ADD_INS (cfg->cbb, ins);
6248
6249                                 if (opcode == OP_STOREI8_MEMBASE_REG)
6250                                         ins = mono_decompose_opcode (cfg, ins);
6251
6252                                 return ins;
6253                         }
6254                 }
6255         } else if (cmethod->klass->image == mono_defaults.corlib &&
6256                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
6257                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
6258                 ins = NULL;
6259
6260 #if SIZEOF_REGISTER == 8
6261                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
6262                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
6263                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
6264                                 ins->dreg = mono_alloc_preg (cfg);
6265                                 ins->sreg1 = args [0]->dreg;
6266                                 ins->type = STACK_I8;
6267                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
6268                                 MONO_ADD_INS (cfg->cbb, ins);
6269                         } else {
6270                                 MonoInst *load_ins;
6271
6272                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6273
6274                                 /* 64 bit reads are already atomic */
6275                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
6276                                 load_ins->dreg = mono_alloc_preg (cfg);
6277                                 load_ins->inst_basereg = args [0]->dreg;
6278                                 load_ins->inst_offset = 0;
6279                                 load_ins->type = STACK_I8;
6280                                 MONO_ADD_INS (cfg->cbb, load_ins);
6281
6282                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6283
6284                                 ins = load_ins;
6285                         }
6286                 }
6287 #endif
6288
6289                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
6290                         MonoInst *ins_iconst;
6291                         guint32 opcode = 0;
6292
6293                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6294                                 opcode = OP_ATOMIC_ADD_I4;
6295                                 cfg->has_atomic_add_i4 = TRUE;
6296                         }
6297 #if SIZEOF_REGISTER == 8
6298                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6299                                 opcode = OP_ATOMIC_ADD_I8;
6300 #endif
6301                         if (opcode) {
6302                                 if (!mono_arch_opcode_supported (opcode))
6303                                         return NULL;
6304                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
6305                                 ins_iconst->inst_c0 = 1;
6306                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
6307                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
6308
6309                                 MONO_INST_NEW (cfg, ins, opcode);
6310                                 ins->dreg = mono_alloc_ireg (cfg);
6311                                 ins->inst_basereg = args [0]->dreg;
6312                                 ins->inst_offset = 0;
6313                                 ins->sreg2 = ins_iconst->dreg;
6314                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6315                                 MONO_ADD_INS (cfg->cbb, ins);
6316                         }
6317                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
6318                         MonoInst *ins_iconst;
6319                         guint32 opcode = 0;
6320
6321                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6322                                 opcode = OP_ATOMIC_ADD_I4;
6323                                 cfg->has_atomic_add_i4 = TRUE;
6324                         }
6325 #if SIZEOF_REGISTER == 8
6326                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6327                                 opcode = OP_ATOMIC_ADD_I8;
6328 #endif
6329                         if (opcode) {
6330                                 if (!mono_arch_opcode_supported (opcode))
6331                                         return NULL;
6332                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
6333                                 ins_iconst->inst_c0 = -1;
6334                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
6335                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
6336
6337                                 MONO_INST_NEW (cfg, ins, opcode);
6338                                 ins->dreg = mono_alloc_ireg (cfg);
6339                                 ins->inst_basereg = args [0]->dreg;
6340                                 ins->inst_offset = 0;
6341                                 ins->sreg2 = ins_iconst->dreg;
6342                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6343                                 MONO_ADD_INS (cfg->cbb, ins);
6344                         }
6345                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
6346                         guint32 opcode = 0;
6347
6348                         if (fsig->params [0]->type == MONO_TYPE_I4) {
6349                                 opcode = OP_ATOMIC_ADD_I4;
6350                                 cfg->has_atomic_add_i4 = TRUE;
6351                         }
6352 #if SIZEOF_REGISTER == 8
6353                         else if (fsig->params [0]->type == MONO_TYPE_I8)
6354                                 opcode = OP_ATOMIC_ADD_I8;
6355 #endif
6356                         if (opcode) {
6357                                 if (!mono_arch_opcode_supported (opcode))
6358                                         return NULL;
6359                                 MONO_INST_NEW (cfg, ins, opcode);
6360                                 ins->dreg = mono_alloc_ireg (cfg);
6361                                 ins->inst_basereg = args [0]->dreg;
6362                                 ins->inst_offset = 0;
6363                                 ins->sreg2 = args [1]->dreg;
6364                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
6365                                 MONO_ADD_INS (cfg->cbb, ins);
6366                         }
6367                 }
6368                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
6369                         MonoInst *f2i = NULL, *i2f;
6370                         guint32 opcode, f2i_opcode, i2f_opcode;
6371                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
6372                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
6373
6374                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
6375                             fsig->params [0]->type == MONO_TYPE_R4) {
6376                                 opcode = OP_ATOMIC_EXCHANGE_I4;
6377                                 f2i_opcode = OP_MOVE_F_TO_I4;
6378                                 i2f_opcode = OP_MOVE_I4_TO_F;
6379                                 cfg->has_atomic_exchange_i4 = TRUE;
6380                         }
6381 #if SIZEOF_REGISTER == 8
6382                         else if (is_ref ||
6383                                  fsig->params [0]->type == MONO_TYPE_I8 ||
6384                                  fsig->params [0]->type == MONO_TYPE_R8 ||
6385                                  fsig->params [0]->type == MONO_TYPE_I) {
6386                                 opcode = OP_ATOMIC_EXCHANGE_I8;
6387                                 f2i_opcode = OP_MOVE_F_TO_I8;
6388                                 i2f_opcode = OP_MOVE_I8_TO_F;
6389                         }
6390 #else
6391                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
6392                                 opcode = OP_ATOMIC_EXCHANGE_I4;
6393                                 cfg->has_atomic_exchange_i4 = TRUE;
6394                         }
6395 #endif
6396                         else
6397                                 return NULL;
6398
6399                         if (!mono_arch_opcode_supported (opcode))
6400                                 return NULL;
6401
6402                         if (is_float) {
6403                                 /* TODO: Decompose these opcodes instead of bailing here. */
6404                                 if (COMPILE_SOFT_FLOAT (cfg))
6405                                         return NULL;
6406
6407                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
6408                                 f2i->dreg = mono_alloc_ireg (cfg);
6409                                 f2i->sreg1 = args [1]->dreg;
6410                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6411                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6412                                 MONO_ADD_INS (cfg->cbb, f2i);
6413                         }
6414
6415                         MONO_INST_NEW (cfg, ins, opcode);
6416                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
6417                         ins->inst_basereg = args [0]->dreg;
6418                         ins->inst_offset = 0;
6419                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
6420                         MONO_ADD_INS (cfg->cbb, ins);
6421
6422                         switch (fsig->params [0]->type) {
6423                         case MONO_TYPE_I4:
6424                                 ins->type = STACK_I4;
6425                                 break;
6426                         case MONO_TYPE_I8:
6427                                 ins->type = STACK_I8;
6428                                 break;
6429                         case MONO_TYPE_I:
6430 #if SIZEOF_REGISTER == 8
6431                                 ins->type = STACK_I8;
6432 #else
6433                                 ins->type = STACK_I4;
6434 #endif
6435                                 break;
6436                         case MONO_TYPE_R4:
6437                         case MONO_TYPE_R8:
6438                                 ins->type = STACK_R8;
6439                                 break;
6440                         default:
6441                                 g_assert (mini_type_is_reference (fsig->params [0]));
6442                                 ins->type = STACK_OBJ;
6443                                 break;
6444                         }
6445
6446                         if (is_float) {
6447                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
6448                                 i2f->dreg = mono_alloc_freg (cfg);
6449                                 i2f->sreg1 = ins->dreg;
6450                                 i2f->type = STACK_R8;
6451                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
6452                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6453                                 MONO_ADD_INS (cfg->cbb, i2f);
6454
6455                                 ins = i2f;
6456                         }
6457
6458                         if (cfg->gen_write_barriers && is_ref)
6459                                 emit_write_barrier (cfg, args [0], args [1]);
6460                 }
6461                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
6462                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
6463                         guint32 opcode, f2i_opcode, i2f_opcode;
6464                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
6465                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
6466
6467                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
6468                             fsig->params [1]->type == MONO_TYPE_R4) {
6469                                 opcode = OP_ATOMIC_CAS_I4;
6470                                 f2i_opcode = OP_MOVE_F_TO_I4;
6471                                 i2f_opcode = OP_MOVE_I4_TO_F;
6472                                 cfg->has_atomic_cas_i4 = TRUE;
6473                         }
6474 #if SIZEOF_REGISTER == 8
6475                         else if (is_ref ||
6476                                  fsig->params [1]->type == MONO_TYPE_I8 ||
6477                                  fsig->params [1]->type == MONO_TYPE_R8 ||
6478                                  fsig->params [1]->type == MONO_TYPE_I) {
6479                                 opcode = OP_ATOMIC_CAS_I8;
6480                                 f2i_opcode = OP_MOVE_F_TO_I8;
6481                                 i2f_opcode = OP_MOVE_I8_TO_F;
6482                         }
6483 #else
6484                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
6485                                 opcode = OP_ATOMIC_CAS_I4;
6486                                 cfg->has_atomic_cas_i4 = TRUE;
6487                         }
6488 #endif
6489                         else
6490                                 return NULL;
6491
6492                         if (!mono_arch_opcode_supported (opcode))
6493                                 return NULL;
6494
6495                         if (is_float) {
6496                                 /* TODO: Decompose these opcodes instead of bailing here. */
6497                                 if (COMPILE_SOFT_FLOAT (cfg))
6498                                         return NULL;
6499
6500                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
6501                                 f2i_new->dreg = mono_alloc_ireg (cfg);
6502                                 f2i_new->sreg1 = args [1]->dreg;
6503                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6504                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6505                                 MONO_ADD_INS (cfg->cbb, f2i_new);
6506
6507                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
6508                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
6509                                 f2i_cmp->sreg1 = args [2]->dreg;
6510                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
6511                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6512                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
6513                         }
6514
6515                         MONO_INST_NEW (cfg, ins, opcode);
6516                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
6517                         ins->sreg1 = args [0]->dreg;
6518                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
6519                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
6520                         MONO_ADD_INS (cfg->cbb, ins);
6521
6522                         switch (fsig->params [1]->type) {
6523                         case MONO_TYPE_I4:
6524                                 ins->type = STACK_I4;
6525                                 break;
6526                         case MONO_TYPE_I8:
6527                                 ins->type = STACK_I8;
6528                                 break;
6529                         case MONO_TYPE_I:
6530 #if SIZEOF_REGISTER == 8
6531                                 ins->type = STACK_I8;
6532 #else
6533                                 ins->type = STACK_I4;
6534 #endif
6535                                 break;
6536                         case MONO_TYPE_R4:
6537                                 ins->type = cfg->r4_stack_type;
6538                                 break;
6539                         case MONO_TYPE_R8:
6540                                 ins->type = STACK_R8;
6541                                 break;
6542                         default:
6543                                 g_assert (mini_type_is_reference (fsig->params [1]));
6544                                 ins->type = STACK_OBJ;
6545                                 break;
6546                         }
6547
6548                         if (is_float) {
6549                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
6550                                 i2f->dreg = mono_alloc_freg (cfg);
6551                                 i2f->sreg1 = ins->dreg;
6552                                 i2f->type = STACK_R8;
6553                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
6554                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
6555                                 MONO_ADD_INS (cfg->cbb, i2f);
6556
6557                                 ins = i2f;
6558                         }
6559
6560                         if (cfg->gen_write_barriers && is_ref)
6561                                 emit_write_barrier (cfg, args [0], args [1]);
6562                 }
6563                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
6564                          fsig->params [1]->type == MONO_TYPE_I4) {
6565                         MonoInst *cmp, *ceq;
6566
6567                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
6568                                 return NULL;
6569
6570                         /* int32 r = CAS (location, value, comparand); */
6571                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
6572                         ins->dreg = alloc_ireg (cfg);
6573                         ins->sreg1 = args [0]->dreg;
6574                         ins->sreg2 = args [1]->dreg;
6575                         ins->sreg3 = args [2]->dreg;
6576                         ins->type = STACK_I4;
6577                         MONO_ADD_INS (cfg->cbb, ins);
6578
6579                         /* bool result = r == comparand; */
6580                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
6581                         cmp->sreg1 = ins->dreg;
6582                         cmp->sreg2 = args [2]->dreg;
6583                         cmp->type = STACK_I4;
6584                         MONO_ADD_INS (cfg->cbb, cmp);
6585
6586                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
6587                         ceq->dreg = alloc_ireg (cfg);
6588                         ceq->type = STACK_I4;
6589                         MONO_ADD_INS (cfg->cbb, ceq);
6590
6591                         /* *success = result; */
6592                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
6593
6594                         cfg->has_atomic_cas_i4 = TRUE;
6595                 }
6596                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
6597                         ins = emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
6598
6599                 if (ins)
6600                         return ins;
6601         } else if (cmethod->klass->image == mono_defaults.corlib &&
6602                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
6603                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
6604                 ins = NULL;
6605
6606                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
6607                         guint32 opcode = 0;
6608                         MonoType *t = fsig->params [0];
6609                         gboolean is_ref;
6610                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
6611
6612                         g_assert (t->byref);
6613                         /* t is a byref type, so the reference check is more complicated */
6614                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
6615                         if (t->type == MONO_TYPE_I1)
6616                                 opcode = OP_ATOMIC_LOAD_I1;
6617                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
6618                                 opcode = OP_ATOMIC_LOAD_U1;
6619                         else if (t->type == MONO_TYPE_I2)
6620                                 opcode = OP_ATOMIC_LOAD_I2;
6621                         else if (t->type == MONO_TYPE_U2)
6622                                 opcode = OP_ATOMIC_LOAD_U2;
6623                         else if (t->type == MONO_TYPE_I4)
6624                                 opcode = OP_ATOMIC_LOAD_I4;
6625                         else if (t->type == MONO_TYPE_U4)
6626                                 opcode = OP_ATOMIC_LOAD_U4;
6627                         else if (t->type == MONO_TYPE_R4)
6628                                 opcode = OP_ATOMIC_LOAD_R4;
6629                         else if (t->type == MONO_TYPE_R8)
6630                                 opcode = OP_ATOMIC_LOAD_R8;
6631 #if SIZEOF_REGISTER == 8
6632                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
6633                                 opcode = OP_ATOMIC_LOAD_I8;
6634                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
6635                                 opcode = OP_ATOMIC_LOAD_U8;
6636 #else
6637                         else if (t->type == MONO_TYPE_I)
6638                                 opcode = OP_ATOMIC_LOAD_I4;
6639                         else if (is_ref || t->type == MONO_TYPE_U)
6640                                 opcode = OP_ATOMIC_LOAD_U4;
6641 #endif
6642
6643                         if (opcode) {
6644                                 if (!mono_arch_opcode_supported (opcode))
6645                                         return NULL;
6646
6647                                 MONO_INST_NEW (cfg, ins, opcode);
6648                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
6649                                 ins->sreg1 = args [0]->dreg;
6650                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
6651                                 MONO_ADD_INS (cfg->cbb, ins);
6652
6653                                 switch (t->type) {
6654                                 case MONO_TYPE_BOOLEAN:
6655                                 case MONO_TYPE_I1:
6656                                 case MONO_TYPE_U1:
6657                                 case MONO_TYPE_I2:
6658                                 case MONO_TYPE_U2:
6659                                 case MONO_TYPE_I4:
6660                                 case MONO_TYPE_U4:
6661                                         ins->type = STACK_I4;
6662                                         break;
6663                                 case MONO_TYPE_I8:
6664                                 case MONO_TYPE_U8:
6665                                         ins->type = STACK_I8;
6666                                         break;
6667                                 case MONO_TYPE_I:
6668                                 case MONO_TYPE_U:
6669 #if SIZEOF_REGISTER == 8
6670                                         ins->type = STACK_I8;
6671 #else
6672                                         ins->type = STACK_I4;
6673 #endif
6674                                         break;
6675                                 case MONO_TYPE_R4:
6676                                         ins->type = cfg->r4_stack_type;
6677                                         break;
6678                                 case MONO_TYPE_R8:
6679                                         ins->type = STACK_R8;
6680                                         break;
6681                                 default:
6682                                         g_assert (is_ref);
6683                                         ins->type = STACK_OBJ;
6684                                         break;
6685                                 }
6686                         }
6687                 }
6688
6689                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
6690                         guint32 opcode = 0;
6691                         MonoType *t = fsig->params [0];
6692                         gboolean is_ref;
6693
6694                         g_assert (t->byref);
6695                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
6696                         if (t->type == MONO_TYPE_I1)
6697                                 opcode = OP_ATOMIC_STORE_I1;
6698                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
6699                                 opcode = OP_ATOMIC_STORE_U1;
6700                         else if (t->type == MONO_TYPE_I2)
6701                                 opcode = OP_ATOMIC_STORE_I2;
6702                         else if (t->type == MONO_TYPE_U2)
6703                                 opcode = OP_ATOMIC_STORE_U2;
6704                         else if (t->type == MONO_TYPE_I4)
6705                                 opcode = OP_ATOMIC_STORE_I4;
6706                         else if (t->type == MONO_TYPE_U4)
6707                                 opcode = OP_ATOMIC_STORE_U4;
6708                         else if (t->type == MONO_TYPE_R4)
6709                                 opcode = OP_ATOMIC_STORE_R4;
6710                         else if (t->type == MONO_TYPE_R8)
6711                                 opcode = OP_ATOMIC_STORE_R8;
6712 #if SIZEOF_REGISTER == 8
6713                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
6714                                 opcode = OP_ATOMIC_STORE_I8;
6715                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
6716                                 opcode = OP_ATOMIC_STORE_U8;
6717 #else
6718                         else if (t->type == MONO_TYPE_I)
6719                                 opcode = OP_ATOMIC_STORE_I4;
6720                         else if (is_ref || t->type == MONO_TYPE_U)
6721                                 opcode = OP_ATOMIC_STORE_U4;
6722 #endif
6723
6724                         if (opcode) {
6725                                 if (!mono_arch_opcode_supported (opcode))
6726                                         return NULL;
6727
6728                                 MONO_INST_NEW (cfg, ins, opcode);
6729                                 ins->dreg = args [0]->dreg;
6730                                 ins->sreg1 = args [1]->dreg;
6731                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
6732                                 MONO_ADD_INS (cfg->cbb, ins);
6733
6734                                 if (cfg->gen_write_barriers && is_ref)
6735                                         emit_write_barrier (cfg, args [0], args [1]);
6736                         }
6737                 }
6738
6739                 if (ins)
6740                         return ins;
6741         } else if (cmethod->klass->image == mono_defaults.corlib &&
6742                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
6743                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
6744                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
6745                         if (should_insert_brekpoint (cfg->method)) {
6746                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
6747                         } else {
6748                                 MONO_INST_NEW (cfg, ins, OP_NOP);
6749                                 MONO_ADD_INS (cfg->cbb, ins);
6750                         }
6751                         return ins;
6752                 }
6753         } else if (cmethod->klass->image == mono_defaults.corlib &&
6754                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
6755                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
6756                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
6757 #ifdef TARGET_WIN32
6758                         EMIT_NEW_ICONST (cfg, ins, 1);
6759 #else
6760                         EMIT_NEW_ICONST (cfg, ins, 0);
6761 #endif
6762                 }
6763         } else if (cmethod->klass->image == mono_defaults.corlib &&
6764                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6765                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
6766                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
6767                         /* No stack walks are currently available, so implement this as an intrinsic */
6768                         MonoInst *assembly_ins;
6769
6770                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
6771                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
6772                         return ins;
6773                 }
6774         } else if (cmethod->klass->image == mono_defaults.corlib &&
6775                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6776                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
6777                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
6778                         /* No stack walks are currently available, so implement this as an intrinsic */
6779                         MonoInst *method_ins;
6780                         MonoMethod *declaring = cfg->method;
6781
6782                         /* This returns the declaring generic method */
6783                         if (declaring->is_inflated)
6784                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
6785                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
6786                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
6787                         cfg->no_inline = TRUE;
6788                         if (cfg->method != cfg->current_method)
6789                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
6790                         return ins;
6791                 }
6792         } else if (cmethod->klass == mono_defaults.math_class) {
6793                 /* 
6794                  * There is general branchless code for Min/Max, but it does not work for 
6795                  * all inputs:
6796                  * http://everything2.com/?node_id=1051618
6797                  */
6798         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
6799                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
6800                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
6801                                 !strcmp (cmethod->klass->name, "Selector")) ||
6802                            (!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") &&
6803                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6804                                 !strcmp (cmethod->klass->name, "Selector"))
6805                            ) {
6806                 if (cfg->backend->have_objc_get_selector &&
6807                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6808                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6809                     cfg->compile_aot && !cfg->llvm_only) {
6810                         MonoInst *pi;
6811                         MonoJumpInfoToken *ji;
6812                         MonoString *s;
6813
6814                         // FIXME: llvmonly
6815
6816                         cfg->exception_message = g_strdup ("GetHandle");
6817                         cfg->disable_llvm = TRUE;
6818
6819                         if (args [0]->opcode == OP_GOT_ENTRY) {
6820                                 pi = (MonoInst *)args [0]->inst_p1;
6821                                 g_assert (pi->opcode == OP_PATCH_INFO);
6822                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6823                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6824                         } else {
6825                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6826                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6827                         }
6828
6829                         NULLIFY_INS (args [0]);
6830
6831                         // FIXME: Ugly
6832                         s = mono_ldstr_checked (cfg->domain, ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6833                         return_val_if_nok (&cfg->error, NULL);
6834                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6835                         ins->dreg = mono_alloc_ireg (cfg);
6836                         // FIXME: Leaks
6837                         ins->inst_p0 = mono_string_to_utf8 (s);
6838                         MONO_ADD_INS (cfg->cbb, ins);
6839                         return ins;
6840                 }
6841         }
6842
6843 #ifdef MONO_ARCH_SIMD_INTRINSICS
6844         if (cfg->opt & MONO_OPT_SIMD) {
6845                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6846                 if (ins)
6847                         return ins;
6848         }
6849 #endif
6850
6851         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6852         if (ins)
6853                 return ins;
6854
6855         if (COMPILE_LLVM (cfg)) {
6856                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6857                 if (ins)
6858                         return ins;
6859         }
6860
6861         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6862 }
6863
6864 /*
6865  * This entry point could be used later for arbitrary method
6866  * redirection.
6867  */
6868 inline static MonoInst*
6869 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6870                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6871 {
6872         if (method->klass == mono_defaults.string_class) {
6873                 /* managed string allocation support */
6874                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6875                         MonoInst *iargs [2];
6876                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6877                         MonoMethod *managed_alloc = NULL;
6878
6879                         g_assert (vtable); /*Should not fail since it System.String*/
6880 #ifndef MONO_CROSS_COMPILE
6881                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6882 #endif
6883                         if (!managed_alloc)
6884                                 return NULL;
6885                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6886                         iargs [1] = args [0];
6887                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6888                 }
6889         }
6890         return NULL;
6891 }
6892
6893 static void
6894 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6895 {
6896         MonoInst *store, *temp;
6897         int i;
6898
6899         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6900                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6901
6902                 /*
6903                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6904                  * would be different than the MonoInst's used to represent arguments, and
6905                  * the ldelema implementation can't deal with that.
6906                  * Solution: When ldelema is used on an inline argument, create a var for 
6907                  * it, emit ldelema on that var, and emit the saving code below in
6908                  * inline_method () if needed.
6909                  */
6910                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6911                 cfg->args [i] = temp;
6912                 /* This uses cfg->args [i] which is set by the preceeding line */
6913                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6914                 store->cil_code = sp [0]->cil_code;
6915                 sp++;
6916         }
6917 }
6918
6919 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6920 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6921
6922 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6923 static gboolean
6924 check_inline_called_method_name_limit (MonoMethod *called_method)
6925 {
6926         int strncmp_result;
6927         static const char *limit = NULL;
6928         
6929         if (limit == NULL) {
6930                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6931
6932                 if (limit_string != NULL)
6933                         limit = limit_string;
6934                 else
6935                         limit = "";
6936         }
6937
6938         if (limit [0] != '\0') {
6939                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6940
6941                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6942                 g_free (called_method_name);
6943         
6944                 //return (strncmp_result <= 0);
6945                 return (strncmp_result == 0);
6946         } else {
6947                 return TRUE;
6948         }
6949 }
6950 #endif
6951
6952 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6953 static gboolean
6954 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6955 {
6956         int strncmp_result;
6957         static const char *limit = NULL;
6958         
6959         if (limit == NULL) {
6960                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6961                 if (limit_string != NULL) {
6962                         limit = limit_string;
6963                 } else {
6964                         limit = "";
6965                 }
6966         }
6967
6968         if (limit [0] != '\0') {
6969                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6970
6971                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6972                 g_free (caller_method_name);
6973         
6974                 //return (strncmp_result <= 0);
6975                 return (strncmp_result == 0);
6976         } else {
6977                 return TRUE;
6978         }
6979 }
6980 #endif
6981
6982 static void
6983 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6984 {
6985         static double r8_0 = 0.0;
6986         static float r4_0 = 0.0;
6987         MonoInst *ins;
6988         int t;
6989
6990         rtype = mini_get_underlying_type (rtype);
6991         t = rtype->type;
6992
6993         if (rtype->byref) {
6994                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6995         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6996                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6997         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6998                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6999         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
7000                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
7001                 ins->type = STACK_R4;
7002                 ins->inst_p0 = (void*)&r4_0;
7003                 ins->dreg = dreg;
7004                 MONO_ADD_INS (cfg->cbb, ins);
7005         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7006                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7007                 ins->type = STACK_R8;
7008                 ins->inst_p0 = (void*)&r8_0;
7009                 ins->dreg = dreg;
7010                 MONO_ADD_INS (cfg->cbb, ins);
7011         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7012                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
7013                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
7014         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
7015                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
7016         } else {
7017                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
7018         }
7019 }
7020
7021 static void
7022 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
7023 {
7024         int t;
7025
7026         rtype = mini_get_underlying_type (rtype);
7027         t = rtype->type;
7028
7029         if (rtype->byref) {
7030                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
7031         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
7032                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
7033         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
7034                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
7035         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
7036                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
7037         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7038                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
7039         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7040                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
7041                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
7042         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
7043                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
7044         } else {
7045                 emit_init_rvar (cfg, dreg, rtype);
7046         }
7047 }
7048
7049 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
7050 static void
7051 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
7052 {
7053         MonoInst *var = cfg->locals [local];
7054         if (COMPILE_SOFT_FLOAT (cfg)) {
7055                 MonoInst *store;
7056                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
7057                 emit_init_rvar (cfg, reg, type);
7058                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
7059         } else {
7060                 if (init)
7061                         emit_init_rvar (cfg, var->dreg, type);
7062                 else
7063                         emit_dummy_init_rvar (cfg, var->dreg, type);
7064         }
7065 }
7066
7067 /*
7068  * inline_method:
7069  *
7070  *   Return the cost of inlining CMETHOD.
7071  */
7072 static int
7073 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
7074                            guchar *ip, guint real_offset, gboolean inline_always)
7075 {
7076         MonoError error;
7077         MonoInst *ins, *rvar = NULL;
7078         MonoMethodHeader *cheader;
7079         MonoBasicBlock *ebblock, *sbblock;
7080         int i, costs;
7081         MonoMethod *prev_inlined_method;
7082         MonoInst **prev_locals, **prev_args;
7083         MonoType **prev_arg_types;
7084         guint prev_real_offset;
7085         GHashTable *prev_cbb_hash;
7086         MonoBasicBlock **prev_cil_offset_to_bb;
7087         MonoBasicBlock *prev_cbb;
7088         unsigned char* prev_cil_start;
7089         guint32 prev_cil_offset_to_bb_len;
7090         MonoMethod *prev_current_method;
7091         MonoGenericContext *prev_generic_context;
7092         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
7093
7094         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
7095
7096 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
7097         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
7098                 return 0;
7099 #endif
7100 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
7101         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
7102                 return 0;
7103 #endif
7104
7105         if (!fsig)
7106                 fsig = mono_method_signature (cmethod);
7107
7108         if (cfg->verbose_level > 2)
7109                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
7110
7111         if (!cmethod->inline_info) {
7112                 cfg->stat_inlineable_methods++;
7113                 cmethod->inline_info = 1;
7114         }
7115
7116         /* allocate local variables */
7117         cheader = mono_method_get_header_checked (cmethod, &error);
7118         if (!cheader) {
7119                 if (inline_always) {
7120                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7121                         mono_error_move (&cfg->error, &error);
7122                 } else {
7123                         mono_error_cleanup (&error);
7124                 }
7125                 return 0;
7126         }
7127
7128         /*Must verify before creating locals as it can cause the JIT to assert.*/
7129         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
7130                 mono_metadata_free_mh (cheader);
7131                 return 0;
7132         }
7133
7134         /* allocate space to store the return value */
7135         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
7136                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
7137         }
7138
7139         prev_locals = cfg->locals;
7140         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
7141         for (i = 0; i < cheader->num_locals; ++i)
7142                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
7143
7144         /* allocate start and end blocks */
7145         /* This is needed so if the inline is aborted, we can clean up */
7146         NEW_BBLOCK (cfg, sbblock);
7147         sbblock->real_offset = real_offset;
7148
7149         NEW_BBLOCK (cfg, ebblock);
7150         ebblock->block_num = cfg->num_bblocks++;
7151         ebblock->real_offset = real_offset;
7152
7153         prev_args = cfg->args;
7154         prev_arg_types = cfg->arg_types;
7155         prev_inlined_method = cfg->inlined_method;
7156         cfg->inlined_method = cmethod;
7157         cfg->ret_var_set = FALSE;
7158         cfg->inline_depth ++;
7159         prev_real_offset = cfg->real_offset;
7160         prev_cbb_hash = cfg->cbb_hash;
7161         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
7162         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
7163         prev_cil_start = cfg->cil_start;
7164         prev_cbb = cfg->cbb;
7165         prev_current_method = cfg->current_method;
7166         prev_generic_context = cfg->generic_context;
7167         prev_ret_var_set = cfg->ret_var_set;
7168         prev_disable_inline = cfg->disable_inline;
7169
7170         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
7171                 virtual_ = TRUE;
7172
7173         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
7174
7175         ret_var_set = cfg->ret_var_set;
7176
7177         cfg->inlined_method = prev_inlined_method;
7178         cfg->real_offset = prev_real_offset;
7179         cfg->cbb_hash = prev_cbb_hash;
7180         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
7181         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
7182         cfg->cil_start = prev_cil_start;
7183         cfg->locals = prev_locals;
7184         cfg->args = prev_args;
7185         cfg->arg_types = prev_arg_types;
7186         cfg->current_method = prev_current_method;
7187         cfg->generic_context = prev_generic_context;
7188         cfg->ret_var_set = prev_ret_var_set;
7189         cfg->disable_inline = prev_disable_inline;
7190         cfg->inline_depth --;
7191
7192         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
7193                 if (cfg->verbose_level > 2)
7194                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
7195                 
7196                 cfg->stat_inlined_methods++;
7197
7198                 /* always add some code to avoid block split failures */
7199                 MONO_INST_NEW (cfg, ins, OP_NOP);
7200                 MONO_ADD_INS (prev_cbb, ins);
7201
7202                 prev_cbb->next_bb = sbblock;
7203                 link_bblock (cfg, prev_cbb, sbblock);
7204
7205                 /* 
7206                  * Get rid of the begin and end bblocks if possible to aid local
7207                  * optimizations.
7208                  */
7209                 mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
7210
7211                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
7212                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
7213
7214                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
7215                         MonoBasicBlock *prev = ebblock->in_bb [0];
7216
7217                         if (prev->next_bb == ebblock) {
7218                                 mono_merge_basic_blocks (cfg, prev, ebblock);
7219                                 cfg->cbb = prev;
7220                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
7221                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
7222                                         cfg->cbb = prev_cbb;
7223                                 }
7224                         } else {
7225                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
7226                                 cfg->cbb = ebblock;
7227                         }
7228                 } else {
7229                         /* 
7230                          * Its possible that the rvar is set in some prev bblock, but not in others.
7231                          * (#1835).
7232                          */
7233                         if (rvar) {
7234                                 MonoBasicBlock *bb;
7235
7236                                 for (i = 0; i < ebblock->in_count; ++i) {
7237                                         bb = ebblock->in_bb [i];
7238
7239                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
7240                                                 cfg->cbb = bb;
7241
7242                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
7243                                         }
7244                                 }
7245                         }
7246
7247                         cfg->cbb = ebblock;
7248                 }
7249
7250                 if (rvar) {
7251                         /*
7252                          * If the inlined method contains only a throw, then the ret var is not 
7253                          * set, so set it to a dummy value.
7254                          */
7255                         if (!ret_var_set)
7256                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
7257
7258                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
7259                         *sp++ = ins;
7260                 }
7261                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
7262                 return costs + 1;
7263         } else {
7264                 if (cfg->verbose_level > 2)
7265                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
7266                 cfg->exception_type = MONO_EXCEPTION_NONE;
7267
7268                 /* This gets rid of the newly added bblocks */
7269                 cfg->cbb = prev_cbb;
7270         }
7271         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
7272         return 0;
7273 }
7274
7275 /*
7276  * Some of these comments may well be out-of-date.
7277  * Design decisions: we do a single pass over the IL code (and we do bblock 
7278  * splitting/merging in the few cases when it's required: a back jump to an IL
7279  * address that was not already seen as bblock starting point).
7280  * Code is validated as we go (full verification is still better left to metadata/verify.c).
7281  * Complex operations are decomposed in simpler ones right away. We need to let the 
7282  * arch-specific code peek and poke inside this process somehow (except when the 
7283  * optimizations can take advantage of the full semantic info of coarse opcodes).
7284  * All the opcodes of the form opcode.s are 'normalized' to opcode.
7285  * MonoInst->opcode initially is the IL opcode or some simplification of that 
7286  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
7287  * opcode with value bigger than OP_LAST.
7288  * At this point the IR can be handed over to an interpreter, a dumb code generator
7289  * or to the optimizing code generator that will translate it to SSA form.
7290  *
7291  * Profiling directed optimizations.
7292  * We may compile by default with few or no optimizations and instrument the code
7293  * or the user may indicate what methods to optimize the most either in a config file
7294  * or through repeated runs where the compiler applies offline the optimizations to 
7295  * each method and then decides if it was worth it.
7296  */
7297
7298 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
7299 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
7300 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
7301 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
7302 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
7303 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
7304 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
7305 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
7306
7307 /* offset from br.s -> br like opcodes */
7308 #define BIG_BRANCH_OFFSET 13
7309
7310 static gboolean
7311 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
7312 {
7313         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
7314
7315         return b == NULL || b == bb;
7316 }
7317
7318 static int
7319 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
7320 {
7321         unsigned char *ip = start;
7322         unsigned char *target;
7323         int i;
7324         guint cli_addr;
7325         MonoBasicBlock *bblock;
7326         const MonoOpcode *opcode;
7327
7328         while (ip < end) {
7329                 cli_addr = ip - start;
7330                 i = mono_opcode_value ((const guint8 **)&ip, end);
7331                 if (i < 0)
7332                         UNVERIFIED;
7333                 opcode = &mono_opcodes [i];
7334                 switch (opcode->argument) {
7335                 case MonoInlineNone:
7336                         ip++; 
7337                         break;
7338                 case MonoInlineString:
7339                 case MonoInlineType:
7340                 case MonoInlineField:
7341                 case MonoInlineMethod:
7342                 case MonoInlineTok:
7343                 case MonoInlineSig:
7344                 case MonoShortInlineR:
7345                 case MonoInlineI:
7346                         ip += 5;
7347                         break;
7348                 case MonoInlineVar:
7349                         ip += 3;
7350                         break;
7351                 case MonoShortInlineVar:
7352                 case MonoShortInlineI:
7353                         ip += 2;
7354                         break;
7355                 case MonoShortInlineBrTarget:
7356                         target = start + cli_addr + 2 + (signed char)ip [1];
7357                         GET_BBLOCK (cfg, bblock, target);
7358                         ip += 2;
7359                         if (ip < end)
7360                                 GET_BBLOCK (cfg, bblock, ip);
7361                         break;
7362                 case MonoInlineBrTarget:
7363                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
7364                         GET_BBLOCK (cfg, bblock, target);
7365                         ip += 5;
7366                         if (ip < end)
7367                                 GET_BBLOCK (cfg, bblock, ip);
7368                         break;
7369                 case MonoInlineSwitch: {
7370                         guint32 n = read32 (ip + 1);
7371                         guint32 j;
7372                         ip += 5;
7373                         cli_addr += 5 + 4 * n;
7374                         target = start + cli_addr;
7375                         GET_BBLOCK (cfg, bblock, target);
7376                         
7377                         for (j = 0; j < n; ++j) {
7378                                 target = start + cli_addr + (gint32)read32 (ip);
7379                                 GET_BBLOCK (cfg, bblock, target);
7380                                 ip += 4;
7381                         }
7382                         break;
7383                 }
7384                 case MonoInlineR:
7385                 case MonoInlineI8:
7386                         ip += 9;
7387                         break;
7388                 default:
7389                         g_assert_not_reached ();
7390                 }
7391
7392                 if (i == CEE_THROW) {
7393                         unsigned char *bb_start = ip - 1;
7394                         
7395                         /* Find the start of the bblock containing the throw */
7396                         bblock = NULL;
7397                         while ((bb_start >= start) && !bblock) {
7398                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
7399                                 bb_start --;
7400                         }
7401                         if (bblock)
7402                                 bblock->out_of_line = 1;
7403                 }
7404         }
7405         return 0;
7406 unverified:
7407 exception_exit:
7408         *pos = ip;
7409         return 1;
7410 }
7411
7412 static inline MonoMethod *
7413 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
7414 {
7415         MonoMethod *method;
7416
7417         mono_error_init (error);
7418
7419         if (m->wrapper_type != MONO_WRAPPER_NONE) {
7420                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
7421                 if (context) {
7422                         method = mono_class_inflate_generic_method_checked (method, context, error);
7423                 }
7424         } else {
7425                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
7426         }
7427
7428         return method;
7429 }
7430
7431 static inline MonoMethod *
7432 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
7433 {
7434         MonoError error;
7435         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
7436
7437         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
7438                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
7439                 method = NULL;
7440         }
7441
7442         if (!method && !cfg)
7443                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7444
7445         return method;
7446 }
7447
7448 static inline MonoClass*
7449 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
7450 {
7451         MonoError error;
7452         MonoClass *klass;
7453
7454         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7455                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7456                 if (context) {
7457                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
7458                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7459                 }
7460         } else {
7461                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
7462                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7463         }
7464         if (klass)
7465                 mono_class_init (klass);
7466         return klass;
7467 }
7468
7469 static inline MonoMethodSignature*
7470 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
7471 {
7472         MonoMethodSignature *fsig;
7473
7474         mono_error_init (error);
7475         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7476                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
7477         } else {
7478                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
7479                 return_val_if_nok (error, NULL);
7480         }
7481         if (context) {
7482                 fsig = mono_inflate_generic_signature(fsig, context, error);
7483         }
7484         return fsig;
7485 }
7486
7487 static MonoMethod*
7488 throw_exception (void)
7489 {
7490         static MonoMethod *method = NULL;
7491
7492         if (!method) {
7493                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
7494                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
7495         }
7496         g_assert (method);
7497         return method;
7498 }
7499
7500 static void
7501 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
7502 {
7503         MonoMethod *thrower = throw_exception ();
7504         MonoInst *args [1];
7505
7506         EMIT_NEW_PCONST (cfg, args [0], ex);
7507         mono_emit_method_call (cfg, thrower, args, NULL);
7508 }
7509
7510 /*
7511  * Return the original method is a wrapper is specified. We can only access 
7512  * the custom attributes from the original method.
7513  */
7514 static MonoMethod*
7515 get_original_method (MonoMethod *method)
7516 {
7517         if (method->wrapper_type == MONO_WRAPPER_NONE)
7518                 return method;
7519
7520         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
7521         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
7522                 return NULL;
7523
7524         /* in other cases we need to find the original method */
7525         return mono_marshal_method_from_wrapper (method);
7526 }
7527
7528 static void
7529 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
7530 {
7531         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
7532         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
7533         if (ex)
7534                 emit_throw_exception (cfg, ex);
7535 }
7536
7537 static void
7538 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
7539 {
7540         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
7541         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
7542         if (ex)
7543                 emit_throw_exception (cfg, ex);
7544 }
7545
7546 /*
7547  * Check that the IL instructions at ip are the array initialization
7548  * sequence and return the pointer to the data and the size.
7549  */
7550 static const char*
7551 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
7552 {
7553         /*
7554          * newarr[System.Int32]
7555          * dup
7556          * ldtoken field valuetype ...
7557          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
7558          */
7559         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
7560                 MonoError error;
7561                 guint32 token = read32 (ip + 7);
7562                 guint32 field_token = read32 (ip + 2);
7563                 guint32 field_index = field_token & 0xffffff;
7564                 guint32 rva;
7565                 const char *data_ptr;
7566                 int size = 0;
7567                 MonoMethod *cmethod;
7568                 MonoClass *dummy_class;
7569                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
7570                 int dummy_align;
7571
7572                 if (!field) {
7573                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7574                         return NULL;
7575                 }
7576
7577                 *out_field_token = field_token;
7578
7579                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
7580                 if (!cmethod)
7581                         return NULL;
7582                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
7583                         return NULL;
7584                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
7585                 case MONO_TYPE_BOOLEAN:
7586                 case MONO_TYPE_I1:
7587                 case MONO_TYPE_U1:
7588                         size = 1; break;
7589                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
7590 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
7591                 case MONO_TYPE_CHAR:
7592                 case MONO_TYPE_I2:
7593                 case MONO_TYPE_U2:
7594                         size = 2; break;
7595                 case MONO_TYPE_I4:
7596                 case MONO_TYPE_U4:
7597                 case MONO_TYPE_R4:
7598                         size = 4; break;
7599                 case MONO_TYPE_R8:
7600                 case MONO_TYPE_I8:
7601                 case MONO_TYPE_U8:
7602                         size = 8; break;
7603 #endif
7604                 default:
7605                         return NULL;
7606                 }
7607                 size *= len;
7608                 if (size > mono_type_size (field->type, &dummy_align))
7609                     return NULL;
7610                 *out_size = size;
7611                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
7612                 if (!image_is_dynamic (method->klass->image)) {
7613                         field_index = read32 (ip + 2) & 0xffffff;
7614                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
7615                         data_ptr = mono_image_rva_map (method->klass->image, rva);
7616                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
7617                         /* for aot code we do the lookup on load */
7618                         if (aot && data_ptr)
7619                                 return (const char *)GUINT_TO_POINTER (rva);
7620                 } else {
7621                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
7622                         g_assert (!aot);
7623                         data_ptr = mono_field_get_data (field);
7624                 }
7625                 return data_ptr;
7626         }
7627         return NULL;
7628 }
7629
7630 static void
7631 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
7632 {
7633         MonoError error;
7634         char *method_fname = mono_method_full_name (method, TRUE);
7635         char *method_code;
7636         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
7637
7638         if (!header) {
7639                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
7640                 mono_error_cleanup (&error);
7641         } else if (header->code_size == 0)
7642                 method_code = g_strdup ("method body is empty.");
7643         else
7644                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
7645         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
7646         g_free (method_fname);
7647         g_free (method_code);
7648         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7649 }
7650
7651 static void
7652 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
7653 {
7654         MonoInst *ins;
7655         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
7656         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
7657                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
7658                 /* Optimize reg-reg moves away */
7659                 /* 
7660                  * Can't optimize other opcodes, since sp[0] might point to
7661                  * the last ins of a decomposed opcode.
7662                  */
7663                 sp [0]->dreg = (cfg)->locals [n]->dreg;
7664         } else {
7665                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
7666         }
7667 }
7668
7669 /*
7670  * ldloca inhibits many optimizations so try to get rid of it in common
7671  * cases.
7672  */
7673 static inline unsigned char *
7674 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
7675 {
7676         int local, token;
7677         MonoClass *klass;
7678         MonoType *type;
7679
7680         if (size == 1) {
7681                 local = ip [1];
7682                 ip += 2;
7683         } else {
7684                 local = read16 (ip + 2);
7685                 ip += 4;
7686         }
7687         
7688         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
7689                 /* From the INITOBJ case */
7690                 token = read32 (ip + 2);
7691                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
7692                 CHECK_TYPELOAD (klass);
7693                 type = mini_get_underlying_type (&klass->byval_arg);
7694                 emit_init_local (cfg, local, type, TRUE);
7695                 return ip + 6;
7696         }
7697  exception_exit:
7698         return NULL;
7699 }
7700
7701 static MonoInst*
7702 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
7703 {
7704         MonoInst *icall_args [16];
7705         MonoInst *call_target, *ins, *vtable_ins;
7706         int arg_reg, this_reg, vtable_reg;
7707         gboolean is_iface = cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE;
7708         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
7709         gboolean variant_iface = FALSE;
7710         guint32 slot;
7711         int offset;
7712
7713         /*
7714          * In llvm-only mode, vtables contain function descriptors instead of
7715          * method addresses/trampolines.
7716          */
7717         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
7718
7719         if (is_iface)
7720                 slot = mono_method_get_imt_slot (cmethod);
7721         else
7722                 slot = mono_method_get_vtable_index (cmethod);
7723
7724         this_reg = sp [0]->dreg;
7725
7726         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
7727                 variant_iface = TRUE;
7728
7729         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
7730                 /*
7731                  * The simplest case, a normal virtual call.
7732                  */
7733                 int slot_reg = alloc_preg (cfg);
7734                 int addr_reg = alloc_preg (cfg);
7735                 int arg_reg = alloc_preg (cfg);
7736                 MonoBasicBlock *non_null_bb;
7737
7738                 vtable_reg = alloc_preg (cfg);
7739                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7740                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7741
7742                 /* Load the vtable slot, which contains a function descriptor. */
7743                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7744
7745                 NEW_BBLOCK (cfg, non_null_bb);
7746
7747                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7748                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
7749                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
7750
7751                 /* Slow path */
7752                 // FIXME: Make the wrapper use the preserveall cconv
7753                 // FIXME: Use one icall per slot for small slot numbers ?
7754                 icall_args [0] = vtable_ins;
7755                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7756                 /* Make the icall return the vtable slot value to save some code space */
7757                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
7758                 ins->dreg = slot_reg;
7759                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
7760
7761                 /* Fastpath */
7762                 MONO_START_BB (cfg, non_null_bb);
7763                 /* Load the address + arg from the vtable slot */
7764                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7765                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
7766
7767                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7768         }
7769
7770         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt) {
7771                 /*
7772                  * A simple interface call
7773                  *
7774                  * We make a call through an imt slot to obtain the function descriptor we need to call.
7775                  * The imt slot contains a function descriptor for a runtime function + arg.
7776                  */
7777                 int slot_reg = alloc_preg (cfg);
7778                 int addr_reg = alloc_preg (cfg);
7779                 int arg_reg = alloc_preg (cfg);
7780                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7781
7782                 vtable_reg = alloc_preg (cfg);
7783                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7784                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7785
7786                 /*
7787                  * The slot is already initialized when the vtable is created so there is no need
7788                  * to check it here.
7789                  */
7790
7791                 /* Load the imt slot, which contains a function descriptor. */
7792                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7793
7794                 /* Load the address + arg of the imt thunk from the imt slot */
7795                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7796                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7797                 /*
7798                  * IMT thunks in llvm-only mode are C functions which take an info argument
7799                  * plus the imt method and return the ftndesc to call.
7800                  */
7801                 icall_args [0] = thunk_arg_ins;
7802                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7803                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7804                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_thunk, icall_args, thunk_addr_ins, NULL, NULL);
7805
7806                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7807         }
7808
7809         if ((fsig->generic_param_count || variant_iface) && !is_gsharedvt) {
7810                 /*
7811                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7812                  * dynamically extended as more instantiations are discovered.
7813                  * This handles generic virtual methods both on classes and interfaces.
7814                  */
7815                 int slot_reg = alloc_preg (cfg);
7816                 int addr_reg = alloc_preg (cfg);
7817                 int arg_reg = alloc_preg (cfg);
7818                 int ftndesc_reg = alloc_preg (cfg);
7819                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7820                 MonoBasicBlock *slowpath_bb, *end_bb;
7821
7822                 NEW_BBLOCK (cfg, slowpath_bb);
7823                 NEW_BBLOCK (cfg, end_bb);
7824
7825                 vtable_reg = alloc_preg (cfg);
7826                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7827                 if (is_iface)
7828                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7829                 else
7830                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7831
7832                 /* Load the slot, which contains a function descriptor. */
7833                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7834
7835                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7836                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7837                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7838                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7839
7840                 /* Fastpath */
7841                 /* Same as with iface calls */
7842                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7843                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7844                 icall_args [0] = thunk_arg_ins;
7845                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7846                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7847                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_thunk, icall_args, thunk_addr_ins, NULL, NULL);
7848                 ftndesc_ins->dreg = ftndesc_reg;
7849                 /*
7850                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7851                  * they don't know about yet. Fall back to the slowpath in that case.
7852                  */
7853                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7854                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7855
7856                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7857
7858                 /* Slowpath */
7859                 MONO_START_BB (cfg, slowpath_bb);
7860                 icall_args [0] = vtable_ins;
7861                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7862                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7863                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7864                 if (is_iface)
7865                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7866                 else
7867                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7868                 ftndesc_ins->dreg = ftndesc_reg;
7869                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7870
7871                 /* Common case */
7872                 MONO_START_BB (cfg, end_bb);
7873                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7874         }
7875
7876         /*
7877          * Non-optimized cases
7878          */
7879         icall_args [0] = sp [0];
7880         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7881
7882         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7883                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7884
7885         arg_reg = alloc_preg (cfg);
7886         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7887         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7888
7889         g_assert (is_gsharedvt);
7890         if (is_iface)
7891                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7892         else
7893                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7894
7895         /*
7896          * Pass the extra argument even if the callee doesn't receive it, most
7897          * calling conventions allow this.
7898          */
7899         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7900 }
7901
7902 static gboolean
7903 is_exception_class (MonoClass *klass)
7904 {
7905         while (klass) {
7906                 if (klass == mono_defaults.exception_class)
7907                         return TRUE;
7908                 klass = klass->parent;
7909         }
7910         return FALSE;
7911 }
7912
7913 /*
7914  * is_jit_optimizer_disabled:
7915  *
7916  *   Determine whenever M's assembly has a DebuggableAttribute with the
7917  * IsJITOptimizerDisabled flag set.
7918  */
7919 static gboolean
7920 is_jit_optimizer_disabled (MonoMethod *m)
7921 {
7922         MonoError error;
7923         MonoAssembly *ass = m->klass->image->assembly;
7924         MonoCustomAttrInfo* attrs;
7925         MonoClass *klass;
7926         int i;
7927         gboolean val = FALSE;
7928
7929         g_assert (ass);
7930         if (ass->jit_optimizer_disabled_inited)
7931                 return ass->jit_optimizer_disabled;
7932
7933         klass = mono_class_try_get_debuggable_attribute_class ();
7934
7935         if (!klass) {
7936                 /* Linked away */
7937                 ass->jit_optimizer_disabled = FALSE;
7938                 mono_memory_barrier ();
7939                 ass->jit_optimizer_disabled_inited = TRUE;
7940                 return FALSE;
7941         }
7942
7943         attrs = mono_custom_attrs_from_assembly_checked (ass, &error);
7944         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7945         if (attrs) {
7946                 for (i = 0; i < attrs->num_attrs; ++i) {
7947                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7948                         const gchar *p;
7949                         MonoMethodSignature *sig;
7950
7951                         if (!attr->ctor || attr->ctor->klass != klass)
7952                                 continue;
7953                         /* Decode the attribute. See reflection.c */
7954                         p = (const char*)attr->data;
7955                         g_assert (read16 (p) == 0x0001);
7956                         p += 2;
7957
7958                         // FIXME: Support named parameters
7959                         sig = mono_method_signature (attr->ctor);
7960                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7961                                 continue;
7962                         /* Two boolean arguments */
7963                         p ++;
7964                         val = *p;
7965                 }
7966                 mono_custom_attrs_free (attrs);
7967         }
7968
7969         ass->jit_optimizer_disabled = val;
7970         mono_memory_barrier ();
7971         ass->jit_optimizer_disabled_inited = TRUE;
7972
7973         return val;
7974 }
7975
7976 static gboolean
7977 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7978 {
7979         gboolean supported_tail_call;
7980         int i;
7981
7982         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7983
7984         for (i = 0; i < fsig->param_count; ++i) {
7985                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7986                         /* These can point to the current method's stack */
7987                         supported_tail_call = FALSE;
7988         }
7989         if (fsig->hasthis && cmethod->klass->valuetype)
7990                 /* this might point to the current method's stack */
7991                 supported_tail_call = FALSE;
7992         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7993                 supported_tail_call = FALSE;
7994         if (cfg->method->save_lmf)
7995                 supported_tail_call = FALSE;
7996         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7997                 supported_tail_call = FALSE;
7998         if (call_opcode != CEE_CALL)
7999                 supported_tail_call = FALSE;
8000
8001         /* Debugging support */
8002 #if 0
8003         if (supported_tail_call) {
8004                 if (!mono_debug_count ())
8005                         supported_tail_call = FALSE;
8006         }
8007 #endif
8008
8009         return supported_tail_call;
8010 }
8011
8012 /*
8013  * handle_ctor_call:
8014  *
8015  *   Handle calls made to ctors from NEWOBJ opcodes.
8016  */
8017 static void
8018 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
8019                                   MonoInst **sp, guint8 *ip, int *inline_costs)
8020 {
8021         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
8022
8023         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
8024                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
8025                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
8026                         mono_class_vtable (cfg->domain, cmethod->klass);
8027                         CHECK_TYPELOAD (cmethod->klass);
8028
8029                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
8030                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8031                 } else {
8032                         if (context_used) {
8033                                 vtable_arg = emit_get_rgctx_klass (cfg, context_used,
8034                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8035                         } else {
8036                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8037
8038                                 CHECK_TYPELOAD (cmethod->klass);
8039                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8040                         }
8041                 }
8042         }
8043
8044         /* Avoid virtual calls to ctors if possible */
8045         if (mono_class_is_marshalbyref (cmethod->klass))
8046                 callvirt_this_arg = sp [0];
8047
8048         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
8049                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
8050                 CHECK_CFG_EXCEPTION;
8051         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
8052                            mono_method_check_inlining (cfg, cmethod) &&
8053                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
8054                 int costs;
8055
8056                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
8057                         cfg->real_offset += 5;
8058
8059                         *inline_costs += costs - 5;
8060                 } else {
8061                         INLINE_FAILURE ("inline failure");
8062                         // FIXME-VT: Clean this up
8063                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8064                                 GSHAREDVT_FAILURE(*ip);
8065                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
8066                 }
8067         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8068                 MonoInst *addr;
8069
8070                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
8071
8072                 if (cfg->llvm_only) {
8073                         // FIXME: Avoid initializing vtable_arg
8074                         emit_llvmonly_calli (cfg, fsig, sp, addr);
8075                 } else {
8076                         mono_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
8077                 }
8078         } else if (context_used &&
8079                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8080                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
8081                 MonoInst *cmethod_addr;
8082
8083                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
8084
8085                 if (cfg->llvm_only) {
8086                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
8087                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8088                         emit_llvmonly_calli (cfg, fsig, sp, addr);
8089                 } else {
8090                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
8091                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8092
8093                         mono_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
8094                 }
8095         } else {
8096                 INLINE_FAILURE ("ctor call");
8097                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
8098                                                                                   callvirt_this_arg, NULL, vtable_arg);
8099         }
8100  exception_exit:
8101         return;
8102 }
8103
8104 static void
8105 emit_setret (MonoCompile *cfg, MonoInst *val)
8106 {
8107         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
8108         MonoInst *ins;
8109
8110         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
8111                 MonoInst *ret_addr;
8112
8113                 if (!cfg->vret_addr) {
8114                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
8115                 } else {
8116                         EMIT_NEW_RETLOADA (cfg, ret_addr);
8117
8118                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
8119                         ins->klass = mono_class_from_mono_type (ret_type);
8120                 }
8121         } else {
8122 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
8123                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
8124                         MonoInst *iargs [1];
8125                         MonoInst *conv;
8126
8127                         iargs [0] = val;
8128                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
8129                         mono_arch_emit_setret (cfg, cfg->method, conv);
8130                 } else {
8131                         mono_arch_emit_setret (cfg, cfg->method, val);
8132                 }
8133 #else
8134                 mono_arch_emit_setret (cfg, cfg->method, val);
8135 #endif
8136         }
8137 }
8138
8139 /*
8140  * mono_method_to_ir:
8141  *
8142  *   Translate the .net IL into linear IR.
8143  */
8144 int
8145 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
8146                    MonoInst *return_var, MonoInst **inline_args, 
8147                    guint inline_offset, gboolean is_virtual_call)
8148 {
8149         MonoError error;
8150         MonoInst *ins, **sp, **stack_start;
8151         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
8152         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
8153         MonoMethod *cmethod, *method_definition;
8154         MonoInst **arg_array;
8155         MonoMethodHeader *header;
8156         MonoImage *image;
8157         guint32 token, ins_flag;
8158         MonoClass *klass;
8159         MonoClass *constrained_class = NULL;
8160         unsigned char *ip, *end, *target, *err_pos;
8161         MonoMethodSignature *sig;
8162         MonoGenericContext *generic_context = NULL;
8163         MonoGenericContainer *generic_container = NULL;
8164         MonoType **param_types;
8165         int i, n, start_new_bblock, dreg;
8166         int num_calls = 0, inline_costs = 0;
8167         int breakpoint_id = 0;
8168         guint num_args;
8169         GSList *class_inits = NULL;
8170         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
8171         int context_used;
8172         gboolean init_locals, seq_points, skip_dead_blocks;
8173         gboolean sym_seq_points = FALSE;
8174         MonoDebugMethodInfo *minfo;
8175         MonoBitSet *seq_point_locs = NULL;
8176         MonoBitSet *seq_point_set_locs = NULL;
8177
8178         cfg->disable_inline = is_jit_optimizer_disabled (method);
8179
8180         /* serialization and xdomain stuff may need access to private fields and methods */
8181         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
8182         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
8183         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
8184         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
8185         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
8186         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
8187
8188         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
8189         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
8190         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
8191         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
8192         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
8193
8194         image = method->klass->image;
8195         header = mono_method_get_header_checked (method, &cfg->error);
8196         if (!header) {
8197                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
8198                 goto exception_exit;
8199         }
8200         generic_container = mono_method_get_generic_container (method);
8201         sig = mono_method_signature (method);
8202         num_args = sig->hasthis + sig->param_count;
8203         ip = (unsigned char*)header->code;
8204         cfg->cil_start = ip;
8205         end = ip + header->code_size;
8206         cfg->stat_cil_code_size += header->code_size;
8207
8208         seq_points = cfg->gen_seq_points && cfg->method == method;
8209
8210         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
8211                 /* We could hit a seq point before attaching to the JIT (#8338) */
8212                 seq_points = FALSE;
8213         }
8214
8215         if (cfg->gen_sdb_seq_points && cfg->method == method) {
8216                 minfo = mono_debug_lookup_method (method);
8217                 if (minfo) {
8218                         MonoSymSeqPoint *sps;
8219                         int i, n_il_offsets;
8220
8221                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
8222                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8223                         seq_point_set_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8224                         sym_seq_points = TRUE;
8225                         for (i = 0; i < n_il_offsets; ++i) {
8226                                 if (sps [i].il_offset < header->code_size)
8227                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
8228                         }
8229                         g_free (sps);
8230                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
8231                         /* Methods without line number info like auto-generated property accessors */
8232                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8233                         seq_point_set_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
8234                         sym_seq_points = TRUE;
8235                 }
8236         }
8237
8238         /* 
8239          * Methods without init_locals set could cause asserts in various passes
8240          * (#497220). To work around this, we emit dummy initialization opcodes
8241          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
8242          * on some platforms.
8243          */
8244         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
8245                 init_locals = header->init_locals;
8246         else
8247                 init_locals = TRUE;
8248
8249         method_definition = method;
8250         while (method_definition->is_inflated) {
8251                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
8252                 method_definition = imethod->declaring;
8253         }
8254
8255         /* SkipVerification is not allowed if core-clr is enabled */
8256         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
8257                 dont_verify = TRUE;
8258                 dont_verify_stloc = TRUE;
8259         }
8260
8261         if (sig->is_inflated)
8262                 generic_context = mono_method_get_context (method);
8263         else if (generic_container)
8264                 generic_context = &generic_container->context;
8265         cfg->generic_context = generic_context;
8266
8267         if (!cfg->gshared)
8268                 g_assert (!sig->has_type_parameters);
8269
8270         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
8271                 g_assert (method->is_inflated);
8272                 g_assert (mono_method_get_context (method)->method_inst);
8273         }
8274         if (method->is_inflated && mono_method_get_context (method)->method_inst)
8275                 g_assert (sig->generic_param_count);
8276
8277         if (cfg->method == method) {
8278                 cfg->real_offset = 0;
8279         } else {
8280                 cfg->real_offset = inline_offset;
8281         }
8282
8283         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
8284         cfg->cil_offset_to_bb_len = header->code_size;
8285
8286         cfg->current_method = method;
8287
8288         if (cfg->verbose_level > 2)
8289                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
8290
8291         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
8292         if (sig->hasthis)
8293                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
8294         for (n = 0; n < sig->param_count; ++n)
8295                 param_types [n + sig->hasthis] = sig->params [n];
8296         cfg->arg_types = param_types;
8297
8298         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
8299         if (cfg->method == method) {
8300
8301                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
8302                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
8303
8304                 /* ENTRY BLOCK */
8305                 NEW_BBLOCK (cfg, start_bblock);
8306                 cfg->bb_entry = start_bblock;
8307                 start_bblock->cil_code = NULL;
8308                 start_bblock->cil_length = 0;
8309
8310                 /* EXIT BLOCK */
8311                 NEW_BBLOCK (cfg, end_bblock);
8312                 cfg->bb_exit = end_bblock;
8313                 end_bblock->cil_code = NULL;
8314                 end_bblock->cil_length = 0;
8315                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
8316                 g_assert (cfg->num_bblocks == 2);
8317
8318                 arg_array = cfg->args;
8319
8320                 if (header->num_clauses) {
8321                         cfg->spvars = g_hash_table_new (NULL, NULL);
8322                         cfg->exvars = g_hash_table_new (NULL, NULL);
8323                 }
8324                 /* handle exception clauses */
8325                 for (i = 0; i < header->num_clauses; ++i) {
8326                         MonoBasicBlock *try_bb;
8327                         MonoExceptionClause *clause = &header->clauses [i];
8328                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
8329
8330                         try_bb->real_offset = clause->try_offset;
8331                         try_bb->try_start = TRUE;
8332                         try_bb->region = ((i + 1) << 8) | clause->flags;
8333                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
8334                         tblock->real_offset = clause->handler_offset;
8335                         tblock->flags |= BB_EXCEPTION_HANDLER;
8336
8337                         /*
8338                          * Linking the try block with the EH block hinders inlining as we won't be able to 
8339                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
8340                          */
8341                         if (COMPILE_LLVM (cfg))
8342                                 link_bblock (cfg, try_bb, tblock);
8343
8344                         if (*(ip + clause->handler_offset) == CEE_POP)
8345                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
8346
8347                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
8348                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
8349                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
8350                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
8351                                 MONO_ADD_INS (tblock, ins);
8352
8353                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
8354                                         /* finally clauses already have a seq point */
8355                                         /* seq points for filter clauses are emitted below */
8356                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
8357                                         MONO_ADD_INS (tblock, ins);
8358                                 }
8359
8360                                 /* todo: is a fault block unsafe to optimize? */
8361                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
8362                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
8363                         }
8364
8365                         /*printf ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
8366                           while (p < end) {
8367                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
8368                           }*/
8369                         /* catch and filter blocks get the exception object on the stack */
8370                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
8371                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8372
8373                                 /* mostly like handle_stack_args (), but just sets the input args */
8374                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
8375                                 tblock->in_scount = 1;
8376                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
8377                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
8378
8379                                 cfg->cbb = tblock;
8380
8381 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
8382                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
8383                                 if (!cfg->compile_llvm) {
8384                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
8385                                         ins->dreg = tblock->in_stack [0]->dreg;
8386                                         MONO_ADD_INS (tblock, ins);
8387                                 }
8388 #else
8389                                 MonoInst *dummy_use;
8390
8391                                 /* 
8392                                  * Add a dummy use for the exvar so its liveness info will be
8393                                  * correct.
8394                                  */
8395                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
8396 #endif
8397
8398                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8399                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
8400                                         MONO_ADD_INS (tblock, ins);
8401                                 }
8402                                 
8403                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
8404                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
8405                                         tblock->flags |= BB_EXCEPTION_HANDLER;
8406                                         tblock->real_offset = clause->data.filter_offset;
8407                                         tblock->in_scount = 1;
8408                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
8409                                         /* The filter block shares the exvar with the handler block */
8410                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
8411                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
8412                                         MONO_ADD_INS (tblock, ins);
8413                                 }
8414                         }
8415
8416                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
8417                                         clause->data.catch_class &&
8418                                         cfg->gshared &&
8419                                         mono_class_check_context_used (clause->data.catch_class)) {
8420                                 /*
8421                                  * In shared generic code with catch
8422                                  * clauses containing type variables
8423                                  * the exception handling code has to
8424                                  * be able to get to the rgctx.
8425                                  * Therefore we have to make sure that
8426                                  * the vtable/mrgctx argument (for
8427                                  * static or generic methods) or the
8428                                  * "this" argument (for non-static
8429                                  * methods) are live.
8430                                  */
8431                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
8432                                                 mini_method_get_context (method)->method_inst ||
8433                                                 method->klass->valuetype) {
8434                                         mono_get_vtable_var (cfg);
8435                                 } else {
8436                                         MonoInst *dummy_use;
8437
8438                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
8439                                 }
8440                         }
8441                 }
8442         } else {
8443                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
8444                 cfg->cbb = start_bblock;
8445                 cfg->args = arg_array;
8446                 mono_save_args (cfg, sig, inline_args);
8447         }
8448
8449         /* FIRST CODE BLOCK */
8450         NEW_BBLOCK (cfg, tblock);
8451         tblock->cil_code = ip;
8452         cfg->cbb = tblock;
8453         cfg->ip = ip;
8454
8455         ADD_BBLOCK (cfg, tblock);
8456
8457         if (cfg->method == method) {
8458                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
8459                 if (breakpoint_id) {
8460                         MONO_INST_NEW (cfg, ins, OP_BREAK);
8461                         MONO_ADD_INS (cfg->cbb, ins);
8462                 }
8463         }
8464
8465         /* we use a separate basic block for the initialization code */
8466         NEW_BBLOCK (cfg, init_localsbb);
8467         cfg->bb_init = init_localsbb;
8468         init_localsbb->real_offset = cfg->real_offset;
8469         start_bblock->next_bb = init_localsbb;
8470         init_localsbb->next_bb = cfg->cbb;
8471         link_bblock (cfg, start_bblock, init_localsbb);
8472         link_bblock (cfg, init_localsbb, cfg->cbb);
8473                 
8474         cfg->cbb = init_localsbb;
8475
8476         if (cfg->gsharedvt && cfg->method == method) {
8477                 MonoGSharedVtMethodInfo *info;
8478                 MonoInst *var, *locals_var;
8479                 int dreg;
8480
8481                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
8482                 info->method = cfg->method;
8483                 info->count_entries = 16;
8484                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
8485                 cfg->gsharedvt_info = info;
8486
8487                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8488                 /* prevent it from being register allocated */
8489                 //var->flags |= MONO_INST_VOLATILE;
8490                 cfg->gsharedvt_info_var = var;
8491
8492                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
8493                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
8494
8495                 /* Allocate locals */
8496                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8497                 /* prevent it from being register allocated */
8498                 //locals_var->flags |= MONO_INST_VOLATILE;
8499                 cfg->gsharedvt_locals_var = locals_var;
8500
8501                 dreg = alloc_ireg (cfg);
8502                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
8503
8504                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8505                 ins->dreg = locals_var->dreg;
8506                 ins->sreg1 = dreg;
8507                 MONO_ADD_INS (cfg->cbb, ins);
8508                 cfg->gsharedvt_locals_var_ins = ins;
8509                 
8510                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8511                 /*
8512                 if (init_locals)
8513                         ins->flags |= MONO_INST_INIT;
8514                 */
8515         }
8516
8517         if (mono_security_core_clr_enabled ()) {
8518                 /* check if this is native code, e.g. an icall or a p/invoke */
8519                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
8520                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
8521                         if (wrapped) {
8522                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
8523                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
8524
8525                                 /* if this ia a native call then it can only be JITted from platform code */
8526                                 if ((icall || pinvk) && method->klass && method->klass->image) {
8527                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
8528                                                 MonoException *ex = icall ? mono_get_exception_security () : 
8529                                                         mono_get_exception_method_access ();
8530                                                 emit_throw_exception (cfg, ex);
8531                                         }
8532                                 }
8533                         }
8534                 }
8535         }
8536
8537         CHECK_CFG_EXCEPTION;
8538
8539         if (header->code_size == 0)
8540                 UNVERIFIED;
8541
8542         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
8543                 ip = err_pos;
8544                 UNVERIFIED;
8545         }
8546
8547         if (cfg->method == method)
8548                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
8549
8550         for (n = 0; n < header->num_locals; ++n) {
8551                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
8552                         UNVERIFIED;
8553         }
8554         class_inits = NULL;
8555
8556         /* We force the vtable variable here for all shared methods
8557            for the possibility that they might show up in a stack
8558            trace where their exact instantiation is needed. */
8559         if (cfg->gshared && method == cfg->method) {
8560                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
8561                                 mini_method_get_context (method)->method_inst ||
8562                                 method->klass->valuetype) {
8563                         mono_get_vtable_var (cfg);
8564                 } else {
8565                         /* FIXME: Is there a better way to do this?
8566                            We need the variable live for the duration
8567                            of the whole method. */
8568                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
8569                 }
8570         }
8571
8572         /* add a check for this != NULL to inlined methods */
8573         if (is_virtual_call) {
8574                 MonoInst *arg_ins;
8575
8576                 NEW_ARGLOAD (cfg, arg_ins, 0);
8577                 MONO_ADD_INS (cfg->cbb, arg_ins);
8578                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
8579         }
8580
8581         skip_dead_blocks = !dont_verify;
8582         if (skip_dead_blocks) {
8583                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
8584                 CHECK_CFG_ERROR;
8585                 g_assert (bb);
8586         }
8587
8588         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
8589         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
8590
8591         ins_flag = 0;
8592         start_new_bblock = 0;
8593         while (ip < end) {
8594                 if (cfg->method == method)
8595                         cfg->real_offset = ip - header->code;
8596                 else
8597                         cfg->real_offset = inline_offset;
8598                 cfg->ip = ip;
8599
8600                 context_used = 0;
8601
8602                 if (start_new_bblock) {
8603                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
8604                         if (start_new_bblock == 2) {
8605                                 g_assert (ip == tblock->cil_code);
8606                         } else {
8607                                 GET_BBLOCK (cfg, tblock, ip);
8608                         }
8609                         cfg->cbb->next_bb = tblock;
8610                         cfg->cbb = tblock;
8611                         start_new_bblock = 0;
8612                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
8613                                 if (cfg->verbose_level > 3)
8614                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
8615                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
8616                                 *sp++ = ins;
8617                         }
8618                         if (class_inits)
8619                                 g_slist_free (class_inits);
8620                         class_inits = NULL;
8621                 } else {
8622                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
8623                                 link_bblock (cfg, cfg->cbb, tblock);
8624                                 if (sp != stack_start) {
8625                                         handle_stack_args (cfg, stack_start, sp - stack_start);
8626                                         sp = stack_start;
8627                                         CHECK_UNVERIFIABLE (cfg);
8628                                 }
8629                                 cfg->cbb->next_bb = tblock;
8630                                 cfg->cbb = tblock;
8631                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
8632                                         if (cfg->verbose_level > 3)
8633                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
8634                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
8635                                         *sp++ = ins;
8636                                 }
8637                                 g_slist_free (class_inits);
8638                                 class_inits = NULL;
8639                         }
8640                 }
8641
8642                 if (skip_dead_blocks) {
8643                         int ip_offset = ip - header->code;
8644
8645                         if (ip_offset == bb->end)
8646                                 bb = bb->next;
8647
8648                         if (bb->dead) {
8649                                 int op_size = mono_opcode_size (ip, end);
8650                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
8651
8652                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
8653
8654                                 if (ip_offset + op_size == bb->end) {
8655                                         MONO_INST_NEW (cfg, ins, OP_NOP);
8656                                         MONO_ADD_INS (cfg->cbb, ins);
8657                                         start_new_bblock = 1;
8658                                 }
8659
8660                                 ip += op_size;
8661                                 continue;
8662                         }
8663                 }
8664                 /*
8665                  * Sequence points are points where the debugger can place a breakpoint.
8666                  * Currently, we generate these automatically at points where the IL
8667                  * stack is empty.
8668                  */
8669                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
8670                         /*
8671                          * Make methods interruptable at the beginning, and at the targets of
8672                          * backward branches.
8673                          * Also, do this at the start of every bblock in methods with clauses too,
8674                          * to be able to handle instructions with inprecise control flow like
8675                          * throw/endfinally.
8676                          * Backward branches are handled at the end of method-to-ir ().
8677                          */
8678                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
8679                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
8680
8681                         /* Avoid sequence points on empty IL like .volatile */
8682                         // FIXME: Enable this
8683                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
8684                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
8685                         if ((sp != stack_start) && !sym_seq_point)
8686                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
8687                         MONO_ADD_INS (cfg->cbb, ins);
8688
8689                         if (sym_seq_points)
8690                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
8691                 }
8692
8693                 cfg->cbb->real_offset = cfg->real_offset;
8694
8695                 if ((cfg->method == method) && cfg->coverage_info) {
8696                         guint32 cil_offset = ip - header->code;
8697                         cfg->coverage_info->data [cil_offset].cil_code = ip;
8698
8699                         /* TODO: Use an increment here */
8700 #if defined(TARGET_X86)
8701                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
8702                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
8703                         ins->inst_imm = 1;
8704                         MONO_ADD_INS (cfg->cbb, ins);
8705 #else
8706                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
8707                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
8708 #endif
8709                 }
8710
8711                 if (cfg->verbose_level > 3)
8712                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8713
8714                 switch (*ip) {
8715                 case CEE_NOP:
8716                         if (seq_points && !sym_seq_points && sp != stack_start) {
8717                                 /*
8718                                  * The C# compiler uses these nops to notify the JIT that it should
8719                                  * insert seq points.
8720                                  */
8721                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
8722                                 MONO_ADD_INS (cfg->cbb, ins);
8723                         }
8724                         if (cfg->keep_cil_nops)
8725                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
8726                         else
8727                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8728                         ip++;
8729                         MONO_ADD_INS (cfg->cbb, ins);
8730                         break;
8731                 case CEE_BREAK:
8732                         if (should_insert_brekpoint (cfg->method)) {
8733                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
8734                         } else {
8735                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8736                         }
8737                         ip++;
8738                         MONO_ADD_INS (cfg->cbb, ins);
8739                         break;
8740                 case CEE_LDARG_0:
8741                 case CEE_LDARG_1:
8742                 case CEE_LDARG_2:
8743                 case CEE_LDARG_3:
8744                         CHECK_STACK_OVF (1);
8745                         n = (*ip)-CEE_LDARG_0;
8746                         CHECK_ARG (n);
8747                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8748                         ip++;
8749                         *sp++ = ins;
8750                         break;
8751                 case CEE_LDLOC_0:
8752                 case CEE_LDLOC_1:
8753                 case CEE_LDLOC_2:
8754                 case CEE_LDLOC_3:
8755                         CHECK_STACK_OVF (1);
8756                         n = (*ip)-CEE_LDLOC_0;
8757                         CHECK_LOCAL (n);
8758                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8759                         ip++;
8760                         *sp++ = ins;
8761                         break;
8762                 case CEE_STLOC_0:
8763                 case CEE_STLOC_1:
8764                 case CEE_STLOC_2:
8765                 case CEE_STLOC_3: {
8766                         CHECK_STACK (1);
8767                         n = (*ip)-CEE_STLOC_0;
8768                         CHECK_LOCAL (n);
8769                         --sp;
8770                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8771                                 UNVERIFIED;
8772                         emit_stloc_ir (cfg, sp, header, n);
8773                         ++ip;
8774                         inline_costs += 1;
8775                         break;
8776                         }
8777                 case CEE_LDARG_S:
8778                         CHECK_OPSIZE (2);
8779                         CHECK_STACK_OVF (1);
8780                         n = ip [1];
8781                         CHECK_ARG (n);
8782                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8783                         *sp++ = ins;
8784                         ip += 2;
8785                         break;
8786                 case CEE_LDARGA_S:
8787                         CHECK_OPSIZE (2);
8788                         CHECK_STACK_OVF (1);
8789                         n = ip [1];
8790                         CHECK_ARG (n);
8791                         NEW_ARGLOADA (cfg, ins, n);
8792                         MONO_ADD_INS (cfg->cbb, ins);
8793                         *sp++ = ins;
8794                         ip += 2;
8795                         break;
8796                 case CEE_STARG_S:
8797                         CHECK_OPSIZE (2);
8798                         CHECK_STACK (1);
8799                         --sp;
8800                         n = ip [1];
8801                         CHECK_ARG (n);
8802                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8803                                 UNVERIFIED;
8804                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8805                         ip += 2;
8806                         break;
8807                 case CEE_LDLOC_S:
8808                         CHECK_OPSIZE (2);
8809                         CHECK_STACK_OVF (1);
8810                         n = ip [1];
8811                         CHECK_LOCAL (n);
8812                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8813                         *sp++ = ins;
8814                         ip += 2;
8815                         break;
8816                 case CEE_LDLOCA_S: {
8817                         unsigned char *tmp_ip;
8818                         CHECK_OPSIZE (2);
8819                         CHECK_STACK_OVF (1);
8820                         CHECK_LOCAL (ip [1]);
8821
8822                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8823                                 ip = tmp_ip;
8824                                 inline_costs += 1;
8825                                 break;
8826                         }
8827
8828                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8829                         *sp++ = ins;
8830                         ip += 2;
8831                         break;
8832                 }
8833                 case CEE_STLOC_S:
8834                         CHECK_OPSIZE (2);
8835                         CHECK_STACK (1);
8836                         --sp;
8837                         CHECK_LOCAL (ip [1]);
8838                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8839                                 UNVERIFIED;
8840                         emit_stloc_ir (cfg, sp, header, ip [1]);
8841                         ip += 2;
8842                         inline_costs += 1;
8843                         break;
8844                 case CEE_LDNULL:
8845                         CHECK_STACK_OVF (1);
8846                         EMIT_NEW_PCONST (cfg, ins, NULL);
8847                         ins->type = STACK_OBJ;
8848                         ++ip;
8849                         *sp++ = ins;
8850                         break;
8851                 case CEE_LDC_I4_M1:
8852                         CHECK_STACK_OVF (1);
8853                         EMIT_NEW_ICONST (cfg, ins, -1);
8854                         ++ip;
8855                         *sp++ = ins;
8856                         break;
8857                 case CEE_LDC_I4_0:
8858                 case CEE_LDC_I4_1:
8859                 case CEE_LDC_I4_2:
8860                 case CEE_LDC_I4_3:
8861                 case CEE_LDC_I4_4:
8862                 case CEE_LDC_I4_5:
8863                 case CEE_LDC_I4_6:
8864                 case CEE_LDC_I4_7:
8865                 case CEE_LDC_I4_8:
8866                         CHECK_STACK_OVF (1);
8867                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8868                         ++ip;
8869                         *sp++ = ins;
8870                         break;
8871                 case CEE_LDC_I4_S:
8872                         CHECK_OPSIZE (2);
8873                         CHECK_STACK_OVF (1);
8874                         ++ip;
8875                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8876                         ++ip;
8877                         *sp++ = ins;
8878                         break;
8879                 case CEE_LDC_I4:
8880                         CHECK_OPSIZE (5);
8881                         CHECK_STACK_OVF (1);
8882                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8883                         ip += 5;
8884                         *sp++ = ins;
8885                         break;
8886                 case CEE_LDC_I8:
8887                         CHECK_OPSIZE (9);
8888                         CHECK_STACK_OVF (1);
8889                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8890                         ins->type = STACK_I8;
8891                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8892                         ++ip;
8893                         ins->inst_l = (gint64)read64 (ip);
8894                         MONO_ADD_INS (cfg->cbb, ins);
8895                         ip += 8;
8896                         *sp++ = ins;
8897                         break;
8898                 case CEE_LDC_R4: {
8899                         float *f;
8900                         gboolean use_aotconst = FALSE;
8901
8902 #ifdef TARGET_POWERPC
8903                         /* FIXME: Clean this up */
8904                         if (cfg->compile_aot)
8905                                 use_aotconst = TRUE;
8906 #endif
8907
8908                         /* FIXME: we should really allocate this only late in the compilation process */
8909                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8910                         CHECK_OPSIZE (5);
8911                         CHECK_STACK_OVF (1);
8912
8913                         if (use_aotconst) {
8914                                 MonoInst *cons;
8915                                 int dreg;
8916
8917                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8918
8919                                 dreg = alloc_freg (cfg);
8920                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8921                                 ins->type = cfg->r4_stack_type;
8922                         } else {
8923                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8924                                 ins->type = cfg->r4_stack_type;
8925                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8926                                 ins->inst_p0 = f;
8927                                 MONO_ADD_INS (cfg->cbb, ins);
8928                         }
8929                         ++ip;
8930                         readr4 (ip, f);
8931                         ip += 4;
8932                         *sp++ = ins;                    
8933                         break;
8934                 }
8935                 case CEE_LDC_R8: {
8936                         double *d;
8937                         gboolean use_aotconst = FALSE;
8938
8939 #ifdef TARGET_POWERPC
8940                         /* FIXME: Clean this up */
8941                         if (cfg->compile_aot)
8942                                 use_aotconst = TRUE;
8943 #endif
8944
8945                         /* FIXME: we should really allocate this only late in the compilation process */
8946                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8947                         CHECK_OPSIZE (9);
8948                         CHECK_STACK_OVF (1);
8949
8950                         if (use_aotconst) {
8951                                 MonoInst *cons;
8952                                 int dreg;
8953
8954                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8955
8956                                 dreg = alloc_freg (cfg);
8957                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8958                                 ins->type = STACK_R8;
8959                         } else {
8960                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8961                                 ins->type = STACK_R8;
8962                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8963                                 ins->inst_p0 = d;
8964                                 MONO_ADD_INS (cfg->cbb, ins);
8965                         }
8966                         ++ip;
8967                         readr8 (ip, d);
8968                         ip += 8;
8969                         *sp++ = ins;
8970                         break;
8971                 }
8972                 case CEE_DUP: {
8973                         MonoInst *temp, *store;
8974                         CHECK_STACK (1);
8975                         CHECK_STACK_OVF (1);
8976                         sp--;
8977                         ins = *sp;
8978
8979                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8980                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8981
8982                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8983                         *sp++ = ins;
8984
8985                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8986                         *sp++ = ins;
8987
8988                         ++ip;
8989                         inline_costs += 2;
8990                         break;
8991                 }
8992                 case CEE_POP:
8993                         CHECK_STACK (1);
8994                         ip++;
8995                         --sp;
8996
8997 #ifdef TARGET_X86
8998                         if (sp [0]->type == STACK_R8)
8999                                 /* we need to pop the value from the x86 FP stack */
9000                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
9001 #endif
9002                         break;
9003                 case CEE_JMP: {
9004                         MonoCallInst *call;
9005                         MonoMethodSignature *fsig;
9006                         int i, n;
9007
9008                         INLINE_FAILURE ("jmp");
9009                         GSHAREDVT_FAILURE (*ip);
9010
9011                         CHECK_OPSIZE (5);
9012                         if (stack_start != sp)
9013                                 UNVERIFIED;
9014                         token = read32 (ip + 1);
9015                         /* FIXME: check the signature matches */
9016                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9017                         CHECK_CFG_ERROR;
9018  
9019                         if (cfg->gshared && mono_method_check_context_used (cmethod))
9020                                 GENERIC_SHARING_FAILURE (CEE_JMP);
9021
9022                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9023
9024                         fsig = mono_method_signature (cmethod);
9025                         n = fsig->param_count + fsig->hasthis;
9026                         if (cfg->llvm_only) {
9027                                 MonoInst **args;
9028
9029                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
9030                                 for (i = 0; i < n; ++i)
9031                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
9032                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
9033                                 /*
9034                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
9035                                  * have to emit a normal return since llvm expects it.
9036                                  */
9037                                 if (cfg->ret)
9038                                         emit_setret (cfg, ins);
9039                                 MONO_INST_NEW (cfg, ins, OP_BR);
9040                                 ins->inst_target_bb = end_bblock;
9041                                 MONO_ADD_INS (cfg->cbb, ins);
9042                                 link_bblock (cfg, cfg->cbb, end_bblock);
9043                                 ip += 5;
9044                                 break;
9045                         } else if (cfg->backend->have_op_tail_call) {
9046                                 /* Handle tail calls similarly to calls */
9047                                 DISABLE_AOT (cfg);
9048
9049                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
9050                                 call->method = cmethod;
9051                                 call->tail_call = TRUE;
9052                                 call->signature = mono_method_signature (cmethod);
9053                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
9054                                 call->inst.inst_p0 = cmethod;
9055                                 for (i = 0; i < n; ++i)
9056                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
9057
9058                                 mono_arch_emit_call (cfg, call);
9059                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
9060                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
9061                         } else {
9062                                 for (i = 0; i < num_args; ++i)
9063                                         /* Prevent arguments from being optimized away */
9064                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
9065
9066                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9067                                 ins = (MonoInst*)call;
9068                                 ins->inst_p0 = cmethod;
9069                                 MONO_ADD_INS (cfg->cbb, ins);
9070                         }
9071
9072                         ip += 5;
9073                         start_new_bblock = 1;
9074                         break;
9075                 }
9076                 case CEE_CALLI: {
9077                         MonoInst *addr;
9078                         MonoMethodSignature *fsig;
9079
9080                         CHECK_OPSIZE (5);
9081                         token = read32 (ip + 1);
9082
9083                         ins = NULL;
9084
9085                         //GSHAREDVT_FAILURE (*ip);
9086                         cmethod = NULL;
9087                         CHECK_STACK (1);
9088                         --sp;
9089                         addr = *sp;
9090                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
9091                         CHECK_CFG_ERROR;
9092
9093                         if (method->dynamic && fsig->pinvoke) {
9094                                 MonoInst *args [3];
9095
9096                                 /*
9097                                  * This is a call through a function pointer using a pinvoke
9098                                  * signature. Have to create a wrapper and call that instead.
9099                                  * FIXME: This is very slow, need to create a wrapper at JIT time
9100                                  * instead based on the signature.
9101                                  */
9102                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
9103                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
9104                                 args [2] = addr;
9105                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
9106                         }
9107
9108                         n = fsig->param_count + fsig->hasthis;
9109
9110                         CHECK_STACK (n);
9111
9112                         //g_assert (!virtual_ || fsig->hasthis);
9113
9114                         sp -= n;
9115
9116                         inline_costs += 10 * num_calls++;
9117
9118                         /*
9119                          * Making generic calls out of gsharedvt methods.
9120                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9121                          * patching gshared method addresses into a gsharedvt method.
9122                          */
9123                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
9124                                 /*
9125                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
9126                                  */
9127                                 MonoInst *callee = addr;
9128
9129                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
9130                                         /* Not tested */
9131                                         GSHAREDVT_FAILURE (*ip);
9132
9133                                 if (cfg->llvm_only)
9134                                         // FIXME:
9135                                         GSHAREDVT_FAILURE (*ip);
9136
9137                                 addr = emit_get_rgctx_sig (cfg, context_used,
9138                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
9139                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
9140                                 goto calli_end;
9141                         }
9142
9143                         /* Prevent inlining of methods with indirect calls */
9144                         INLINE_FAILURE ("indirect call");
9145
9146                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
9147                                 MonoJumpInfoType info_type;
9148                                 gpointer info_data;
9149
9150                                 /*
9151                                  * Instead of emitting an indirect call, emit a direct call
9152                                  * with the contents of the aotconst as the patch info.
9153                                  */
9154                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
9155                                         info_type = (MonoJumpInfoType)addr->inst_c1;
9156                                         info_data = addr->inst_p0;
9157                                 } else {
9158                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
9159                                         info_data = addr->inst_right->inst_left;
9160                                 }
9161
9162                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
9163                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
9164                                         NULLIFY_INS (addr);
9165                                         goto calli_end;
9166                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9167                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
9168                                         NULLIFY_INS (addr);
9169                                         goto calli_end;
9170                                 }
9171                         }
9172                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9173
9174                         calli_end:
9175
9176                         /* End of call, INS should contain the result of the call, if any */
9177
9178                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9179                                 g_assert (ins);
9180                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9181                         }
9182
9183                         CHECK_CFG_EXCEPTION;
9184
9185                         ip += 5;
9186                         ins_flag = 0;
9187                         constrained_class = NULL;
9188                         break;
9189                 }
9190                 case CEE_CALL:
9191                 case CEE_CALLVIRT: {
9192                         MonoInst *addr = NULL;
9193                         MonoMethodSignature *fsig = NULL;
9194                         int array_rank = 0;
9195                         int virtual_ = *ip == CEE_CALLVIRT;
9196                         gboolean pass_imt_from_rgctx = FALSE;
9197                         MonoInst *imt_arg = NULL;
9198                         MonoInst *keep_this_alive = NULL;
9199                         gboolean pass_vtable = FALSE;
9200                         gboolean pass_mrgctx = FALSE;
9201                         MonoInst *vtable_arg = NULL;
9202                         gboolean check_this = FALSE;
9203                         gboolean supported_tail_call = FALSE;
9204                         gboolean tail_call = FALSE;
9205                         gboolean need_seq_point = FALSE;
9206                         guint32 call_opcode = *ip;
9207                         gboolean emit_widen = TRUE;
9208                         gboolean push_res = TRUE;
9209                         gboolean skip_ret = FALSE;
9210                         gboolean delegate_invoke = FALSE;
9211                         gboolean direct_icall = FALSE;
9212                         gboolean constrained_partial_call = FALSE;
9213                         MonoMethod *cil_method;
9214
9215                         CHECK_OPSIZE (5);
9216                         token = read32 (ip + 1);
9217
9218                         ins = NULL;
9219
9220                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9221                         CHECK_CFG_ERROR;
9222
9223                         cil_method = cmethod;
9224                                 
9225                         if (constrained_class) {
9226                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
9227                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
9228                                                 g_assert (!cmethod->klass->valuetype);
9229                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
9230                                                         constrained_partial_call = TRUE;
9231                                         }
9232                                 }
9233
9234                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
9235                                         if (cfg->verbose_level > 2)
9236                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
9237                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
9238                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
9239                                                   cfg->gshared)) {
9240                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
9241                                                 CHECK_CFG_ERROR;
9242                                         }
9243                                 } else {
9244                                         if (cfg->verbose_level > 2)
9245                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
9246
9247                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
9248                                                 /* 
9249                                                  * This is needed since get_method_constrained can't find 
9250                                                  * the method in klass representing a type var.
9251                                                  * The type var is guaranteed to be a reference type in this
9252                                                  * case.
9253                                                  */
9254                                                 if (!mini_is_gsharedvt_klass (constrained_class))
9255                                                         g_assert (!cmethod->klass->valuetype);
9256                                         } else {
9257                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
9258                                                 CHECK_CFG_ERROR;
9259                                         }
9260                                 }
9261                         }
9262                                         
9263                         if (!dont_verify && !cfg->skip_visibility) {
9264                                 MonoMethod *target_method = cil_method;
9265                                 if (method->is_inflated) {
9266                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
9267                                         CHECK_CFG_ERROR;
9268                                 }
9269                                 if (!mono_method_can_access_method (method_definition, target_method) &&
9270                                         !mono_method_can_access_method (method, cil_method))
9271                                         METHOD_ACCESS_FAILURE (method, cil_method);
9272                         }
9273
9274                         if (mono_security_core_clr_enabled ())
9275                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
9276
9277                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
9278                                 /* MS.NET seems to silently convert this to a callvirt */
9279                                 virtual_ = 1;
9280
9281                         {
9282                                 /*
9283                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
9284                                  * converts to a callvirt.
9285                                  *
9286                                  * tests/bug-515884.il is an example of this behavior
9287                                  */
9288                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
9289                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
9290                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
9291                                         virtual_ = 1;
9292                         }
9293
9294                         if (!cmethod->klass->inited)
9295                                 if (!mono_class_init (cmethod->klass))
9296                                         TYPE_LOAD_ERROR (cmethod->klass);
9297
9298                         fsig = mono_method_signature (cmethod);
9299                         if (!fsig)
9300                                 LOAD_ERROR;
9301                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
9302                                 mini_class_is_system_array (cmethod->klass)) {
9303                                 array_rank = cmethod->klass->rank;
9304                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
9305                                 direct_icall = TRUE;
9306                         } else if (fsig->pinvoke) {
9307                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9308                                 fsig = mono_method_signature (wrapper);
9309                         } else if (constrained_class) {
9310                         } else {
9311                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9312                                 CHECK_CFG_ERROR;
9313                         }
9314
9315                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
9316                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
9317
9318                         /* See code below */
9319                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
9320                                 MonoBasicBlock *tbb;
9321
9322                                 GET_BBLOCK (cfg, tbb, ip + 5);
9323                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9324                                         /*
9325                                          * We want to extend the try block to cover the call, but we can't do it if the
9326                                          * call is made directly since its followed by an exception check.
9327                                          */
9328                                         direct_icall = FALSE;
9329                                 }
9330                         }
9331
9332                         mono_save_token_info (cfg, image, token, cil_method);
9333
9334                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
9335                                 need_seq_point = TRUE;
9336
9337                         /* Don't support calls made using type arguments for now */
9338                         /*
9339                           if (cfg->gsharedvt) {
9340                           if (mini_is_gsharedvt_signature (fsig))
9341                           GSHAREDVT_FAILURE (*ip);
9342                           }
9343                         */
9344
9345                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
9346                                 g_assert_not_reached ();
9347
9348                         n = fsig->param_count + fsig->hasthis;
9349
9350                         if (!cfg->gshared && cmethod->klass->generic_container)
9351                                 UNVERIFIED;
9352
9353                         if (!cfg->gshared)
9354                                 g_assert (!mono_method_check_context_used (cmethod));
9355
9356                         CHECK_STACK (n);
9357
9358                         //g_assert (!virtual_ || fsig->hasthis);
9359
9360                         sp -= n;
9361
9362                         /*
9363                          * We have the `constrained.' prefix opcode.
9364                          */
9365                         if (constrained_class) {
9366                                 if (mini_is_gsharedvt_klass (constrained_class)) {
9367                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
9368                                                 /* The 'Own method' case below */
9369                                         } else if (cmethod->klass->image != mono_defaults.corlib && !(cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) && !cmethod->klass->valuetype) {
9370                                                 /* 'The type parameter is instantiated as a reference type' case below. */
9371                                         } else {
9372                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
9373                                                 CHECK_CFG_EXCEPTION;
9374                                                 g_assert (ins);
9375                                                 goto call_end;
9376                                         }
9377                                 }
9378
9379                                 if (constrained_partial_call) {
9380                                         gboolean need_box = TRUE;
9381
9382                                         /*
9383                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
9384                                          * called method is not known at compile time either. The called method could end up being
9385                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
9386                                          * to box the receiver.
9387                                          * A simple solution would be to box always and make a normal virtual call, but that would
9388                                          * be bad performance wise.
9389                                          */
9390                                         if (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE && cmethod->klass->generic_class) {
9391                                                 /*
9392                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
9393                                                  */
9394                                                 need_box = FALSE;
9395                                         }
9396
9397                                         if (!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
9398                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
9399                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9400                                                 ins->klass = constrained_class;
9401                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9402                                                 CHECK_CFG_EXCEPTION;
9403                                         } else if (need_box) {
9404                                                 MonoInst *box_type;
9405                                                 MonoBasicBlock *is_ref_bb, *end_bb;
9406                                                 MonoInst *nonbox_call;
9407
9408                                                 /*
9409                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
9410                                                  * if needed.
9411                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
9412                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
9413                                                  */
9414                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
9415
9416                                                 NEW_BBLOCK (cfg, is_ref_bb);
9417                                                 NEW_BBLOCK (cfg, end_bb);
9418
9419                                                 box_type = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_BOX_TYPE);
9420                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
9421                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
9422
9423                                                 /* Non-ref case */
9424                                                 nonbox_call = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9425
9426                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
9427
9428                                                 /* Ref case */
9429                                                 MONO_START_BB (cfg, is_ref_bb);
9430                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9431                                                 ins->klass = constrained_class;
9432                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9433                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9434
9435                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
9436
9437                                                 MONO_START_BB (cfg, end_bb);
9438                                                 cfg->cbb = end_bb;
9439
9440                                                 nonbox_call->dreg = ins->dreg;
9441                                                 goto call_end;
9442                                         } else {
9443                                                 g_assert (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE);
9444                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
9445                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9446                                                 goto call_end;
9447                                         }
9448                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
9449                                         /*
9450                                          * The type parameter is instantiated as a valuetype,
9451                                          * but that type doesn't override the method we're
9452                                          * calling, so we need to box `this'.
9453                                          */
9454                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9455                                         ins->klass = constrained_class;
9456                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9457                                         CHECK_CFG_EXCEPTION;
9458                                 } else if (!constrained_class->valuetype) {
9459                                         int dreg = alloc_ireg_ref (cfg);
9460
9461                                         /*
9462                                          * The type parameter is instantiated as a reference
9463                                          * type.  We have a managed pointer on the stack, so
9464                                          * we need to dereference it here.
9465                                          */
9466                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
9467                                         ins->type = STACK_OBJ;
9468                                         sp [0] = ins;
9469                                 } else {
9470                                         if (cmethod->klass->valuetype) {
9471                                                 /* Own method */
9472                                         } else {
9473                                                 /* Interface method */
9474                                                 int ioffset, slot;
9475
9476                                                 mono_class_setup_vtable (constrained_class);
9477                                                 CHECK_TYPELOAD (constrained_class);
9478                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
9479                                                 if (ioffset == -1)
9480                                                         TYPE_LOAD_ERROR (constrained_class);
9481                                                 slot = mono_method_get_vtable_slot (cmethod);
9482                                                 if (slot == -1)
9483                                                         TYPE_LOAD_ERROR (cmethod->klass);
9484                                                 cmethod = constrained_class->vtable [ioffset + slot];
9485
9486                                                 if (cmethod->klass == mono_defaults.enum_class) {
9487                                                         /* Enum implements some interfaces, so treat this as the first case */
9488                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
9489                                                         ins->klass = constrained_class;
9490                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
9491                                                         CHECK_CFG_EXCEPTION;
9492                                                 }
9493                                         }
9494                                         virtual_ = 0;
9495                                 }
9496                                 constrained_class = NULL;
9497                         }
9498
9499                         if (check_call_signature (cfg, fsig, sp))
9500                                 UNVERIFIED;
9501
9502                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
9503                                 delegate_invoke = TRUE;
9504
9505                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
9506                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9507                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9508                                         emit_widen = FALSE;
9509                                 }
9510
9511                                 goto call_end;
9512                         }
9513
9514                         /* 
9515                          * If the callee is a shared method, then its static cctor
9516                          * might not get called after the call was patched.
9517                          */
9518                         if (cfg->gshared && cmethod->klass != method->klass && cmethod->klass->generic_class && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
9519                                 emit_class_init (cfg, cmethod->klass);
9520                                 CHECK_TYPELOAD (cmethod->klass);
9521                         }
9522
9523                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
9524
9525                         if (cfg->gshared) {
9526                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
9527
9528                                 context_used = mini_method_check_context_used (cfg, cmethod);
9529
9530                                 if (context_used && (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
9531                                         /* Generic method interface
9532                                            calls are resolved via a
9533                                            helper function and don't
9534                                            need an imt. */
9535                                         if (!cmethod_context || !cmethod_context->method_inst)
9536                                                 pass_imt_from_rgctx = TRUE;
9537                                 }
9538
9539                                 /*
9540                                  * If a shared method calls another
9541                                  * shared method then the caller must
9542                                  * have a generic sharing context
9543                                  * because the magic trampoline
9544                                  * requires it.  FIXME: We shouldn't
9545                                  * have to force the vtable/mrgctx
9546                                  * variable here.  Instead there
9547                                  * should be a flag in the cfg to
9548                                  * request a generic sharing context.
9549                                  */
9550                                 if (context_used &&
9551                                                 ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype))
9552                                         mono_get_vtable_var (cfg);
9553                         }
9554
9555                         if (pass_vtable) {
9556                                 if (context_used) {
9557                                         vtable_arg = emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
9558                                 } else {
9559                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
9560
9561                                         CHECK_TYPELOAD (cmethod->klass);
9562                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
9563                                 }
9564                         }
9565
9566                         if (pass_mrgctx) {
9567                                 g_assert (!vtable_arg);
9568
9569                                 if (!cfg->compile_aot) {
9570                                         /* 
9571                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
9572                                          * for type load errors before.
9573                                          */
9574                                         mono_class_setup_vtable (cmethod->klass);
9575                                         CHECK_TYPELOAD (cmethod->klass);
9576                                 }
9577
9578                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
9579
9580                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
9581                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
9582                                          MONO_METHOD_IS_FINAL (cmethod)) &&
9583                                         !mono_class_is_marshalbyref (cmethod->klass)) {
9584                                         if (virtual_)
9585                                                 check_this = TRUE;
9586                                         virtual_ = 0;
9587                                 }
9588                         }
9589
9590                         if (pass_imt_from_rgctx) {
9591                                 g_assert (!pass_vtable);
9592
9593                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9594                                         cmethod, MONO_RGCTX_INFO_METHOD);
9595                         }
9596
9597                         if (check_this)
9598                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9599
9600                         /* Calling virtual generic methods */
9601                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
9602                             !(MONO_METHOD_IS_FINAL (cmethod) && 
9603                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
9604                             fsig->generic_param_count && 
9605                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
9606                                 !cfg->llvm_only) {
9607                                 MonoInst *this_temp, *this_arg_temp, *store;
9608                                 MonoInst *iargs [4];
9609
9610                                 g_assert (fsig->is_inflated);
9611
9612                                 /* Prevent inlining of methods that contain indirect calls */
9613                                 INLINE_FAILURE ("virtual generic call");
9614
9615                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
9616                                         GSHAREDVT_FAILURE (*ip);
9617
9618                                 if (cfg->backend->have_generalized_imt_thunk && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
9619                                         g_assert (!imt_arg);
9620                                         if (!context_used)
9621                                                 g_assert (cmethod->is_inflated);
9622                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
9623                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9624                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
9625                                 } else {
9626                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
9627                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
9628                                         MONO_ADD_INS (cfg->cbb, store);
9629
9630                                         /* FIXME: This should be a managed pointer */
9631                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
9632
9633                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
9634                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
9635                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
9636                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
9637                                         addr = mono_emit_jit_icall (cfg,
9638                                                                                                 mono_helper_compile_generic_method, iargs);
9639
9640                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
9641
9642                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9643                                 }
9644
9645                                 goto call_end;
9646                         }
9647
9648                         /*
9649                          * Implement a workaround for the inherent races involved in locking:
9650                          * Monitor.Enter ()
9651                          * try {
9652                          * } finally {
9653                          *    Monitor.Exit ()
9654                          * }
9655                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
9656                          * try block, the Exit () won't be executed, see:
9657                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
9658                          * To work around this, we extend such try blocks to include the last x bytes
9659                          * of the Monitor.Enter () call.
9660                          */
9661                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
9662                                 MonoBasicBlock *tbb;
9663
9664                                 GET_BBLOCK (cfg, tbb, ip + 5);
9665                                 /* 
9666                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
9667                                  * from Monitor.Enter like ArgumentNullException.
9668                                  */
9669                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9670                                         /* Mark this bblock as needing to be extended */
9671                                         tbb->extend_try_block = TRUE;
9672                                 }
9673                         }
9674
9675                         /* Conversion to a JIT intrinsic */
9676                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
9677                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9678                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9679                                         emit_widen = FALSE;
9680                                 }
9681                                 goto call_end;
9682                         }
9683                         CHECK_CFG_ERROR;
9684                         
9685                         /* Inlining */
9686                         if ((cfg->opt & MONO_OPT_INLINE) &&
9687                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
9688                             mono_method_check_inlining (cfg, cmethod)) {
9689                                 int costs;
9690                                 gboolean always = FALSE;
9691
9692                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9693                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9694                                         /* Prevent inlining of methods that call wrappers */
9695                                         INLINE_FAILURE ("wrapper call");
9696                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
9697                                         always = TRUE;
9698                                 }
9699
9700                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
9701                                 if (costs) {
9702                                         cfg->real_offset += 5;
9703
9704                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9705                                                 /* *sp is already set by inline_method */
9706                                                 sp++;
9707                                                 push_res = FALSE;
9708                                         }
9709
9710                                         inline_costs += costs;
9711
9712                                         goto call_end;
9713                                 }
9714                         }
9715
9716                         /* Tail recursion elimination */
9717                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
9718                                 gboolean has_vtargs = FALSE;
9719                                 int i;
9720
9721                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9722                                 INLINE_FAILURE ("tail call");
9723
9724                                 /* keep it simple */
9725                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
9726                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
9727                                                 has_vtargs = TRUE;
9728                                 }
9729
9730                                 if (!has_vtargs) {
9731                                         for (i = 0; i < n; ++i)
9732                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9733                                         MONO_INST_NEW (cfg, ins, OP_BR);
9734                                         MONO_ADD_INS (cfg->cbb, ins);
9735                                         tblock = start_bblock->out_bb [0];
9736                                         link_bblock (cfg, cfg->cbb, tblock);
9737                                         ins->inst_target_bb = tblock;
9738                                         start_new_bblock = 1;
9739
9740                                         /* skip the CEE_RET, too */
9741                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
9742                                                 skip_ret = TRUE;
9743                                         push_res = FALSE;
9744                                         goto call_end;
9745                                 }
9746                         }
9747
9748                         inline_costs += 10 * num_calls++;
9749
9750                         /*
9751                          * Making generic calls out of gsharedvt methods.
9752                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9753                          * patching gshared method addresses into a gsharedvt method.
9754                          */
9755                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || cmethod->klass->generic_class) &&
9756                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9757                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9758                                 MonoRgctxInfoType info_type;
9759
9760                                 if (virtual_) {
9761                                         //if (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
9762                                                 //GSHAREDVT_FAILURE (*ip);
9763                                         // disable for possible remoting calls
9764                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9765                                                 GSHAREDVT_FAILURE (*ip);
9766                                         if (fsig->generic_param_count) {
9767                                                 /* virtual generic call */
9768                                                 g_assert (!imt_arg);
9769                                                 /* Same as the virtual generic case above */
9770                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9771                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9772                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9773                                                 vtable_arg = NULL;
9774                                         } else if ((cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) && !imt_arg) {
9775                                                 /* This can happen when we call a fully instantiated iface method */
9776                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9777                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9778                                                 vtable_arg = NULL;
9779                                         }
9780                                 }
9781
9782                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9783                                         keep_this_alive = sp [0];
9784
9785                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9786                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9787                                 else
9788                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9789                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9790
9791                                 if (cfg->llvm_only) {
9792                                         // FIXME: Avoid initializing vtable_arg
9793                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9794                                 } else {
9795                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9796                                 }
9797                                 goto call_end;
9798                         }
9799
9800                         /* Generic sharing */
9801
9802                         /*
9803                          * Use this if the callee is gsharedvt sharable too, since
9804                          * at runtime we might find an instantiation so the call cannot
9805                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9806                          */
9807                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9808                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9809                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9810                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9811                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9812                                 INLINE_FAILURE ("gshared");
9813
9814                                 g_assert (cfg->gshared && cmethod);
9815                                 g_assert (!addr);
9816
9817                                 /*
9818                                  * We are compiling a call to a
9819                                  * generic method from shared code,
9820                                  * which means that we have to look up
9821                                  * the method in the rgctx and do an
9822                                  * indirect call.
9823                                  */
9824                                 if (fsig->hasthis)
9825                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9826
9827                                 if (cfg->llvm_only) {
9828                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9829                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9830                                         else
9831                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9832                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9833                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9834                                 } else {
9835                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9836                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9837                                 }
9838                                 goto call_end;
9839                         }
9840
9841                         /* Direct calls to icalls */
9842                         if (direct_icall) {
9843                                 MonoMethod *wrapper;
9844                                 int costs;
9845
9846                                 /* Inline the wrapper */
9847                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9848
9849                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9850                                 g_assert (costs > 0);
9851                                 cfg->real_offset += 5;
9852
9853                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9854                                         /* *sp is already set by inline_method */
9855                                         sp++;
9856                                         push_res = FALSE;
9857                                 }
9858
9859                                 inline_costs += costs;
9860
9861                                 goto call_end;
9862                         }
9863                                         
9864                         /* Array methods */
9865                         if (array_rank) {
9866                                 MonoInst *addr;
9867
9868                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9869                                         MonoInst *val = sp [fsig->param_count];
9870
9871                                         if (val->type == STACK_OBJ) {
9872                                                 MonoInst *iargs [2];
9873
9874                                                 iargs [0] = sp [0];
9875                                                 iargs [1] = val;
9876                                                 
9877                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9878                                         }
9879                                         
9880                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9881                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9882                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !(val->opcode == OP_PCONST && val->inst_c0 == 0))
9883                                                 emit_write_barrier (cfg, addr, val);
9884                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9885                                                 GSHAREDVT_FAILURE (*ip);
9886                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9887                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9888
9889                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9890                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9891                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9892                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9893                                         CHECK_TYPELOAD (cmethod->klass);
9894                                         
9895                                         readonly = FALSE;
9896                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9897                                         ins = addr;
9898                                 } else {
9899                                         g_assert_not_reached ();
9900                                 }
9901
9902                                 emit_widen = FALSE;
9903                                 goto call_end;
9904                         }
9905
9906                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9907                         if (ins)
9908                                 goto call_end;
9909
9910                         /* Tail prefix / tail call optimization */
9911
9912                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9913                         /* FIXME: runtime generic context pointer for jumps? */
9914                         /* FIXME: handle this for generic sharing eventually */
9915                         if ((ins_flag & MONO_INST_TAILCALL) &&
9916                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9917                                 supported_tail_call = TRUE;
9918
9919                         if (supported_tail_call) {
9920                                 MonoCallInst *call;
9921
9922                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9923                                 INLINE_FAILURE ("tail call");
9924
9925                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9926
9927                                 if (cfg->backend->have_op_tail_call) {
9928                                         /* Handle tail calls similarly to normal calls */
9929                                         tail_call = TRUE;
9930                                 } else {
9931                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9932
9933                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9934                                         call->tail_call = TRUE;
9935                                         call->method = cmethod;
9936                                         call->signature = mono_method_signature (cmethod);
9937
9938                                         /*
9939                                          * We implement tail calls by storing the actual arguments into the 
9940                                          * argument variables, then emitting a CEE_JMP.
9941                                          */
9942                                         for (i = 0; i < n; ++i) {
9943                                                 /* Prevent argument from being register allocated */
9944                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9945                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9946                                         }
9947                                         ins = (MonoInst*)call;
9948                                         ins->inst_p0 = cmethod;
9949                                         ins->inst_p1 = arg_array [0];
9950                                         MONO_ADD_INS (cfg->cbb, ins);
9951                                         link_bblock (cfg, cfg->cbb, end_bblock);
9952                                         start_new_bblock = 1;
9953
9954                                         // FIXME: Eliminate unreachable epilogs
9955
9956                                         /*
9957                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9958                                          * only reachable from this call.
9959                                          */
9960                                         GET_BBLOCK (cfg, tblock, ip + 5);
9961                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9962                                                 skip_ret = TRUE;
9963                                         push_res = FALSE;
9964
9965                                         goto call_end;
9966                                 }
9967                         }
9968
9969                         /* 
9970                          * Synchronized wrappers.
9971                          * Its hard to determine where to replace a method with its synchronized
9972                          * wrapper without causing an infinite recursion. The current solution is
9973                          * to add the synchronized wrapper in the trampolines, and to
9974                          * change the called method to a dummy wrapper, and resolve that wrapper
9975                          * to the real method in mono_jit_compile_method ().
9976                          */
9977                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9978                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9979                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9980                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9981                         }
9982
9983                         /*
9984                          * Virtual calls in llvm-only mode.
9985                          */
9986                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9987                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9988                                 goto call_end;
9989                         }
9990
9991                         /* Common call */
9992                         INLINE_FAILURE ("call");
9993                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9994                                                                                           imt_arg, vtable_arg);
9995
9996                         if (tail_call && !cfg->llvm_only) {
9997                                 link_bblock (cfg, cfg->cbb, end_bblock);
9998                                 start_new_bblock = 1;
9999
10000                                 // FIXME: Eliminate unreachable epilogs
10001
10002                                 /*
10003                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
10004                                  * only reachable from this call.
10005                                  */
10006                                 GET_BBLOCK (cfg, tblock, ip + 5);
10007                                 if (tblock == cfg->cbb || tblock->in_count == 0)
10008                                         skip_ret = TRUE;
10009                                 push_res = FALSE;
10010                         }
10011
10012                         call_end:
10013
10014                         /* End of call, INS should contain the result of the call, if any */
10015
10016                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
10017                                 g_assert (ins);
10018                                 if (emit_widen)
10019                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
10020                                 else
10021                                         *sp++ = ins;
10022                         }
10023
10024                         if (keep_this_alive) {
10025                                 MonoInst *dummy_use;
10026
10027                                 /* See mono_emit_method_call_full () */
10028                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
10029                         }
10030
10031                         CHECK_CFG_EXCEPTION;
10032
10033                         ip += 5;
10034                         if (skip_ret) {
10035                                 g_assert (*ip == CEE_RET);
10036                                 ip += 1;
10037                         }
10038                         ins_flag = 0;
10039                         constrained_class = NULL;
10040                         if (need_seq_point)
10041                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10042                         break;
10043                 }
10044                 case CEE_RET:
10045                         if (cfg->method != method) {
10046                                 /* return from inlined method */
10047                                 /* 
10048                                  * If in_count == 0, that means the ret is unreachable due to
10049                                  * being preceeded by a throw. In that case, inline_method () will
10050                                  * handle setting the return value 
10051                                  * (test case: test_0_inline_throw ()).
10052                                  */
10053                                 if (return_var && cfg->cbb->in_count) {
10054                                         MonoType *ret_type = mono_method_signature (method)->ret;
10055
10056                                         MonoInst *store;
10057                                         CHECK_STACK (1);
10058                                         --sp;
10059
10060                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
10061                                                 UNVERIFIED;
10062
10063                                         //g_assert (returnvar != -1);
10064                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
10065                                         cfg->ret_var_set = TRUE;
10066                                 } 
10067                         } else {
10068                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
10069
10070                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
10071                                         emit_pop_lmf (cfg);
10072
10073                                 if (cfg->ret) {
10074                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
10075
10076                                         if (seq_points && !sym_seq_points) {
10077                                                 /* 
10078                                                  * Place a seq point here too even through the IL stack is not
10079                                                  * empty, so a step over on
10080                                                  * call <FOO>
10081                                                  * ret
10082                                                  * will work correctly.
10083                                                  */
10084                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
10085                                                 MONO_ADD_INS (cfg->cbb, ins);
10086                                         }
10087
10088                                         g_assert (!return_var);
10089                                         CHECK_STACK (1);
10090                                         --sp;
10091
10092                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
10093                                                 UNVERIFIED;
10094
10095                                         emit_setret (cfg, *sp);
10096                                 }
10097                         }
10098                         if (sp != stack_start)
10099                                 UNVERIFIED;
10100                         MONO_INST_NEW (cfg, ins, OP_BR);
10101                         ip++;
10102                         ins->inst_target_bb = end_bblock;
10103                         MONO_ADD_INS (cfg->cbb, ins);
10104                         link_bblock (cfg, cfg->cbb, end_bblock);
10105                         start_new_bblock = 1;
10106                         break;
10107                 case CEE_BR_S:
10108                         CHECK_OPSIZE (2);
10109                         MONO_INST_NEW (cfg, ins, OP_BR);
10110                         ip++;
10111                         target = ip + 1 + (signed char)(*ip);
10112                         ++ip;
10113                         GET_BBLOCK (cfg, tblock, target);
10114                         link_bblock (cfg, cfg->cbb, tblock);
10115                         ins->inst_target_bb = tblock;
10116                         if (sp != stack_start) {
10117                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10118                                 sp = stack_start;
10119                                 CHECK_UNVERIFIABLE (cfg);
10120                         }
10121                         MONO_ADD_INS (cfg->cbb, ins);
10122                         start_new_bblock = 1;
10123                         inline_costs += BRANCH_COST;
10124                         break;
10125                 case CEE_BEQ_S:
10126                 case CEE_BGE_S:
10127                 case CEE_BGT_S:
10128                 case CEE_BLE_S:
10129                 case CEE_BLT_S:
10130                 case CEE_BNE_UN_S:
10131                 case CEE_BGE_UN_S:
10132                 case CEE_BGT_UN_S:
10133                 case CEE_BLE_UN_S:
10134                 case CEE_BLT_UN_S:
10135                         CHECK_OPSIZE (2);
10136                         CHECK_STACK (2);
10137                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
10138                         ip++;
10139                         target = ip + 1 + *(signed char*)ip;
10140                         ip++;
10141
10142                         ADD_BINCOND (NULL);
10143
10144                         sp = stack_start;
10145                         inline_costs += BRANCH_COST;
10146                         break;
10147                 case CEE_BR:
10148                         CHECK_OPSIZE (5);
10149                         MONO_INST_NEW (cfg, ins, OP_BR);
10150                         ip++;
10151
10152                         target = ip + 4 + (gint32)read32(ip);
10153                         ip += 4;
10154                         GET_BBLOCK (cfg, tblock, target);
10155                         link_bblock (cfg, cfg->cbb, tblock);
10156                         ins->inst_target_bb = tblock;
10157                         if (sp != stack_start) {
10158                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10159                                 sp = stack_start;
10160                                 CHECK_UNVERIFIABLE (cfg);
10161                         }
10162
10163                         MONO_ADD_INS (cfg->cbb, ins);
10164
10165                         start_new_bblock = 1;
10166                         inline_costs += BRANCH_COST;
10167                         break;
10168                 case CEE_BRFALSE_S:
10169                 case CEE_BRTRUE_S:
10170                 case CEE_BRFALSE:
10171                 case CEE_BRTRUE: {
10172                         MonoInst *cmp;
10173                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
10174                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
10175                         guint32 opsize = is_short ? 1 : 4;
10176
10177                         CHECK_OPSIZE (opsize);
10178                         CHECK_STACK (1);
10179                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
10180                                 UNVERIFIED;
10181                         ip ++;
10182                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
10183                         ip += opsize;
10184
10185                         sp--;
10186
10187                         GET_BBLOCK (cfg, tblock, target);
10188                         link_bblock (cfg, cfg->cbb, tblock);
10189                         GET_BBLOCK (cfg, tblock, ip);
10190                         link_bblock (cfg, cfg->cbb, tblock);
10191
10192                         if (sp != stack_start) {
10193                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10194                                 CHECK_UNVERIFIABLE (cfg);
10195                         }
10196
10197                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
10198                         cmp->sreg1 = sp [0]->dreg;
10199                         type_from_op (cfg, cmp, sp [0], NULL);
10200                         CHECK_TYPE (cmp);
10201
10202 #if SIZEOF_REGISTER == 4
10203                         if (cmp->opcode == OP_LCOMPARE_IMM) {
10204                                 /* Convert it to OP_LCOMPARE */
10205                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
10206                                 ins->type = STACK_I8;
10207                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
10208                                 ins->inst_l = 0;
10209                                 MONO_ADD_INS (cfg->cbb, ins);
10210                                 cmp->opcode = OP_LCOMPARE;
10211                                 cmp->sreg2 = ins->dreg;
10212                         }
10213 #endif
10214                         MONO_ADD_INS (cfg->cbb, cmp);
10215
10216                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
10217                         type_from_op (cfg, ins, sp [0], NULL);
10218                         MONO_ADD_INS (cfg->cbb, ins);
10219                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
10220                         GET_BBLOCK (cfg, tblock, target);
10221                         ins->inst_true_bb = tblock;
10222                         GET_BBLOCK (cfg, tblock, ip);
10223                         ins->inst_false_bb = tblock;
10224                         start_new_bblock = 2;
10225
10226                         sp = stack_start;
10227                         inline_costs += BRANCH_COST;
10228                         break;
10229                 }
10230                 case CEE_BEQ:
10231                 case CEE_BGE:
10232                 case CEE_BGT:
10233                 case CEE_BLE:
10234                 case CEE_BLT:
10235                 case CEE_BNE_UN:
10236                 case CEE_BGE_UN:
10237                 case CEE_BGT_UN:
10238                 case CEE_BLE_UN:
10239                 case CEE_BLT_UN:
10240                         CHECK_OPSIZE (5);
10241                         CHECK_STACK (2);
10242                         MONO_INST_NEW (cfg, ins, *ip);
10243                         ip++;
10244                         target = ip + 4 + (gint32)read32(ip);
10245                         ip += 4;
10246
10247                         ADD_BINCOND (NULL);
10248
10249                         sp = stack_start;
10250                         inline_costs += BRANCH_COST;
10251                         break;
10252                 case CEE_SWITCH: {
10253                         MonoInst *src1;
10254                         MonoBasicBlock **targets;
10255                         MonoBasicBlock *default_bblock;
10256                         MonoJumpInfoBBTable *table;
10257                         int offset_reg = alloc_preg (cfg);
10258                         int target_reg = alloc_preg (cfg);
10259                         int table_reg = alloc_preg (cfg);
10260                         int sum_reg = alloc_preg (cfg);
10261                         gboolean use_op_switch;
10262
10263                         CHECK_OPSIZE (5);
10264                         CHECK_STACK (1);
10265                         n = read32 (ip + 1);
10266                         --sp;
10267                         src1 = sp [0];
10268                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
10269                                 UNVERIFIED;
10270
10271                         ip += 5;
10272                         CHECK_OPSIZE (n * sizeof (guint32));
10273                         target = ip + n * sizeof (guint32);
10274
10275                         GET_BBLOCK (cfg, default_bblock, target);
10276                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
10277
10278                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
10279                         for (i = 0; i < n; ++i) {
10280                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
10281                                 targets [i] = tblock;
10282                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
10283                                 ip += 4;
10284                         }
10285
10286                         if (sp != stack_start) {
10287                                 /* 
10288                                  * Link the current bb with the targets as well, so handle_stack_args
10289                                  * will set their in_stack correctly.
10290                                  */
10291                                 link_bblock (cfg, cfg->cbb, default_bblock);
10292                                 for (i = 0; i < n; ++i)
10293                                         link_bblock (cfg, cfg->cbb, targets [i]);
10294
10295                                 handle_stack_args (cfg, stack_start, sp - stack_start);
10296                                 sp = stack_start;
10297                                 CHECK_UNVERIFIABLE (cfg);
10298
10299                                 /* Undo the links */
10300                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
10301                                 for (i = 0; i < n; ++i)
10302                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
10303                         }
10304
10305                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
10306                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
10307
10308                         for (i = 0; i < n; ++i)
10309                                 link_bblock (cfg, cfg->cbb, targets [i]);
10310
10311                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
10312                         table->table = targets;
10313                         table->table_size = n;
10314
10315                         use_op_switch = FALSE;
10316 #ifdef TARGET_ARM
10317                         /* ARM implements SWITCH statements differently */
10318                         /* FIXME: Make it use the generic implementation */
10319                         if (!cfg->compile_aot)
10320                                 use_op_switch = TRUE;
10321 #endif
10322
10323                         if (COMPILE_LLVM (cfg))
10324                                 use_op_switch = TRUE;
10325
10326                         cfg->cbb->has_jump_table = 1;
10327
10328                         if (use_op_switch) {
10329                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
10330                                 ins->sreg1 = src1->dreg;
10331                                 ins->inst_p0 = table;
10332                                 ins->inst_many_bb = targets;
10333                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
10334                                 MONO_ADD_INS (cfg->cbb, ins);
10335                         } else {
10336                                 if (sizeof (gpointer) == 8)
10337                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
10338                                 else
10339                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
10340
10341 #if SIZEOF_REGISTER == 8
10342                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
10343                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
10344 #endif
10345
10346                                 if (cfg->compile_aot) {
10347                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
10348                                 } else {
10349                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
10350                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
10351                                         ins->inst_p0 = table;
10352                                         ins->dreg = table_reg;
10353                                         MONO_ADD_INS (cfg->cbb, ins);
10354                                 }
10355
10356                                 /* FIXME: Use load_memindex */
10357                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
10358                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
10359                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
10360                         }
10361                         start_new_bblock = 1;
10362                         inline_costs += (BRANCH_COST * 2);
10363                         break;
10364                 }
10365                 case CEE_LDIND_I1:
10366                 case CEE_LDIND_U1:
10367                 case CEE_LDIND_I2:
10368                 case CEE_LDIND_U2:
10369                 case CEE_LDIND_I4:
10370                 case CEE_LDIND_U4:
10371                 case CEE_LDIND_I8:
10372                 case CEE_LDIND_I:
10373                 case CEE_LDIND_R4:
10374                 case CEE_LDIND_R8:
10375                 case CEE_LDIND_REF:
10376                         CHECK_STACK (1);
10377                         --sp;
10378
10379                         switch (*ip) {
10380                         case CEE_LDIND_R4:
10381                         case CEE_LDIND_R8:
10382                                 dreg = alloc_freg (cfg);
10383                                 break;
10384                         case CEE_LDIND_I8:
10385                                 dreg = alloc_lreg (cfg);
10386                                 break;
10387                         case CEE_LDIND_REF:
10388                                 dreg = alloc_ireg_ref (cfg);
10389                                 break;
10390                         default:
10391                                 dreg = alloc_preg (cfg);
10392                         }
10393
10394                         NEW_LOAD_MEMBASE (cfg, ins, ldind_to_load_membase (*ip), dreg, sp [0]->dreg, 0);
10395                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
10396                         if (*ip == CEE_LDIND_R4)
10397                                 ins->type = cfg->r4_stack_type;
10398                         ins->flags |= ins_flag;
10399                         MONO_ADD_INS (cfg->cbb, ins);
10400                         *sp++ = ins;
10401                         if (ins_flag & MONO_INST_VOLATILE) {
10402                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10403                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10404                         }
10405                         ins_flag = 0;
10406                         ++ip;
10407                         break;
10408                 case CEE_STIND_REF:
10409                 case CEE_STIND_I1:
10410                 case CEE_STIND_I2:
10411                 case CEE_STIND_I4:
10412                 case CEE_STIND_I8:
10413                 case CEE_STIND_R4:
10414                 case CEE_STIND_R8:
10415                 case CEE_STIND_I:
10416                         CHECK_STACK (2);
10417                         sp -= 2;
10418
10419                         if (ins_flag & MONO_INST_VOLATILE) {
10420                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10421                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10422                         }
10423
10424                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
10425                         ins->flags |= ins_flag;
10426                         ins_flag = 0;
10427
10428                         MONO_ADD_INS (cfg->cbb, ins);
10429
10430                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [1]->opcode == OP_PCONST) && (sp [1]->inst_p0 == 0)))
10431                                 emit_write_barrier (cfg, sp [0], sp [1]);
10432
10433                         inline_costs += 1;
10434                         ++ip;
10435                         break;
10436
10437                 case CEE_MUL:
10438                         CHECK_STACK (2);
10439
10440                         MONO_INST_NEW (cfg, ins, (*ip));
10441                         sp -= 2;
10442                         ins->sreg1 = sp [0]->dreg;
10443                         ins->sreg2 = sp [1]->dreg;
10444                         type_from_op (cfg, ins, sp [0], sp [1]);
10445                         CHECK_TYPE (ins);
10446                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
10447
10448                         /* Use the immediate opcodes if possible */
10449                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
10450                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
10451                                 if (imm_opcode != -1) {
10452                                         ins->opcode = imm_opcode;
10453                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
10454                                         ins->sreg2 = -1;
10455
10456                                         NULLIFY_INS (sp [1]);
10457                                 }
10458                         }
10459
10460                         MONO_ADD_INS ((cfg)->cbb, (ins));
10461
10462                         *sp++ = mono_decompose_opcode (cfg, ins);
10463                         ip++;
10464                         break;
10465                 case CEE_ADD:
10466                 case CEE_SUB:
10467                 case CEE_DIV:
10468                 case CEE_DIV_UN:
10469                 case CEE_REM:
10470                 case CEE_REM_UN:
10471                 case CEE_AND:
10472                 case CEE_OR:
10473                 case CEE_XOR:
10474                 case CEE_SHL:
10475                 case CEE_SHR:
10476                 case CEE_SHR_UN:
10477                         CHECK_STACK (2);
10478
10479                         MONO_INST_NEW (cfg, ins, (*ip));
10480                         sp -= 2;
10481                         ins->sreg1 = sp [0]->dreg;
10482                         ins->sreg2 = sp [1]->dreg;
10483                         type_from_op (cfg, ins, sp [0], sp [1]);
10484                         CHECK_TYPE (ins);
10485                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
10486                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
10487
10488                         /* FIXME: Pass opcode to is_inst_imm */
10489
10490                         /* Use the immediate opcodes if possible */
10491                         if (((sp [1]->opcode == OP_ICONST) || (sp [1]->opcode == OP_I8CONST)) && mono_arch_is_inst_imm (sp [1]->opcode == OP_ICONST ? sp [1]->inst_c0 : sp [1]->inst_l)) {
10492                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
10493                                 if (imm_opcode != -1) {
10494                                         ins->opcode = imm_opcode;
10495                                         if (sp [1]->opcode == OP_I8CONST) {
10496 #if SIZEOF_REGISTER == 8
10497                                                 ins->inst_imm = sp [1]->inst_l;
10498 #else
10499                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
10500                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
10501 #endif
10502                                         }
10503                                         else
10504                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
10505                                         ins->sreg2 = -1;
10506
10507                                         /* Might be followed by an instruction added by add_widen_op */
10508                                         if (sp [1]->next == NULL)
10509                                                 NULLIFY_INS (sp [1]);
10510                                 }
10511                         }
10512                         MONO_ADD_INS ((cfg)->cbb, (ins));
10513
10514                         *sp++ = mono_decompose_opcode (cfg, ins);
10515                         ip++;
10516                         break;
10517                 case CEE_NEG:
10518                 case CEE_NOT:
10519                 case CEE_CONV_I1:
10520                 case CEE_CONV_I2:
10521                 case CEE_CONV_I4:
10522                 case CEE_CONV_R4:
10523                 case CEE_CONV_R8:
10524                 case CEE_CONV_U4:
10525                 case CEE_CONV_I8:
10526                 case CEE_CONV_U8:
10527                 case CEE_CONV_OVF_I8:
10528                 case CEE_CONV_OVF_U8:
10529                 case CEE_CONV_R_UN:
10530                         CHECK_STACK (1);
10531
10532                         /* Special case this earlier so we have long constants in the IR */
10533                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
10534                                 int data = sp [-1]->inst_c0;
10535                                 sp [-1]->opcode = OP_I8CONST;
10536                                 sp [-1]->type = STACK_I8;
10537 #if SIZEOF_REGISTER == 8
10538                                 if ((*ip) == CEE_CONV_U8)
10539                                         sp [-1]->inst_c0 = (guint32)data;
10540                                 else
10541                                         sp [-1]->inst_c0 = data;
10542 #else
10543                                 sp [-1]->inst_ls_word = data;
10544                                 if ((*ip) == CEE_CONV_U8)
10545                                         sp [-1]->inst_ms_word = 0;
10546                                 else
10547                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
10548 #endif
10549                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
10550                         }
10551                         else {
10552                                 ADD_UNOP (*ip);
10553                         }
10554                         ip++;
10555                         break;
10556                 case CEE_CONV_OVF_I4:
10557                 case CEE_CONV_OVF_I1:
10558                 case CEE_CONV_OVF_I2:
10559                 case CEE_CONV_OVF_I:
10560                 case CEE_CONV_OVF_U:
10561                         CHECK_STACK (1);
10562
10563                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
10564                                 ADD_UNOP (CEE_CONV_OVF_I8);
10565                                 ADD_UNOP (*ip);
10566                         } else {
10567                                 ADD_UNOP (*ip);
10568                         }
10569                         ip++;
10570                         break;
10571                 case CEE_CONV_OVF_U1:
10572                 case CEE_CONV_OVF_U2:
10573                 case CEE_CONV_OVF_U4:
10574                         CHECK_STACK (1);
10575
10576                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
10577                                 ADD_UNOP (CEE_CONV_OVF_U8);
10578                                 ADD_UNOP (*ip);
10579                         } else {
10580                                 ADD_UNOP (*ip);
10581                         }
10582                         ip++;
10583                         break;
10584                 case CEE_CONV_OVF_I1_UN:
10585                 case CEE_CONV_OVF_I2_UN:
10586                 case CEE_CONV_OVF_I4_UN:
10587                 case CEE_CONV_OVF_I8_UN:
10588                 case CEE_CONV_OVF_U1_UN:
10589                 case CEE_CONV_OVF_U2_UN:
10590                 case CEE_CONV_OVF_U4_UN:
10591                 case CEE_CONV_OVF_U8_UN:
10592                 case CEE_CONV_OVF_I_UN:
10593                 case CEE_CONV_OVF_U_UN:
10594                 case CEE_CONV_U2:
10595                 case CEE_CONV_U1:
10596                 case CEE_CONV_I:
10597                 case CEE_CONV_U:
10598                         CHECK_STACK (1);
10599                         ADD_UNOP (*ip);
10600                         CHECK_CFG_EXCEPTION;
10601                         ip++;
10602                         break;
10603                 case CEE_ADD_OVF:
10604                 case CEE_ADD_OVF_UN:
10605                 case CEE_MUL_OVF:
10606                 case CEE_MUL_OVF_UN:
10607                 case CEE_SUB_OVF:
10608                 case CEE_SUB_OVF_UN:
10609                         CHECK_STACK (2);
10610                         ADD_BINOP (*ip);
10611                         ip++;
10612                         break;
10613                 case CEE_CPOBJ:
10614                         GSHAREDVT_FAILURE (*ip);
10615                         CHECK_OPSIZE (5);
10616                         CHECK_STACK (2);
10617                         token = read32 (ip + 1);
10618                         klass = mini_get_class (method, token, generic_context);
10619                         CHECK_TYPELOAD (klass);
10620                         sp -= 2;
10621                         if (generic_class_is_reference_type (cfg, klass)) {
10622                                 MonoInst *store, *load;
10623                                 int dreg = alloc_ireg_ref (cfg);
10624
10625                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
10626                                 load->flags |= ins_flag;
10627                                 MONO_ADD_INS (cfg->cbb, load);
10628
10629                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
10630                                 store->flags |= ins_flag;
10631                                 MONO_ADD_INS (cfg->cbb, store);
10632
10633                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
10634                                         emit_write_barrier (cfg, sp [0], sp [1]);
10635                         } else {
10636                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10637                         }
10638                         ins_flag = 0;
10639                         ip += 5;
10640                         break;
10641                 case CEE_LDOBJ: {
10642                         int loc_index = -1;
10643                         int stloc_len = 0;
10644
10645                         CHECK_OPSIZE (5);
10646                         CHECK_STACK (1);
10647                         --sp;
10648                         token = read32 (ip + 1);
10649                         klass = mini_get_class (method, token, generic_context);
10650                         CHECK_TYPELOAD (klass);
10651
10652                         /* Optimize the common ldobj+stloc combination */
10653                         switch (ip [5]) {
10654                         case CEE_STLOC_S:
10655                                 loc_index = ip [6];
10656                                 stloc_len = 2;
10657                                 break;
10658                         case CEE_STLOC_0:
10659                         case CEE_STLOC_1:
10660                         case CEE_STLOC_2:
10661                         case CEE_STLOC_3:
10662                                 loc_index = ip [5] - CEE_STLOC_0;
10663                                 stloc_len = 1;
10664                                 break;
10665                         default:
10666                                 break;
10667                         }
10668
10669                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
10670                                 CHECK_LOCAL (loc_index);
10671
10672                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10673                                 ins->dreg = cfg->locals [loc_index]->dreg;
10674                                 ins->flags |= ins_flag;
10675                                 ip += 5;
10676                                 ip += stloc_len;
10677                                 if (ins_flag & MONO_INST_VOLATILE) {
10678                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10679                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10680                                 }
10681                                 ins_flag = 0;
10682                                 break;
10683                         }
10684
10685                         /* Optimize the ldobj+stobj combination */
10686                         /* The reference case ends up being a load+store anyway */
10687                         /* Skip this if the operation is volatile. */
10688                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token) && !generic_class_is_reference_type (cfg, klass) && !(ins_flag & MONO_INST_VOLATILE)) {
10689                                 CHECK_STACK (1);
10690
10691                                 sp --;
10692
10693                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10694
10695                                 ip += 5 + 5;
10696                                 ins_flag = 0;
10697                                 break;
10698                         }
10699
10700                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10701                         ins->flags |= ins_flag;
10702                         *sp++ = ins;
10703
10704                         if (ins_flag & MONO_INST_VOLATILE) {
10705                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10706                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10707                         }
10708
10709                         ip += 5;
10710                         ins_flag = 0;
10711                         inline_costs += 1;
10712                         break;
10713                 }
10714                 case CEE_LDSTR:
10715                         CHECK_STACK_OVF (1);
10716                         CHECK_OPSIZE (5);
10717                         n = read32 (ip + 1);
10718
10719                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
10720                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
10721                                 ins->type = STACK_OBJ;
10722                                 *sp = ins;
10723                         }
10724                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
10725                                 MonoInst *iargs [1];
10726                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
10727
10728                                 if (cfg->compile_aot)
10729                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
10730                                 else
10731                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
10732                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
10733                         } else {
10734                                 if (cfg->opt & MONO_OPT_SHARED) {
10735                                         MonoInst *iargs [3];
10736
10737                                         if (cfg->compile_aot) {
10738                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
10739                                         }
10740                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10741                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
10742                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
10743                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
10744                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10745                                         CHECK_CFG_ERROR;
10746                                 } else {
10747                                         if (cfg->cbb->out_of_line) {
10748                                                 MonoInst *iargs [2];
10749
10750                                                 if (image == mono_defaults.corlib) {
10751                                                         /* 
10752                                                          * Avoid relocations in AOT and save some space by using a 
10753                                                          * version of helper_ldstr specialized to mscorlib.
10754                                                          */
10755                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
10756                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
10757                                                 } else {
10758                                                         /* Avoid creating the string object */
10759                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
10760                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
10761                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
10762                                                 }
10763                                         } 
10764                                         else
10765                                         if (cfg->compile_aot) {
10766                                                 NEW_LDSTRCONST (cfg, ins, image, n);
10767                                                 *sp = ins;
10768                                                 MONO_ADD_INS (cfg->cbb, ins);
10769                                         } 
10770                                         else {
10771                                                 NEW_PCONST (cfg, ins, NULL);
10772                                                 ins->type = STACK_OBJ;
10773                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10774                                                 CHECK_CFG_ERROR;
10775                                                 
10776                                                 if (!ins->inst_p0)
10777                                                         OUT_OF_MEMORY_FAILURE;
10778
10779                                                 *sp = ins;
10780                                                 MONO_ADD_INS (cfg->cbb, ins);
10781                                         }
10782                                 }
10783                         }
10784
10785                         sp++;
10786                         ip += 5;
10787                         break;
10788                 case CEE_NEWOBJ: {
10789                         MonoInst *iargs [2];
10790                         MonoMethodSignature *fsig;
10791                         MonoInst this_ins;
10792                         MonoInst *alloc;
10793                         MonoInst *vtable_arg = NULL;
10794
10795                         CHECK_OPSIZE (5);
10796                         token = read32 (ip + 1);
10797                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10798                         CHECK_CFG_ERROR;
10799
10800                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10801                         CHECK_CFG_ERROR;
10802
10803                         mono_save_token_info (cfg, image, token, cmethod);
10804
10805                         if (!mono_class_init (cmethod->klass))
10806                                 TYPE_LOAD_ERROR (cmethod->klass);
10807
10808                         context_used = mini_method_check_context_used (cfg, cmethod);
10809
10810                         if (mono_security_core_clr_enabled ())
10811                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10812
10813                         if (cfg->gshared && cmethod && cmethod->klass != method->klass && cmethod->klass->generic_class && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
10814                                 emit_class_init (cfg, cmethod->klass);
10815                                 CHECK_TYPELOAD (cmethod->klass);
10816                         }
10817
10818                         /*
10819                         if (cfg->gsharedvt) {
10820                                 if (mini_is_gsharedvt_variable_signature (sig))
10821                                         GSHAREDVT_FAILURE (*ip);
10822                         }
10823                         */
10824
10825                         n = fsig->param_count;
10826                         CHECK_STACK (n);
10827
10828                         /* 
10829                          * Generate smaller code for the common newobj <exception> instruction in
10830                          * argument checking code.
10831                          */
10832                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10833                                 is_exception_class (cmethod->klass) && n <= 2 &&
10834                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10835                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10836                                 MonoInst *iargs [3];
10837
10838                                 sp -= n;
10839
10840                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10841                                 switch (n) {
10842                                 case 0:
10843                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10844                                         break;
10845                                 case 1:
10846                                         iargs [1] = sp [0];
10847                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10848                                         break;
10849                                 case 2:
10850                                         iargs [1] = sp [0];
10851                                         iargs [2] = sp [1];
10852                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10853                                         break;
10854                                 default:
10855                                         g_assert_not_reached ();
10856                                 }
10857
10858                                 ip += 5;
10859                                 inline_costs += 5;
10860                                 break;
10861                         }
10862
10863                         /* move the args to allow room for 'this' in the first position */
10864                         while (n--) {
10865                                 --sp;
10866                                 sp [1] = sp [0];
10867                         }
10868
10869                         /* check_call_signature () requires sp[0] to be set */
10870                         this_ins.type = STACK_OBJ;
10871                         sp [0] = &this_ins;
10872                         if (check_call_signature (cfg, fsig, sp))
10873                                 UNVERIFIED;
10874
10875                         iargs [0] = NULL;
10876
10877                         if (mini_class_is_system_array (cmethod->klass)) {
10878                                 *sp = emit_get_rgctx_method (cfg, context_used,
10879                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10880
10881                                 /* Avoid varargs in the common case */
10882                                 if (fsig->param_count == 1)
10883                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10884                                 else if (fsig->param_count == 2)
10885                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10886                                 else if (fsig->param_count == 3)
10887                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10888                                 else if (fsig->param_count == 4)
10889                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10890                                 else
10891                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10892                         } else if (cmethod->string_ctor) {
10893                                 g_assert (!context_used);
10894                                 g_assert (!vtable_arg);
10895                                 /* we simply pass a null pointer */
10896                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10897                                 /* now call the string ctor */
10898                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10899                         } else {
10900                                 if (cmethod->klass->valuetype) {
10901                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10902                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10903                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10904
10905                                         alloc = NULL;
10906
10907                                         /* 
10908                                          * The code generated by mini_emit_virtual_call () expects
10909                                          * iargs [0] to be a boxed instance, but luckily the vcall
10910                                          * will be transformed into a normal call there.
10911                                          */
10912                                 } else if (context_used) {
10913                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10914                                         *sp = alloc;
10915                                 } else {
10916                                         MonoVTable *vtable = NULL;
10917
10918                                         if (!cfg->compile_aot)
10919                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10920                                         CHECK_TYPELOAD (cmethod->klass);
10921
10922                                         /*
10923                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10924                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10925                                          * As a workaround, we call class cctors before allocating objects.
10926                                          */
10927                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10928                                                 emit_class_init (cfg, cmethod->klass);
10929                                                 if (cfg->verbose_level > 2)
10930                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10931                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10932                                         }
10933
10934                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10935                                         *sp = alloc;
10936                                 }
10937                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10938
10939                                 if (alloc)
10940                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10941
10942                                 /* Now call the actual ctor */
10943                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10944                                 CHECK_CFG_EXCEPTION;
10945                         }
10946
10947                         if (alloc == NULL) {
10948                                 /* Valuetype */
10949                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10950                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10951                                 *sp++= ins;
10952                         } else {
10953                                 *sp++ = alloc;
10954                         }
10955                         
10956                         ip += 5;
10957                         inline_costs += 5;
10958                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10959                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10960                         break;
10961                 }
10962                 case CEE_CASTCLASS:
10963                         CHECK_STACK (1);
10964                         --sp;
10965                         CHECK_OPSIZE (5);
10966                         token = read32 (ip + 1);
10967                         klass = mini_get_class (method, token, generic_context);
10968                         CHECK_TYPELOAD (klass);
10969                         if (sp [0]->type != STACK_OBJ)
10970                                 UNVERIFIED;
10971
10972                         ins = handle_castclass (cfg, klass, *sp, ip, &inline_costs);
10973                         CHECK_CFG_EXCEPTION;
10974
10975                         *sp ++ = ins;
10976                         ip += 5;
10977                         break;
10978                 case CEE_ISINST: {
10979                         CHECK_STACK (1);
10980                         --sp;
10981                         CHECK_OPSIZE (5);
10982                         token = read32 (ip + 1);
10983                         klass = mini_get_class (method, token, generic_context);
10984                         CHECK_TYPELOAD (klass);
10985                         if (sp [0]->type != STACK_OBJ)
10986                                 UNVERIFIED;
10987  
10988                         context_used = mini_class_check_context_used (cfg, klass);
10989
10990                         if (!context_used && mini_class_has_reference_variant_generic_argument (cfg, klass, context_used)) {
10991                                 MonoMethod *mono_isinst = mono_marshal_get_isinst_with_cache ();
10992                                 MonoInst *args [3];
10993                                 int idx;
10994
10995                                 /* obj */
10996                                 args [0] = *sp;
10997
10998                                 /* klass */
10999                                 EMIT_NEW_CLASSCONST (cfg, args [1], klass);
11000
11001                                 /* inline cache*/
11002                                 idx = get_castclass_cache_idx (cfg);
11003                                 args [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CASTCLASS_CACHE, GINT_TO_POINTER (idx));
11004
11005                                 *sp++ = mono_emit_method_call (cfg, mono_isinst, args, NULL);
11006                                 ip += 5;
11007                                 inline_costs += 2;
11008                         } else if (!context_used && (mono_class_is_marshalbyref (klass) || klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
11009                                 MonoMethod *mono_isinst;
11010                                 MonoInst *iargs [1];
11011                                 int costs;
11012
11013                                 mono_isinst = mono_marshal_get_isinst (klass); 
11014                                 iargs [0] = sp [0];
11015
11016                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), 
11017                                                                            iargs, ip, cfg->real_offset, TRUE);
11018                                 CHECK_CFG_EXCEPTION;
11019                                 g_assert (costs > 0);
11020                                 
11021                                 ip += 5;
11022                                 cfg->real_offset += 5;
11023
11024                                 *sp++= iargs [0];
11025
11026                                 inline_costs += costs;
11027                         }
11028                         else {
11029                                 ins = handle_isinst (cfg, klass, *sp, context_used);
11030                                 CHECK_CFG_EXCEPTION;
11031                                 *sp ++ = ins;
11032                                 ip += 5;
11033                         }
11034                         break;
11035                 }
11036                 case CEE_UNBOX_ANY: {
11037                         MonoInst *res, *addr;
11038
11039                         CHECK_STACK (1);
11040                         --sp;
11041                         CHECK_OPSIZE (5);
11042                         token = read32 (ip + 1);
11043                         klass = mini_get_class (method, token, generic_context);
11044                         CHECK_TYPELOAD (klass);
11045
11046                         mono_save_token_info (cfg, image, token, klass);
11047
11048                         context_used = mini_class_check_context_used (cfg, klass);
11049
11050                         if (mini_is_gsharedvt_klass (klass)) {
11051                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
11052                                 inline_costs += 2;
11053                         } else if (generic_class_is_reference_type (cfg, klass)) {
11054                                 res = handle_castclass (cfg, klass, *sp, ip, &inline_costs);
11055                                 CHECK_CFG_EXCEPTION;
11056                         } else if (mono_class_is_nullable (klass)) {
11057                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
11058                         } else {
11059                                 addr = handle_unbox (cfg, klass, sp, context_used);
11060                                 /* LDOBJ */
11061                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11062                                 res = ins;
11063                                 inline_costs += 2;
11064                         }
11065
11066                         *sp ++ = res;
11067                         ip += 5;
11068                         break;
11069                 }
11070                 case CEE_BOX: {
11071                         MonoInst *val;
11072                         MonoClass *enum_class;
11073                         MonoMethod *has_flag;
11074
11075                         CHECK_STACK (1);
11076                         --sp;
11077                         val = *sp;
11078                         CHECK_OPSIZE (5);
11079                         token = read32 (ip + 1);
11080                         klass = mini_get_class (method, token, generic_context);
11081                         CHECK_TYPELOAD (klass);
11082
11083                         mono_save_token_info (cfg, image, token, klass);
11084
11085                         context_used = mini_class_check_context_used (cfg, klass);
11086
11087                         if (generic_class_is_reference_type (cfg, klass)) {
11088                                 *sp++ = val;
11089                                 ip += 5;
11090                                 break;
11091                         }
11092
11093                         if (klass == mono_defaults.void_class)
11094                                 UNVERIFIED;
11095                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
11096                                 UNVERIFIED;
11097                         /* frequent check in generic code: box (struct), brtrue */
11098
11099                         /*
11100                          * Look for:
11101                          *
11102                          *   <push int/long ptr>
11103                          *   <push int/long>
11104                          *   box MyFlags
11105                          *   constrained. MyFlags
11106                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
11107                          *
11108                          * If we find this sequence and the operand types on box and constrained
11109                          * are equal, we can emit a specialized instruction sequence instead of
11110                          * the very slow HasFlag () call.
11111                          */
11112                         if ((cfg->opt & MONO_OPT_INTRINS) &&
11113                             /* Cheap checks first. */
11114                             ip + 5 + 6 + 5 < end &&
11115                             ip [5] == CEE_PREFIX1 &&
11116                             ip [6] == CEE_CONSTRAINED_ &&
11117                             ip [11] == CEE_CALLVIRT &&
11118                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
11119                             mono_class_is_enum (klass) &&
11120                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
11121                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
11122                             has_flag->klass == mono_defaults.enum_class &&
11123                             !strcmp (has_flag->name, "HasFlag") &&
11124                             has_flag->signature->hasthis &&
11125                             has_flag->signature->param_count == 1) {
11126                                 CHECK_TYPELOAD (enum_class);
11127
11128                                 if (enum_class == klass) {
11129                                         MonoInst *enum_this, *enum_flag;
11130
11131                                         ip += 5 + 6 + 5;
11132                                         --sp;
11133
11134                                         enum_this = sp [0];
11135                                         enum_flag = sp [1];
11136
11137                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
11138                                         break;
11139                                 }
11140                         }
11141
11142                         // FIXME: LLVM can't handle the inconsistent bb linking
11143                         if (!mono_class_is_nullable (klass) &&
11144                                 !mini_is_gsharedvt_klass (klass) &&
11145                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
11146                                 (ip [5] == CEE_BRTRUE || 
11147                                  ip [5] == CEE_BRTRUE_S ||
11148                                  ip [5] == CEE_BRFALSE ||
11149                                  ip [5] == CEE_BRFALSE_S)) {
11150                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
11151                                 int dreg;
11152                                 MonoBasicBlock *true_bb, *false_bb;
11153
11154                                 ip += 5;
11155
11156                                 if (cfg->verbose_level > 3) {
11157                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
11158                                         printf ("<box+brtrue opt>\n");
11159                                 }
11160
11161                                 switch (*ip) {
11162                                 case CEE_BRTRUE_S:
11163                                 case CEE_BRFALSE_S:
11164                                         CHECK_OPSIZE (2);
11165                                         ip++;
11166                                         target = ip + 1 + (signed char)(*ip);
11167                                         ip++;
11168                                         break;
11169                                 case CEE_BRTRUE:
11170                                 case CEE_BRFALSE:
11171                                         CHECK_OPSIZE (5);
11172                                         ip++;
11173                                         target = ip + 4 + (gint)(read32 (ip));
11174                                         ip += 4;
11175                                         break;
11176                                 default:
11177                                         g_assert_not_reached ();
11178                                 }
11179
11180                                 /* 
11181                                  * We need to link both bblocks, since it is needed for handling stack
11182                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
11183                                  * Branching to only one of them would lead to inconsistencies, so
11184                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
11185                                  */
11186                                 GET_BBLOCK (cfg, true_bb, target);
11187                                 GET_BBLOCK (cfg, false_bb, ip);
11188
11189                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
11190                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
11191
11192                                 if (sp != stack_start) {
11193                                         handle_stack_args (cfg, stack_start, sp - stack_start);
11194                                         sp = stack_start;
11195                                         CHECK_UNVERIFIABLE (cfg);
11196                                 }
11197
11198                                 if (COMPILE_LLVM (cfg)) {
11199                                         dreg = alloc_ireg (cfg);
11200                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
11201                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
11202
11203                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
11204                                 } else {
11205                                         /* The JIT can't eliminate the iconst+compare */
11206                                         MONO_INST_NEW (cfg, ins, OP_BR);
11207                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
11208                                         MONO_ADD_INS (cfg->cbb, ins);
11209                                 }
11210
11211                                 start_new_bblock = 1;
11212                                 break;
11213                         }
11214
11215                         *sp++ = handle_box (cfg, val, klass, context_used);
11216
11217                         CHECK_CFG_EXCEPTION;
11218                         ip += 5;
11219                         inline_costs += 1;
11220                         break;
11221                 }
11222                 case CEE_UNBOX: {
11223                         CHECK_STACK (1);
11224                         --sp;
11225                         CHECK_OPSIZE (5);
11226                         token = read32 (ip + 1);
11227                         klass = mini_get_class (method, token, generic_context);
11228                         CHECK_TYPELOAD (klass);
11229
11230                         mono_save_token_info (cfg, image, token, klass);
11231
11232                         context_used = mini_class_check_context_used (cfg, klass);
11233
11234                         if (mono_class_is_nullable (klass)) {
11235                                 MonoInst *val;
11236
11237                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
11238                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
11239
11240                                 *sp++= ins;
11241                         } else {
11242                                 ins = handle_unbox (cfg, klass, sp, context_used);
11243                                 *sp++ = ins;
11244                         }
11245                         ip += 5;
11246                         inline_costs += 2;
11247                         break;
11248                 }
11249                 case CEE_LDFLD:
11250                 case CEE_LDFLDA:
11251                 case CEE_STFLD:
11252                 case CEE_LDSFLD:
11253                 case CEE_LDSFLDA:
11254                 case CEE_STSFLD: {
11255                         MonoClassField *field;
11256 #ifndef DISABLE_REMOTING
11257                         int costs;
11258 #endif
11259                         guint foffset;
11260                         gboolean is_instance;
11261                         int op;
11262                         gpointer addr = NULL;
11263                         gboolean is_special_static;
11264                         MonoType *ftype;
11265                         MonoInst *store_val = NULL;
11266                         MonoInst *thread_ins;
11267
11268                         op = *ip;
11269                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
11270                         if (is_instance) {
11271                                 if (op == CEE_STFLD) {
11272                                         CHECK_STACK (2);
11273                                         sp -= 2;
11274                                         store_val = sp [1];
11275                                 } else {
11276                                         CHECK_STACK (1);
11277                                         --sp;
11278                                 }
11279                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
11280                                         UNVERIFIED;
11281                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
11282                                         UNVERIFIED;
11283                         } else {
11284                                 if (op == CEE_STSFLD) {
11285                                         CHECK_STACK (1);
11286                                         sp--;
11287                                         store_val = sp [0];
11288                                 }
11289                         }
11290
11291                         CHECK_OPSIZE (5);
11292                         token = read32 (ip + 1);
11293                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
11294                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
11295                                 klass = field->parent;
11296                         }
11297                         else {
11298                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
11299                                 CHECK_CFG_ERROR;
11300                         }
11301                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
11302                                 FIELD_ACCESS_FAILURE (method, field);
11303                         mono_class_init (klass);
11304
11305                         /* if the class is Critical then transparent code cannot access it's fields */
11306                         if (!is_instance && mono_security_core_clr_enabled ())
11307                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
11308
11309                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
11310                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
11311                         if (mono_security_core_clr_enabled ())
11312                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
11313                         */
11314
11315                         ftype = mono_field_get_type (field);
11316
11317                         /*
11318                          * LDFLD etc. is usable on static fields as well, so convert those cases to
11319                          * the static case.
11320                          */
11321                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
11322                                 switch (op) {
11323                                 case CEE_LDFLD:
11324                                         op = CEE_LDSFLD;
11325                                         break;
11326                                 case CEE_STFLD:
11327                                         op = CEE_STSFLD;
11328                                         break;
11329                                 case CEE_LDFLDA:
11330                                         op = CEE_LDSFLDA;
11331                                         break;
11332                                 default:
11333                                         g_assert_not_reached ();
11334                                 }
11335                                 is_instance = FALSE;
11336                         }
11337
11338                         context_used = mini_class_check_context_used (cfg, klass);
11339
11340                         /* INSTANCE CASE */
11341
11342                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
11343                         if (op == CEE_STFLD) {
11344                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
11345                                         UNVERIFIED;
11346 #ifndef DISABLE_REMOTING
11347                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
11348                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
11349                                         MonoInst *iargs [5];
11350
11351                                         GSHAREDVT_FAILURE (op);
11352
11353                                         iargs [0] = sp [0];
11354                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11355                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
11356                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
11357                                                     field->offset);
11358                                         iargs [4] = sp [1];
11359
11360                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
11361                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
11362                                                                                            iargs, ip, cfg->real_offset, TRUE);
11363                                                 CHECK_CFG_EXCEPTION;
11364                                                 g_assert (costs > 0);
11365                                                       
11366                                                 cfg->real_offset += 5;
11367
11368                                                 inline_costs += costs;
11369                                         } else {
11370                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
11371                                         }
11372                                 } else
11373 #endif
11374                                 {
11375                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
11376
11377                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
11378
11379                                         if (mini_is_gsharedvt_klass (klass)) {
11380                                                 MonoInst *offset_ins;
11381
11382                                                 context_used = mini_class_check_context_used (cfg, klass);
11383
11384                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11385                                                 /* The value is offset by 1 */
11386                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11387                                                 dreg = alloc_ireg_mp (cfg);
11388                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11389                                                 wbarrier_ptr_ins = ins;
11390                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
11391                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
11392                                         } else {
11393                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
11394                                         }
11395                                         if (sp [0]->opcode != OP_LDADDR)
11396                                                 store->flags |= MONO_INST_FAULT;
11397
11398                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
11399                                                 if (mini_is_gsharedvt_klass (klass)) {
11400                                                         g_assert (wbarrier_ptr_ins);
11401                                                         emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
11402                                                 } else {
11403                                                         /* insert call to write barrier */
11404                                                         MonoInst *ptr;
11405                                                         int dreg;
11406
11407                                                         dreg = alloc_ireg_mp (cfg);
11408                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
11409                                                         emit_write_barrier (cfg, ptr, sp [1]);
11410                                                 }
11411                                         }
11412
11413                                         store->flags |= ins_flag;
11414                                 }
11415                                 ins_flag = 0;
11416                                 ip += 5;
11417                                 break;
11418                         }
11419
11420 #ifndef DISABLE_REMOTING
11421                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
11422                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
11423                                 MonoInst *iargs [4];
11424
11425                                 GSHAREDVT_FAILURE (op);
11426
11427                                 iargs [0] = sp [0];
11428                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11429                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
11430                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
11431                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
11432                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
11433                                                                                    iargs, ip, cfg->real_offset, TRUE);
11434                                         CHECK_CFG_EXCEPTION;
11435                                         g_assert (costs > 0);
11436                                                       
11437                                         cfg->real_offset += 5;
11438
11439                                         *sp++ = iargs [0];
11440
11441                                         inline_costs += costs;
11442                                 } else {
11443                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
11444                                         *sp++ = ins;
11445                                 }
11446                         } else 
11447 #endif
11448                         if (is_instance) {
11449                                 if (sp [0]->type == STACK_VTYPE) {
11450                                         MonoInst *var;
11451
11452                                         /* Have to compute the address of the variable */
11453
11454                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
11455                                         if (!var)
11456                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
11457                                         else
11458                                                 g_assert (var->klass == klass);
11459                                         
11460                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
11461                                         sp [0] = ins;
11462                                 }
11463
11464                                 if (op == CEE_LDFLDA) {
11465                                         if (sp [0]->type == STACK_OBJ) {
11466                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
11467                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
11468                                         }
11469
11470                                         dreg = alloc_ireg_mp (cfg);
11471
11472                                         if (mini_is_gsharedvt_klass (klass)) {
11473                                                 MonoInst *offset_ins;
11474
11475                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11476                                                 /* The value is offset by 1 */
11477                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11478                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11479                                         } else {
11480                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
11481                                         }
11482                                         ins->klass = mono_class_from_mono_type (field->type);
11483                                         ins->type = STACK_MP;
11484                                         *sp++ = ins;
11485                                 } else {
11486                                         MonoInst *load;
11487
11488                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
11489
11490                                         if (mini_is_gsharedvt_klass (klass)) {
11491                                                 MonoInst *offset_ins;
11492
11493                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11494                                                 /* The value is offset by 1 */
11495                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11496                                                 dreg = alloc_ireg_mp (cfg);
11497                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
11498                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, dreg, 0);
11499                                         } else {
11500                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, sp [0]->dreg, foffset);
11501                                         }
11502                                         load->flags |= ins_flag;
11503                                         if (sp [0]->opcode != OP_LDADDR)
11504                                                 load->flags |= MONO_INST_FAULT;
11505                                         *sp++ = load;
11506                                 }
11507                         }
11508
11509                         if (is_instance) {
11510                                 ins_flag = 0;
11511                                 ip += 5;
11512                                 break;
11513                         }
11514
11515                         /* STATIC CASE */
11516                         context_used = mini_class_check_context_used (cfg, klass);
11517
11518                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
11519                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
11520                                 CHECK_CFG_ERROR;
11521                         }
11522
11523                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
11524                          * to be called here.
11525                          */
11526                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
11527                                 mono_class_vtable (cfg->domain, klass);
11528                                 CHECK_TYPELOAD (klass);
11529                         }
11530                         mono_domain_lock (cfg->domain);
11531                         if (cfg->domain->special_static_fields)
11532                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
11533                         mono_domain_unlock (cfg->domain);
11534
11535                         is_special_static = mono_class_field_is_special_static (field);
11536
11537                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
11538                                 thread_ins = mono_get_thread_intrinsic (cfg);
11539                         else
11540                                 thread_ins = NULL;
11541
11542                         /* Generate IR to compute the field address */
11543                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
11544                                 /*
11545                                  * Fast access to TLS data
11546                                  * Inline version of get_thread_static_data () in
11547                                  * threads.c.
11548                                  */
11549                                 guint32 offset;
11550                                 int idx, static_data_reg, array_reg, dreg;
11551
11552                                 GSHAREDVT_FAILURE (op);
11553
11554                                 MONO_ADD_INS (cfg->cbb, thread_ins);
11555                                 static_data_reg = alloc_ireg (cfg);
11556                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
11557
11558                                 if (cfg->compile_aot) {
11559                                         int offset_reg, offset2_reg, idx_reg;
11560
11561                                         /* For TLS variables, this will return the TLS offset */
11562                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
11563                                         offset_reg = ins->dreg;
11564                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
11565                                         idx_reg = alloc_ireg (cfg);
11566                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
11567                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
11568                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
11569                                         array_reg = alloc_ireg (cfg);
11570                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
11571                                         offset2_reg = alloc_ireg (cfg);
11572                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
11573                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
11574                                         dreg = alloc_ireg (cfg);
11575                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
11576                                 } else {
11577                                         offset = (gsize)addr & 0x7fffffff;
11578                                         idx = offset & 0x3f;
11579
11580                                         array_reg = alloc_ireg (cfg);
11581                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
11582                                         dreg = alloc_ireg (cfg);
11583                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
11584                                 }
11585                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
11586                                         (cfg->compile_aot && is_special_static) ||
11587                                         (context_used && is_special_static)) {
11588                                 MonoInst *iargs [2];
11589
11590                                 g_assert (field->parent);
11591                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11592                                 if (context_used) {
11593                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
11594                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
11595                                 } else {
11596                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
11597                                 }
11598                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
11599                         } else if (context_used) {
11600                                 MonoInst *static_data;
11601
11602                                 /*
11603                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
11604                                         method->klass->name_space, method->klass->name, method->name,
11605                                         depth, field->offset);
11606                                 */
11607
11608                                 if (mono_class_needs_cctor_run (klass, method))
11609                                         emit_class_init (cfg, klass);
11610
11611                                 /*
11612                                  * The pointer we're computing here is
11613                                  *
11614                                  *   super_info.static_data + field->offset
11615                                  */
11616                                 static_data = emit_get_rgctx_klass (cfg, context_used,
11617                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
11618
11619                                 if (mini_is_gsharedvt_klass (klass)) {
11620                                         MonoInst *offset_ins;
11621
11622                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
11623                                         /* The value is offset by 1 */
11624                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
11625                                         dreg = alloc_ireg_mp (cfg);
11626                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
11627                                 } else if (field->offset == 0) {
11628                                         ins = static_data;
11629                                 } else {
11630                                         int addr_reg = mono_alloc_preg (cfg);
11631                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
11632                                 }
11633                                 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
11634                                 MonoInst *iargs [2];
11635
11636                                 g_assert (field->parent);
11637                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11638                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
11639                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
11640                         } else {
11641                                 MonoVTable *vtable = NULL;
11642
11643                                 if (!cfg->compile_aot)
11644                                         vtable = mono_class_vtable (cfg->domain, klass);
11645                                 CHECK_TYPELOAD (klass);
11646
11647                                 if (!addr) {
11648                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
11649                                                 if (!(g_slist_find (class_inits, klass))) {
11650                                                         emit_class_init (cfg, klass);
11651                                                         if (cfg->verbose_level > 2)
11652                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
11653                                                         class_inits = g_slist_prepend (class_inits, klass);
11654                                                 }
11655                                         } else {
11656                                                 if (cfg->run_cctors) {
11657                                                         /* This makes so that inline cannot trigger */
11658                                                         /* .cctors: too many apps depend on them */
11659                                                         /* running with a specific order... */
11660                                                         g_assert (vtable);
11661                                                         if (! vtable->initialized)
11662                                                                 INLINE_FAILURE ("class init");
11663                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
11664                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
11665                                                                 goto exception_exit;
11666                                                         }
11667                                                 }
11668                                         }
11669                                         if (cfg->compile_aot)
11670                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
11671                                         else {
11672                                                 g_assert (vtable);
11673                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11674                                                 g_assert (addr);
11675                                                 EMIT_NEW_PCONST (cfg, ins, addr);
11676                                         }
11677                                 } else {
11678                                         MonoInst *iargs [1];
11679                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
11680                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
11681                                 }
11682                         }
11683
11684                         /* Generate IR to do the actual load/store operation */
11685
11686                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11687                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11688                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11689                         }
11690
11691                         if (op == CEE_LDSFLDA) {
11692                                 ins->klass = mono_class_from_mono_type (ftype);
11693                                 ins->type = STACK_PTR;
11694                                 *sp++ = ins;
11695                         } else if (op == CEE_STSFLD) {
11696                                 MonoInst *store;
11697
11698                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
11699                                 store->flags |= ins_flag;
11700                         } else {
11701                                 gboolean is_const = FALSE;
11702                                 MonoVTable *vtable = NULL;
11703                                 gpointer addr = NULL;
11704
11705                                 if (!context_used) {
11706                                         vtable = mono_class_vtable (cfg->domain, klass);
11707                                         CHECK_TYPELOAD (klass);
11708                                 }
11709                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
11710                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
11711                                         int ro_type = ftype->type;
11712                                         if (!addr)
11713                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11714                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
11715                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
11716                                         }
11717
11718                                         GSHAREDVT_FAILURE (op);
11719
11720                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
11721                                         is_const = TRUE;
11722                                         switch (ro_type) {
11723                                         case MONO_TYPE_BOOLEAN:
11724                                         case MONO_TYPE_U1:
11725                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
11726                                                 sp++;
11727                                                 break;
11728                                         case MONO_TYPE_I1:
11729                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
11730                                                 sp++;
11731                                                 break;                                          
11732                                         case MONO_TYPE_CHAR:
11733                                         case MONO_TYPE_U2:
11734                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
11735                                                 sp++;
11736                                                 break;
11737                                         case MONO_TYPE_I2:
11738                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
11739                                                 sp++;
11740                                                 break;
11741                                                 break;
11742                                         case MONO_TYPE_I4:
11743                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
11744                                                 sp++;
11745                                                 break;                                          
11746                                         case MONO_TYPE_U4:
11747                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
11748                                                 sp++;
11749                                                 break;
11750                                         case MONO_TYPE_I:
11751                                         case MONO_TYPE_U:
11752                                         case MONO_TYPE_PTR:
11753                                         case MONO_TYPE_FNPTR:
11754                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11755                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
11756                                                 sp++;
11757                                                 break;
11758                                         case MONO_TYPE_STRING:
11759                                         case MONO_TYPE_OBJECT:
11760                                         case MONO_TYPE_CLASS:
11761                                         case MONO_TYPE_SZARRAY:
11762                                         case MONO_TYPE_ARRAY:
11763                                                 if (!mono_gc_is_moving ()) {
11764                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11765                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
11766                                                         sp++;
11767                                                 } else {
11768                                                         is_const = FALSE;
11769                                                 }
11770                                                 break;
11771                                         case MONO_TYPE_I8:
11772                                         case MONO_TYPE_U8:
11773                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
11774                                                 sp++;
11775                                                 break;
11776                                         case MONO_TYPE_R4:
11777                                         case MONO_TYPE_R8:
11778                                         case MONO_TYPE_VALUETYPE:
11779                                         default:
11780                                                 is_const = FALSE;
11781                                                 break;
11782                                         }
11783                                 }
11784
11785                                 if (!is_const) {
11786                                         MonoInst *load;
11787
11788                                         CHECK_STACK_OVF (1);
11789
11790                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
11791                                         load->flags |= ins_flag;
11792                                         ins_flag = 0;
11793                                         *sp++ = load;
11794                                 }
11795                         }
11796
11797                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11798                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11799                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11800                         }
11801
11802                         ins_flag = 0;
11803                         ip += 5;
11804                         break;
11805                 }
11806                 case CEE_STOBJ:
11807                         CHECK_STACK (2);
11808                         sp -= 2;
11809                         CHECK_OPSIZE (5);
11810                         token = read32 (ip + 1);
11811                         klass = mini_get_class (method, token, generic_context);
11812                         CHECK_TYPELOAD (klass);
11813                         if (ins_flag & MONO_INST_VOLATILE) {
11814                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11815                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11816                         }
11817                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11818                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
11819                         ins->flags |= ins_flag;
11820                         if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
11821                                         generic_class_is_reference_type (cfg, klass)) {
11822                                 /* insert call to write barrier */
11823                                 emit_write_barrier (cfg, sp [0], sp [1]);
11824                         }
11825                         ins_flag = 0;
11826                         ip += 5;
11827                         inline_costs += 1;
11828                         break;
11829
11830                         /*
11831                          * Array opcodes
11832                          */
11833                 case CEE_NEWARR: {
11834                         MonoInst *len_ins;
11835                         const char *data_ptr;
11836                         int data_size = 0;
11837                         guint32 field_token;
11838
11839                         CHECK_STACK (1);
11840                         --sp;
11841
11842                         CHECK_OPSIZE (5);
11843                         token = read32 (ip + 1);
11844
11845                         klass = mini_get_class (method, token, generic_context);
11846                         CHECK_TYPELOAD (klass);
11847
11848                         context_used = mini_class_check_context_used (cfg, klass);
11849
11850                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11851                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11852                                 ins->sreg1 = sp [0]->dreg;
11853                                 ins->type = STACK_I4;
11854                                 ins->dreg = alloc_ireg (cfg);
11855                                 MONO_ADD_INS (cfg->cbb, ins);
11856                                 *sp = mono_decompose_opcode (cfg, ins);
11857                         }
11858
11859                         if (context_used) {
11860                                 MonoInst *args [3];
11861                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11862                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11863
11864                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11865
11866                                 /* vtable */
11867                                 args [0] = emit_get_rgctx_klass (cfg, context_used,
11868                                         array_class, MONO_RGCTX_INFO_VTABLE);
11869                                 /* array len */
11870                                 args [1] = sp [0];
11871
11872                                 if (managed_alloc)
11873                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11874                                 else
11875                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11876                         } else {
11877                                 if (cfg->opt & MONO_OPT_SHARED) {
11878                                         /* Decompose now to avoid problems with references to the domainvar */
11879                                         MonoInst *iargs [3];
11880
11881                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11882                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11883                                         iargs [2] = sp [0];
11884
11885                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11886                                 } else {
11887                                         /* Decompose later since it is needed by abcrem */
11888                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11889                                         mono_class_vtable (cfg->domain, array_type);
11890                                         CHECK_TYPELOAD (array_type);
11891
11892                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11893                                         ins->dreg = alloc_ireg_ref (cfg);
11894                                         ins->sreg1 = sp [0]->dreg;
11895                                         ins->inst_newa_class = klass;
11896                                         ins->type = STACK_OBJ;
11897                                         ins->klass = array_type;
11898                                         MONO_ADD_INS (cfg->cbb, ins);
11899                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11900                                         cfg->cbb->has_array_access = TRUE;
11901
11902                                         /* Needed so mono_emit_load_get_addr () gets called */
11903                                         mono_get_got_var (cfg);
11904                                 }
11905                         }
11906
11907                         len_ins = sp [0];
11908                         ip += 5;
11909                         *sp++ = ins;
11910                         inline_costs += 1;
11911
11912                         /* 
11913                          * we inline/optimize the initialization sequence if possible.
11914                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11915                          * for small sizes open code the memcpy
11916                          * ensure the rva field is big enough
11917                          */
11918                         if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, cfg->cbb, ip + 6) && (len_ins->opcode == OP_ICONST) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, klass, len_ins->inst_c0, &data_size, &field_token))) {
11919                                 MonoMethod *memcpy_method = get_memcpy_method ();
11920                                 MonoInst *iargs [3];
11921                                 int add_reg = alloc_ireg_mp (cfg);
11922
11923                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11924                                 if (cfg->compile_aot) {
11925                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11926                                 } else {
11927                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11928                                 }
11929                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11930                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11931                                 ip += 11;
11932                         }
11933
11934                         break;
11935                 }
11936                 case CEE_LDLEN:
11937                         CHECK_STACK (1);
11938                         --sp;
11939                         if (sp [0]->type != STACK_OBJ)
11940                                 UNVERIFIED;
11941
11942                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11943                         ins->dreg = alloc_preg (cfg);
11944                         ins->sreg1 = sp [0]->dreg;
11945                         ins->type = STACK_I4;
11946                         /* This flag will be inherited by the decomposition */
11947                         ins->flags |= MONO_INST_FAULT;
11948                         MONO_ADD_INS (cfg->cbb, ins);
11949                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11950                         cfg->cbb->has_array_access = TRUE;
11951                         ip ++;
11952                         *sp++ = ins;
11953                         break;
11954                 case CEE_LDELEMA:
11955                         CHECK_STACK (2);
11956                         sp -= 2;
11957                         CHECK_OPSIZE (5);
11958                         if (sp [0]->type != STACK_OBJ)
11959                                 UNVERIFIED;
11960
11961                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11962
11963                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11964                         CHECK_TYPELOAD (klass);
11965                         /* we need to make sure that this array is exactly the type it needs
11966                          * to be for correctness. the wrappers are lax with their usage
11967                          * so we need to ignore them here
11968                          */
11969                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11970                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11971                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11972                                 CHECK_TYPELOAD (array_class);
11973                         }
11974
11975                         readonly = FALSE;
11976                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11977                         *sp++ = ins;
11978                         ip += 5;
11979                         break;
11980                 case CEE_LDELEM:
11981                 case CEE_LDELEM_I1:
11982                 case CEE_LDELEM_U1:
11983                 case CEE_LDELEM_I2:
11984                 case CEE_LDELEM_U2:
11985                 case CEE_LDELEM_I4:
11986                 case CEE_LDELEM_U4:
11987                 case CEE_LDELEM_I8:
11988                 case CEE_LDELEM_I:
11989                 case CEE_LDELEM_R4:
11990                 case CEE_LDELEM_R8:
11991                 case CEE_LDELEM_REF: {
11992                         MonoInst *addr;
11993
11994                         CHECK_STACK (2);
11995                         sp -= 2;
11996
11997                         if (*ip == CEE_LDELEM) {
11998                                 CHECK_OPSIZE (5);
11999                                 token = read32 (ip + 1);
12000                                 klass = mini_get_class (method, token, generic_context);
12001                                 CHECK_TYPELOAD (klass);
12002                                 mono_class_init (klass);
12003                         }
12004                         else
12005                                 klass = array_access_to_klass (*ip);
12006
12007                         if (sp [0]->type != STACK_OBJ)
12008                                 UNVERIFIED;
12009
12010                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
12011
12012                         if (mini_is_gsharedvt_variable_klass (klass)) {
12013                                 // FIXME-VT: OP_ICONST optimization
12014                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
12015                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
12016                                 ins->opcode = OP_LOADV_MEMBASE;
12017                         } else if (sp [1]->opcode == OP_ICONST) {
12018                                 int array_reg = sp [0]->dreg;
12019                                 int index_reg = sp [1]->dreg;
12020                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
12021
12022                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
12023                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
12024
12025                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
12026                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
12027                         } else {
12028                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
12029                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
12030                         }
12031                         *sp++ = ins;
12032                         if (*ip == CEE_LDELEM)
12033                                 ip += 5;
12034                         else
12035                                 ++ip;
12036                         break;
12037                 }
12038                 case CEE_STELEM_I:
12039                 case CEE_STELEM_I1:
12040                 case CEE_STELEM_I2:
12041                 case CEE_STELEM_I4:
12042                 case CEE_STELEM_I8:
12043                 case CEE_STELEM_R4:
12044                 case CEE_STELEM_R8:
12045                 case CEE_STELEM_REF:
12046                 case CEE_STELEM: {
12047                         CHECK_STACK (3);
12048                         sp -= 3;
12049
12050                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
12051
12052                         if (*ip == CEE_STELEM) {
12053                                 CHECK_OPSIZE (5);
12054                                 token = read32 (ip + 1);
12055                                 klass = mini_get_class (method, token, generic_context);
12056                                 CHECK_TYPELOAD (klass);
12057                                 mono_class_init (klass);
12058                         }
12059                         else
12060                                 klass = array_access_to_klass (*ip);
12061
12062                         if (sp [0]->type != STACK_OBJ)
12063                                 UNVERIFIED;
12064
12065                         emit_array_store (cfg, klass, sp, TRUE);
12066
12067                         if (*ip == CEE_STELEM)
12068                                 ip += 5;
12069                         else
12070                                 ++ip;
12071                         inline_costs += 1;
12072                         break;
12073                 }
12074                 case CEE_CKFINITE: {
12075                         CHECK_STACK (1);
12076                         --sp;
12077
12078                         if (cfg->llvm_only) {
12079                                 MonoInst *iargs [1];
12080
12081                                 iargs [0] = sp [0];
12082                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
12083                         } else  {
12084                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
12085                                 ins->sreg1 = sp [0]->dreg;
12086                                 ins->dreg = alloc_freg (cfg);
12087                                 ins->type = STACK_R8;
12088                                 MONO_ADD_INS (cfg->cbb, ins);
12089
12090                                 *sp++ = mono_decompose_opcode (cfg, ins);
12091                         }
12092
12093                         ++ip;
12094                         break;
12095                 }
12096                 case CEE_REFANYVAL: {
12097                         MonoInst *src_var, *src;
12098
12099                         int klass_reg = alloc_preg (cfg);
12100                         int dreg = alloc_preg (cfg);
12101
12102                         GSHAREDVT_FAILURE (*ip);
12103
12104                         CHECK_STACK (1);
12105                         MONO_INST_NEW (cfg, ins, *ip);
12106                         --sp;
12107                         CHECK_OPSIZE (5);
12108                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
12109                         CHECK_TYPELOAD (klass);
12110
12111                         context_used = mini_class_check_context_used (cfg, klass);
12112
12113                         // FIXME:
12114                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12115                         if (!src_var)
12116                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12117                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12118                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
12119
12120                         if (context_used) {
12121                                 MonoInst *klass_ins;
12122
12123                                 klass_ins = emit_get_rgctx_klass (cfg, context_used,
12124                                                 klass, MONO_RGCTX_INFO_KLASS);
12125
12126                                 // FIXME:
12127                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
12128                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
12129                         } else {
12130                                 mini_emit_class_check (cfg, klass_reg, klass);
12131                         }
12132                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
12133                         ins->type = STACK_MP;
12134                         ins->klass = klass;
12135                         *sp++ = ins;
12136                         ip += 5;
12137                         break;
12138                 }
12139                 case CEE_MKREFANY: {
12140                         MonoInst *loc, *addr;
12141
12142                         GSHAREDVT_FAILURE (*ip);
12143
12144                         CHECK_STACK (1);
12145                         MONO_INST_NEW (cfg, ins, *ip);
12146                         --sp;
12147                         CHECK_OPSIZE (5);
12148                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
12149                         CHECK_TYPELOAD (klass);
12150
12151                         context_used = mini_class_check_context_used (cfg, klass);
12152
12153                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
12154                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
12155
12156                         if (context_used) {
12157                                 MonoInst *const_ins;
12158                                 int type_reg = alloc_preg (cfg);
12159
12160                                 const_ins = emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
12161                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
12162                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
12163                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
12164                         } else if (cfg->compile_aot) {
12165                                 int const_reg = alloc_preg (cfg);
12166                                 int type_reg = alloc_preg (cfg);
12167
12168                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
12169                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
12170                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
12171                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
12172                         } else {
12173                                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREP_MEMBASE_IMM, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), &klass->byval_arg);
12174                                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREP_MEMBASE_IMM, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), klass);
12175                         }
12176                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
12177
12178                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
12179                         ins->type = STACK_VTYPE;
12180                         ins->klass = mono_defaults.typed_reference_class;
12181                         *sp++ = ins;
12182                         ip += 5;
12183                         break;
12184                 }
12185                 case CEE_LDTOKEN: {
12186                         gpointer handle;
12187                         MonoClass *handle_class;
12188
12189                         CHECK_STACK_OVF (1);
12190
12191                         CHECK_OPSIZE (5);
12192                         n = read32 (ip + 1);
12193
12194                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
12195                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
12196                                 handle = mono_method_get_wrapper_data (method, n);
12197                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
12198                                 if (handle_class == mono_defaults.typehandle_class)
12199                                         handle = &((MonoClass*)handle)->byval_arg;
12200                         }
12201                         else {
12202                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
12203                                 CHECK_CFG_ERROR;
12204                         }
12205                         if (!handle)
12206                                 LOAD_ERROR;
12207                         mono_class_init (handle_class);
12208                         if (cfg->gshared) {
12209                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
12210                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
12211                                         /* This case handles ldtoken
12212                                            of an open type, like for
12213                                            typeof(Gen<>). */
12214                                         context_used = 0;
12215                                 } else if (handle_class == mono_defaults.typehandle_class) {
12216                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
12217                                 } else if (handle_class == mono_defaults.fieldhandle_class)
12218                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
12219                                 else if (handle_class == mono_defaults.methodhandle_class)
12220                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
12221                                 else
12222                                         g_assert_not_reached ();
12223                         }
12224
12225                         if ((cfg->opt & MONO_OPT_SHARED) &&
12226                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
12227                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
12228                                 MonoInst *addr, *vtvar, *iargs [3];
12229                                 int method_context_used;
12230
12231                                 method_context_used = mini_method_check_context_used (cfg, method);
12232
12233                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
12234
12235                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
12236                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
12237                                 if (method_context_used) {
12238                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
12239                                                 method, MONO_RGCTX_INFO_METHOD);
12240                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
12241                                 } else {
12242                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
12243                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
12244                                 }
12245                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12246
12247                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
12248
12249                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12250                         } else {
12251                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
12252                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
12253                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
12254                                         (cmethod->klass == mono_defaults.systemtype_class) &&
12255                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
12256                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
12257
12258                                         mono_class_init (tclass);
12259                                         if (context_used) {
12260                                                 ins = emit_get_rgctx_klass (cfg, context_used,
12261                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
12262                                         } else if (cfg->compile_aot) {
12263                                                 if (method->wrapper_type) {
12264                                                         mono_error_init (&error); //got to do it since there are multiple conditionals below
12265                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
12266                                                                 /* Special case for static synchronized wrappers */
12267                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
12268                                                         } else {
12269                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
12270                                                                 /* FIXME: n is not a normal token */
12271                                                                 DISABLE_AOT (cfg);
12272                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12273                                                         }
12274                                                 } else {
12275                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
12276                                                 }
12277                                         } else {
12278                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
12279                                                 CHECK_CFG_ERROR;
12280                                                 EMIT_NEW_PCONST (cfg, ins, rt);
12281                                         }
12282                                         ins->type = STACK_OBJ;
12283                                         ins->klass = cmethod->klass;
12284                                         ip += 5;
12285                                 } else {
12286                                         MonoInst *addr, *vtvar;
12287
12288                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
12289
12290                                         if (context_used) {
12291                                                 if (handle_class == mono_defaults.typehandle_class) {
12292                                                         ins = emit_get_rgctx_klass (cfg, context_used,
12293                                                                         mono_class_from_mono_type ((MonoType *)handle),
12294                                                                         MONO_RGCTX_INFO_TYPE);
12295                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
12296                                                         ins = emit_get_rgctx_method (cfg, context_used,
12297                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
12298                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
12299                                                         ins = emit_get_rgctx_field (cfg, context_used,
12300                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
12301                                                 } else {
12302                                                         g_assert_not_reached ();
12303                                                 }
12304                                         } else if (cfg->compile_aot) {
12305                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
12306                                         } else {
12307                                                 EMIT_NEW_PCONST (cfg, ins, handle);
12308                                         }
12309                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12310                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
12311                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12312                                 }
12313                         }
12314
12315                         *sp++ = ins;
12316                         ip += 5;
12317                         break;
12318                 }
12319                 case CEE_THROW:
12320                         CHECK_STACK (1);
12321                         MONO_INST_NEW (cfg, ins, OP_THROW);
12322                         --sp;
12323                         ins->sreg1 = sp [0]->dreg;
12324                         ip++;
12325                         cfg->cbb->out_of_line = TRUE;
12326                         MONO_ADD_INS (cfg->cbb, ins);
12327                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12328                         MONO_ADD_INS (cfg->cbb, ins);
12329                         sp = stack_start;
12330                         
12331                         link_bblock (cfg, cfg->cbb, end_bblock);
12332                         start_new_bblock = 1;
12333                         /* This can complicate code generation for llvm since the return value might not be defined */
12334                         if (COMPILE_LLVM (cfg))
12335                                 INLINE_FAILURE ("throw");
12336                         break;
12337                 case CEE_ENDFINALLY:
12338                         /* mono_save_seq_point_info () depends on this */
12339                         if (sp != stack_start)
12340                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
12341                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
12342                         MONO_ADD_INS (cfg->cbb, ins);
12343                         ip++;
12344                         start_new_bblock = 1;
12345
12346                         /*
12347                          * Control will leave the method so empty the stack, otherwise
12348                          * the next basic block will start with a nonempty stack.
12349                          */
12350                         while (sp != stack_start) {
12351                                 sp--;
12352                         }
12353                         break;
12354                 case CEE_LEAVE:
12355                 case CEE_LEAVE_S: {
12356                         GList *handlers;
12357
12358                         if (*ip == CEE_LEAVE) {
12359                                 CHECK_OPSIZE (5);
12360                                 target = ip + 5 + (gint32)read32(ip + 1);
12361                         } else {
12362                                 CHECK_OPSIZE (2);
12363                                 target = ip + 2 + (signed char)(ip [1]);
12364                         }
12365
12366                         /* empty the stack */
12367                         while (sp != stack_start) {
12368                                 sp--;
12369                         }
12370
12371                         /* 
12372                          * If this leave statement is in a catch block, check for a
12373                          * pending exception, and rethrow it if necessary.
12374                          * We avoid doing this in runtime invoke wrappers, since those are called
12375                          * by native code which excepts the wrapper to catch all exceptions.
12376                          */
12377                         for (i = 0; i < header->num_clauses; ++i) {
12378                                 MonoExceptionClause *clause = &header->clauses [i];
12379
12380                                 /* 
12381                                  * Use <= in the final comparison to handle clauses with multiple
12382                                  * leave statements, like in bug #78024.
12383                                  * The ordering of the exception clauses guarantees that we find the
12384                                  * innermost clause.
12385                                  */
12386                                 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) && (ip - header->code + ((*ip == CEE_LEAVE) ? 5 : 2)) <= (clause->handler_offset + clause->handler_len) && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
12387                                         MonoInst *exc_ins;
12388                                         MonoBasicBlock *dont_throw;
12389
12390                                         /*
12391                                           MonoInst *load;
12392
12393                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
12394                                         */
12395
12396                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
12397
12398                                         NEW_BBLOCK (cfg, dont_throw);
12399
12400                                         /*
12401                                          * Currently, we always rethrow the abort exception, despite the 
12402                                          * fact that this is not correct. See thread6.cs for an example. 
12403                                          * But propagating the abort exception is more important than 
12404                                          * getting the sematics right.
12405                                          */
12406                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
12407                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
12408                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
12409
12410                                         MONO_START_BB (cfg, dont_throw);
12411                                 }
12412                         }
12413
12414 #ifdef ENABLE_LLVM
12415                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
12416 #endif
12417
12418                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
12419                                 GList *tmp;
12420                                 MonoExceptionClause *clause;
12421
12422                                 for (tmp = handlers; tmp; tmp = tmp->next) {
12423                                         clause = (MonoExceptionClause *)tmp->data;
12424                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
12425                                         g_assert (tblock);
12426                                         link_bblock (cfg, cfg->cbb, tblock);
12427                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
12428                                         ins->inst_target_bb = tblock;
12429                                         ins->inst_eh_block = clause;
12430                                         MONO_ADD_INS (cfg->cbb, ins);
12431                                         cfg->cbb->has_call_handler = 1;
12432                                         if (COMPILE_LLVM (cfg)) {
12433                                                 MonoBasicBlock *target_bb;
12434
12435                                                 /* 
12436                                                  * Link the finally bblock with the target, since it will
12437                                                  * conceptually branch there.
12438                                                  */
12439                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
12440                                                 GET_BBLOCK (cfg, target_bb, target);
12441                                                 link_bblock (cfg, tblock, target_bb);
12442                                         }
12443                                 }
12444                                 g_list_free (handlers);
12445                         } 
12446
12447                         MONO_INST_NEW (cfg, ins, OP_BR);
12448                         MONO_ADD_INS (cfg->cbb, ins);
12449                         GET_BBLOCK (cfg, tblock, target);
12450                         link_bblock (cfg, cfg->cbb, tblock);
12451                         ins->inst_target_bb = tblock;
12452
12453                         start_new_bblock = 1;
12454
12455                         if (*ip == CEE_LEAVE)
12456                                 ip += 5;
12457                         else
12458                                 ip += 2;
12459
12460                         break;
12461                 }
12462
12463                         /*
12464                          * Mono specific opcodes
12465                          */
12466                 case MONO_CUSTOM_PREFIX: {
12467
12468                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
12469
12470                         CHECK_OPSIZE (2);
12471                         switch (ip [1]) {
12472                         case CEE_MONO_ICALL: {
12473                                 gpointer func;
12474                                 MonoJitICallInfo *info;
12475
12476                                 token = read32 (ip + 2);
12477                                 func = mono_method_get_wrapper_data (method, token);
12478                                 info = mono_find_jit_icall_by_addr (func);
12479                                 if (!info)
12480                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
12481                                 g_assert (info);
12482
12483                                 CHECK_STACK (info->sig->param_count);
12484                                 sp -= info->sig->param_count;
12485
12486                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
12487                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
12488                                         *sp++ = ins;
12489
12490                                 ip += 6;
12491                                 inline_costs += 10 * num_calls++;
12492
12493                                 break;
12494                         }
12495                         case CEE_MONO_LDPTR_CARD_TABLE:
12496                         case CEE_MONO_LDPTR_NURSERY_START:
12497                         case CEE_MONO_LDPTR_NURSERY_BITS:
12498                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
12499                                 CHECK_STACK_OVF (1);
12500
12501                                 switch (ip [1]) {
12502                                         case CEE_MONO_LDPTR_CARD_TABLE:
12503                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
12504                                                 break;
12505                                         case CEE_MONO_LDPTR_NURSERY_START:
12506                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
12507                                                 break;
12508                                         case CEE_MONO_LDPTR_NURSERY_BITS:
12509                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
12510                                                 break;
12511                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
12512                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
12513                                                 break;
12514                                 }
12515
12516                                 *sp++ = ins;
12517                                 ip += 2;
12518                                 inline_costs += 10 * num_calls++;
12519                                 break;
12520                         }
12521                         case CEE_MONO_LDPTR: {
12522                                 gpointer ptr;
12523
12524                                 CHECK_STACK_OVF (1);
12525                                 CHECK_OPSIZE (6);
12526                                 token = read32 (ip + 2);
12527
12528                                 ptr = mono_method_get_wrapper_data (method, token);
12529                                 EMIT_NEW_PCONST (cfg, ins, ptr);
12530                                 *sp++ = ins;
12531                                 ip += 6;
12532                                 inline_costs += 10 * num_calls++;
12533                                 /* Can't embed random pointers into AOT code */
12534                                 DISABLE_AOT (cfg);
12535                                 break;
12536                         }
12537                         case CEE_MONO_JIT_ICALL_ADDR: {
12538                                 MonoJitICallInfo *callinfo;
12539                                 gpointer ptr;
12540
12541                                 CHECK_STACK_OVF (1);
12542                                 CHECK_OPSIZE (6);
12543                                 token = read32 (ip + 2);
12544
12545                                 ptr = mono_method_get_wrapper_data (method, token);
12546                                 callinfo = mono_find_jit_icall_by_addr (ptr);
12547                                 g_assert (callinfo);
12548                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
12549                                 *sp++ = ins;
12550                                 ip += 6;
12551                                 inline_costs += 10 * num_calls++;
12552                                 break;
12553                         }
12554                         case CEE_MONO_ICALL_ADDR: {
12555                                 MonoMethod *cmethod;
12556                                 gpointer ptr;
12557
12558                                 CHECK_STACK_OVF (1);
12559                                 CHECK_OPSIZE (6);
12560                                 token = read32 (ip + 2);
12561
12562                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
12563
12564                                 if (cfg->compile_aot) {
12565                                         EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
12566                                 } else {
12567                                         ptr = mono_lookup_internal_call (cmethod);
12568                                         g_assert (ptr);
12569                                         EMIT_NEW_PCONST (cfg, ins, ptr);
12570                                 }
12571                                 *sp++ = ins;
12572                                 ip += 6;
12573                                 break;
12574                         }
12575                         case CEE_MONO_VTADDR: {
12576                                 MonoInst *src_var, *src;
12577
12578                                 CHECK_STACK (1);
12579                                 --sp;
12580
12581                                 // FIXME:
12582                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12583                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
12584                                 *sp++ = src;
12585                                 ip += 2;
12586                                 break;
12587                         }
12588                         case CEE_MONO_NEWOBJ: {
12589                                 MonoInst *iargs [2];
12590
12591                                 CHECK_STACK_OVF (1);
12592                                 CHECK_OPSIZE (6);
12593                                 token = read32 (ip + 2);
12594                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12595                                 mono_class_init (klass);
12596                                 NEW_DOMAINCONST (cfg, iargs [0]);
12597                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
12598                                 NEW_CLASSCONST (cfg, iargs [1], klass);
12599                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
12600                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
12601                                 ip += 6;
12602                                 inline_costs += 10 * num_calls++;
12603                                 break;
12604                         }
12605                         case CEE_MONO_OBJADDR:
12606                                 CHECK_STACK (1);
12607                                 --sp;
12608                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12609                                 ins->dreg = alloc_ireg_mp (cfg);
12610                                 ins->sreg1 = sp [0]->dreg;
12611                                 ins->type = STACK_MP;
12612                                 MONO_ADD_INS (cfg->cbb, ins);
12613                                 *sp++ = ins;
12614                                 ip += 2;
12615                                 break;
12616                         case CEE_MONO_LDNATIVEOBJ:
12617                                 /*
12618                                  * Similar to LDOBJ, but instead load the unmanaged 
12619                                  * representation of the vtype to the stack.
12620                                  */
12621                                 CHECK_STACK (1);
12622                                 CHECK_OPSIZE (6);
12623                                 --sp;
12624                                 token = read32 (ip + 2);
12625                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12626                                 g_assert (klass->valuetype);
12627                                 mono_class_init (klass);
12628
12629                                 {
12630                                         MonoInst *src, *dest, *temp;
12631
12632                                         src = sp [0];
12633                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
12634                                         temp->backend.is_pinvoke = 1;
12635                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
12636                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
12637
12638                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
12639                                         dest->type = STACK_VTYPE;
12640                                         dest->klass = klass;
12641
12642                                         *sp ++ = dest;
12643                                         ip += 6;
12644                                 }
12645                                 break;
12646                         case CEE_MONO_RETOBJ: {
12647                                 /*
12648                                  * Same as RET, but return the native representation of a vtype
12649                                  * to the caller.
12650                                  */
12651                                 g_assert (cfg->ret);
12652                                 g_assert (mono_method_signature (method)->pinvoke); 
12653                                 CHECK_STACK (1);
12654                                 --sp;
12655                                 
12656                                 CHECK_OPSIZE (6);
12657                                 token = read32 (ip + 2);    
12658                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12659
12660                                 if (!cfg->vret_addr) {
12661                                         g_assert (cfg->ret_var_is_local);
12662
12663                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
12664                                 } else {
12665                                         EMIT_NEW_RETLOADA (cfg, ins);
12666                                 }
12667                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
12668                                 
12669                                 if (sp != stack_start)
12670                                         UNVERIFIED;
12671                                 
12672                                 MONO_INST_NEW (cfg, ins, OP_BR);
12673                                 ins->inst_target_bb = end_bblock;
12674                                 MONO_ADD_INS (cfg->cbb, ins);
12675                                 link_bblock (cfg, cfg->cbb, end_bblock);
12676                                 start_new_bblock = 1;
12677                                 ip += 6;
12678                                 break;
12679                         }
12680                         case CEE_MONO_CISINST:
12681                         case CEE_MONO_CCASTCLASS: {
12682                                 int token;
12683                                 CHECK_STACK (1);
12684                                 --sp;
12685                                 CHECK_OPSIZE (6);
12686                                 token = read32 (ip + 2);
12687                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12688                                 if (ip [1] == CEE_MONO_CISINST)
12689                                         ins = handle_cisinst (cfg, klass, sp [0]);
12690                                 else
12691                                         ins = handle_ccastclass (cfg, klass, sp [0]);
12692                                 *sp++ = ins;
12693                                 ip += 6;
12694                                 break;
12695                         }
12696                         case CEE_MONO_SAVE_LMF:
12697                         case CEE_MONO_RESTORE_LMF:
12698                                 ip += 2;
12699                                 break;
12700                         case CEE_MONO_CLASSCONST:
12701                                 CHECK_STACK_OVF (1);
12702                                 CHECK_OPSIZE (6);
12703                                 token = read32 (ip + 2);
12704                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
12705                                 *sp++ = ins;
12706                                 ip += 6;
12707                                 inline_costs += 10 * num_calls++;
12708                                 break;
12709                         case CEE_MONO_NOT_TAKEN:
12710                                 cfg->cbb->out_of_line = TRUE;
12711                                 ip += 2;
12712                                 break;
12713                         case CEE_MONO_TLS: {
12714                                 MonoTlsKey key;
12715
12716                                 CHECK_STACK_OVF (1);
12717                                 CHECK_OPSIZE (6);
12718                                 key = (MonoTlsKey)read32 (ip + 2);
12719                                 g_assert (key < TLS_KEY_NUM);
12720
12721                                 ins = mono_create_tls_get (cfg, key);
12722                                 if (!ins) {
12723                                         if (cfg->compile_aot) {
12724                                                 DISABLE_AOT (cfg);
12725                                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
12726                                                 ins->dreg = alloc_preg (cfg);
12727                                                 ins->type = STACK_PTR;
12728                                         } else {
12729                                                 g_assert_not_reached ();
12730                                         }
12731                                 }
12732                                 ins->type = STACK_PTR;
12733                                 MONO_ADD_INS (cfg->cbb, ins);
12734                                 *sp++ = ins;
12735                                 ip += 6;
12736                                 break;
12737                         }
12738                         case CEE_MONO_DYN_CALL: {
12739                                 MonoCallInst *call;
12740
12741                                 /* It would be easier to call a trampoline, but that would put an
12742                                  * extra frame on the stack, confusing exception handling. So
12743                                  * implement it inline using an opcode for now.
12744                                  */
12745
12746                                 if (!cfg->dyn_call_var) {
12747                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12748                                         /* prevent it from being register allocated */
12749                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
12750                                 }
12751
12752                                 /* Has to use a call inst since it local regalloc expects it */
12753                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
12754                                 ins = (MonoInst*)call;
12755                                 sp -= 2;
12756                                 ins->sreg1 = sp [0]->dreg;
12757                                 ins->sreg2 = sp [1]->dreg;
12758                                 MONO_ADD_INS (cfg->cbb, ins);
12759
12760                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
12761
12762                                 ip += 2;
12763                                 inline_costs += 10 * num_calls++;
12764
12765                                 break;
12766                         }
12767                         case CEE_MONO_MEMORY_BARRIER: {
12768                                 CHECK_OPSIZE (6);
12769                                 emit_memory_barrier (cfg, (int)read32 (ip + 2));
12770                                 ip += 6;
12771                                 break;
12772                         }
12773                         case CEE_MONO_JIT_ATTACH: {
12774                                 MonoInst *args [16], *domain_ins;
12775                                 MonoInst *ad_ins, *jit_tls_ins;
12776                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
12777
12778                                 g_assert (!mono_threads_is_coop_enabled ());
12779
12780                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12781
12782                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12783                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12784
12785                                 ad_ins = mono_get_domain_intrinsic (cfg);
12786                                 jit_tls_ins = mono_get_jit_tls_intrinsic (cfg);
12787
12788                                 if (cfg->backend->have_tls_get && ad_ins && jit_tls_ins) {
12789                                         NEW_BBLOCK (cfg, next_bb);
12790                                         NEW_BBLOCK (cfg, call_bb);
12791
12792                                         if (cfg->compile_aot) {
12793                                                 /* AOT code is only used in the root domain */
12794                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12795                                         } else {
12796                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12797                                         }
12798                                         MONO_ADD_INS (cfg->cbb, ad_ins);
12799                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12800                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12801
12802                                         MONO_ADD_INS (cfg->cbb, jit_tls_ins);
12803                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12804                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12805
12806                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12807                                         MONO_START_BB (cfg, call_bb);
12808                                 }
12809
12810                                 /* AOT code is only used in the root domain */
12811                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12812                                 ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12813                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12814
12815                                 if (next_bb)
12816                                         MONO_START_BB (cfg, next_bb);
12817
12818
12819                                 ip += 2;
12820                                 break;
12821                         }
12822                         case CEE_MONO_JIT_DETACH: {
12823                                 MonoInst *args [16];
12824
12825                                 /* Restore the original domain */
12826                                 dreg = alloc_ireg (cfg);
12827                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12828                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12829                                 ip += 2;
12830                                 break;
12831                         }
12832                         case CEE_MONO_CALLI_EXTRA_ARG: {
12833                                 MonoInst *addr;
12834                                 MonoMethodSignature *fsig;
12835                                 MonoInst *arg;
12836
12837                                 /*
12838                                  * This is the same as CEE_CALLI, but passes an additional argument
12839                                  * to the called method in llvmonly mode.
12840                                  * This is only used by delegate invoke wrappers to call the
12841                                  * actual delegate method.
12842                                  */
12843                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12844
12845                                 CHECK_OPSIZE (6);
12846                                 token = read32 (ip + 2);
12847
12848                                 ins = NULL;
12849
12850                                 cmethod = NULL;
12851                                 CHECK_STACK (1);
12852                                 --sp;
12853                                 addr = *sp;
12854                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12855                                 CHECK_CFG_ERROR;
12856
12857                                 if (cfg->llvm_only)
12858                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12859
12860                                 n = fsig->param_count + fsig->hasthis + 1;
12861
12862                                 CHECK_STACK (n);
12863
12864                                 sp -= n;
12865                                 arg = sp [n - 1];
12866
12867                                 if (cfg->llvm_only) {
12868                                         /*
12869                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12870                                          * cconv. This is set by mono_init_delegate ().
12871                                          */
12872                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12873                                                 MonoInst *callee = addr;
12874                                                 MonoInst *call, *localloc_ins;
12875                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12876                                                 int low_bit_reg = alloc_preg (cfg);
12877
12878                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12879                                                 NEW_BBLOCK (cfg, end_bb);
12880
12881                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12882                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12883                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12884
12885                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12886                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12887                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12888                                                 /*
12889                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12890                                                  */
12891                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12892                                                 ins->dreg = alloc_preg (cfg);
12893                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12894                                                 MONO_ADD_INS (cfg->cbb, ins);
12895                                                 localloc_ins = ins;
12896                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12897                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12898                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12899
12900                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12901                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12902
12903                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12904                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12905                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12906                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12907                                                 ins->dreg = call->dreg;
12908
12909                                                 MONO_START_BB (cfg, end_bb);
12910                                         } else {
12911                                                 /* Caller uses a normal calling conv */
12912
12913                                                 MonoInst *callee = addr;
12914                                                 MonoInst *call, *localloc_ins;
12915                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12916                                                 int low_bit_reg = alloc_preg (cfg);
12917
12918                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12919                                                 NEW_BBLOCK (cfg, end_bb);
12920
12921                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12922                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12923                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12924
12925                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12926                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12927                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12928                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12929                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12930                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12931                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12932                                                 MONO_ADD_INS (cfg->cbb, addr);
12933                                                 /*
12934                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12935                                                  */
12936                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12937                                                 ins->dreg = alloc_preg (cfg);
12938                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12939                                                 MONO_ADD_INS (cfg->cbb, ins);
12940                                                 localloc_ins = ins;
12941                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12942                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12943                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12944
12945                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12946                                                 ins->dreg = call->dreg;
12947                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12948
12949                                                 MONO_START_BB (cfg, end_bb);
12950                                         }
12951                                 } else {
12952                                         /* Same as CEE_CALLI */
12953                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12954                                                 /*
12955                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12956                                                  */
12957                                                 MonoInst *callee = addr;
12958
12959                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12960                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12961                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12962                                         } else {
12963                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12964                                         }
12965                                 }
12966
12967                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12968                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12969
12970                                 CHECK_CFG_EXCEPTION;
12971
12972                                 ip += 6;
12973                                 ins_flag = 0;
12974                                 constrained_class = NULL;
12975                                 break;
12976                         }
12977                         case CEE_MONO_LDDOMAIN:
12978                                 CHECK_STACK_OVF (1);
12979                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12980                                 ip += 2;
12981                                 *sp++ = ins;
12982                                 break;
12983                         default:
12984                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12985                                 break;
12986                         }
12987                         break;
12988                 }
12989
12990                 case CEE_PREFIX1: {
12991                         CHECK_OPSIZE (2);
12992                         switch (ip [1]) {
12993                         case CEE_ARGLIST: {
12994                                 /* somewhat similar to LDTOKEN */
12995                                 MonoInst *addr, *vtvar;
12996                                 CHECK_STACK_OVF (1);
12997                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12998
12999                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
13000                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
13001
13002                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
13003                                 ins->type = STACK_VTYPE;
13004                                 ins->klass = mono_defaults.argumenthandle_class;
13005                                 *sp++ = ins;
13006                                 ip += 2;
13007                                 break;
13008                         }
13009                         case CEE_CEQ:
13010                         case CEE_CGT:
13011                         case CEE_CGT_UN:
13012                         case CEE_CLT:
13013                         case CEE_CLT_UN: {
13014                                 MonoInst *cmp, *arg1, *arg2;
13015
13016                                 CHECK_STACK (2);
13017                                 sp -= 2;
13018                                 arg1 = sp [0];
13019                                 arg2 = sp [1];
13020
13021                                 /*
13022                                  * The following transforms:
13023                                  *    CEE_CEQ    into OP_CEQ
13024                                  *    CEE_CGT    into OP_CGT
13025                                  *    CEE_CGT_UN into OP_CGT_UN
13026                                  *    CEE_CLT    into OP_CLT
13027                                  *    CEE_CLT_UN into OP_CLT_UN
13028                                  */
13029                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
13030
13031                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
13032                                 cmp->sreg1 = arg1->dreg;
13033                                 cmp->sreg2 = arg2->dreg;
13034                                 type_from_op (cfg, cmp, arg1, arg2);
13035                                 CHECK_TYPE (cmp);
13036                                 add_widen_op (cfg, cmp, &arg1, &arg2);
13037                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
13038                                         cmp->opcode = OP_LCOMPARE;
13039                                 else if (arg1->type == STACK_R4)
13040                                         cmp->opcode = OP_RCOMPARE;
13041                                 else if (arg1->type == STACK_R8)
13042                                         cmp->opcode = OP_FCOMPARE;
13043                                 else
13044                                         cmp->opcode = OP_ICOMPARE;
13045                                 MONO_ADD_INS (cfg->cbb, cmp);
13046                                 ins->type = STACK_I4;
13047                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
13048                                 type_from_op (cfg, ins, arg1, arg2);
13049
13050                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
13051                                         /*
13052                                          * The backends expect the fceq opcodes to do the
13053                                          * comparison too.
13054                                          */
13055                                         ins->sreg1 = cmp->sreg1;
13056                                         ins->sreg2 = cmp->sreg2;
13057                                         NULLIFY_INS (cmp);
13058                                 }
13059                                 MONO_ADD_INS (cfg->cbb, ins);
13060                                 *sp++ = ins;
13061                                 ip += 2;
13062                                 break;
13063                         }
13064                         case CEE_LDFTN: {
13065                                 MonoInst *argconst;
13066                                 MonoMethod *cil_method;
13067
13068                                 CHECK_STACK_OVF (1);
13069                                 CHECK_OPSIZE (6);
13070                                 n = read32 (ip + 2);
13071                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
13072                                 CHECK_CFG_ERROR;
13073
13074                                 mono_class_init (cmethod->klass);
13075
13076                                 mono_save_token_info (cfg, image, n, cmethod);
13077
13078                                 context_used = mini_method_check_context_used (cfg, cmethod);
13079
13080                                 cil_method = cmethod;
13081                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
13082                                         METHOD_ACCESS_FAILURE (method, cil_method);
13083
13084                                 if (mono_security_core_clr_enabled ())
13085                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
13086
13087                                 /* 
13088                                  * Optimize the common case of ldftn+delegate creation
13089                                  */
13090                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
13091                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
13092                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
13093                                                 MonoInst *target_ins, *handle_ins;
13094                                                 MonoMethod *invoke;
13095                                                 int invoke_context_used;
13096
13097                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
13098                                                 if (!invoke || !mono_method_signature (invoke))
13099                                                         LOAD_ERROR;
13100
13101                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
13102
13103                                                 target_ins = sp [-1];
13104
13105                                                 if (mono_security_core_clr_enabled ())
13106                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
13107
13108                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
13109                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
13110                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
13111                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
13112                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
13113                                                         }
13114                                                 }
13115
13116                                                 /* FIXME: SGEN support */
13117                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
13118                                                         ip += 6;
13119                                                         if (cfg->verbose_level > 3)
13120                                                                 g_print ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
13121                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
13122                                                                 sp --;
13123                                                                 *sp = handle_ins;
13124                                                                 CHECK_CFG_EXCEPTION;
13125                                                                 ip += 5;
13126                                                                 sp ++;
13127                                                                 break;
13128                                                         }
13129                                                         ip -= 6;
13130                                                 }
13131                                         }
13132                                 }
13133
13134                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
13135                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
13136                                 *sp++ = ins;
13137                                 
13138                                 ip += 6;
13139                                 inline_costs += 10 * num_calls++;
13140                                 break;
13141                         }
13142                         case CEE_LDVIRTFTN: {
13143                                 MonoInst *args [2];
13144
13145                                 CHECK_STACK (1);
13146                                 CHECK_OPSIZE (6);
13147                                 n = read32 (ip + 2);
13148                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
13149                                 CHECK_CFG_ERROR;
13150
13151                                 mono_class_init (cmethod->klass);
13152  
13153                                 context_used = mini_method_check_context_used (cfg, cmethod);
13154
13155                                 if (mono_security_core_clr_enabled ())
13156                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
13157
13158                                 /*
13159                                  * Optimize the common case of ldvirtftn+delegate creation
13160                                  */
13161                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ip > header->code && ip [-1] == CEE_DUP)) {
13162                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
13163                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
13164                                                 MonoInst *target_ins, *handle_ins;
13165                                                 MonoMethod *invoke;
13166                                                 int invoke_context_used;
13167                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
13168
13169                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
13170                                                 if (!invoke || !mono_method_signature (invoke))
13171                                                         LOAD_ERROR;
13172
13173                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
13174
13175                                                 target_ins = sp [-1];
13176
13177                                                 if (mono_security_core_clr_enabled ())
13178                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
13179
13180                                                 /* FIXME: SGEN support */
13181                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
13182                                                         ip += 6;
13183                                                         if (cfg->verbose_level > 3)
13184                                                                 g_print ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
13185                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
13186                                                                 sp -= 2;
13187                                                                 *sp = handle_ins;
13188                                                                 CHECK_CFG_EXCEPTION;
13189                                                                 ip += 5;
13190                                                                 sp ++;
13191                                                                 break;
13192                                                         }
13193                                                         ip -= 6;
13194                                                 }
13195                                         }
13196                                 }
13197
13198                                 --sp;
13199                                 args [0] = *sp;
13200
13201                                 args [1] = emit_get_rgctx_method (cfg, context_used,
13202                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
13203
13204                                 if (context_used)
13205                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
13206                                 else
13207                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
13208
13209                                 ip += 6;
13210                                 inline_costs += 10 * num_calls++;
13211                                 break;
13212                         }
13213                         case CEE_LDARG:
13214                                 CHECK_STACK_OVF (1);
13215                                 CHECK_OPSIZE (4);
13216                                 n = read16 (ip + 2);
13217                                 CHECK_ARG (n);
13218                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
13219                                 *sp++ = ins;
13220                                 ip += 4;
13221                                 break;
13222                         case CEE_LDARGA:
13223                                 CHECK_STACK_OVF (1);
13224                                 CHECK_OPSIZE (4);
13225                                 n = read16 (ip + 2);
13226                                 CHECK_ARG (n);
13227                                 NEW_ARGLOADA (cfg, ins, n);
13228                                 MONO_ADD_INS (cfg->cbb, ins);
13229                                 *sp++ = ins;
13230                                 ip += 4;
13231                                 break;
13232                         case CEE_STARG:
13233                                 CHECK_STACK (1);
13234                                 --sp;
13235                                 CHECK_OPSIZE (4);
13236                                 n = read16 (ip + 2);
13237                                 CHECK_ARG (n);
13238                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
13239                                         UNVERIFIED;
13240                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
13241                                 ip += 4;
13242                                 break;
13243                         case CEE_LDLOC:
13244                                 CHECK_STACK_OVF (1);
13245                                 CHECK_OPSIZE (4);
13246                                 n = read16 (ip + 2);
13247                                 CHECK_LOCAL (n);
13248                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
13249                                 *sp++ = ins;
13250                                 ip += 4;
13251                                 break;
13252                         case CEE_LDLOCA: {
13253                                 unsigned char *tmp_ip;
13254                                 CHECK_STACK_OVF (1);
13255                                 CHECK_OPSIZE (4);
13256                                 n = read16 (ip + 2);
13257                                 CHECK_LOCAL (n);
13258
13259                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
13260                                         ip = tmp_ip;
13261                                         inline_costs += 1;
13262                                         break;
13263                                 }                       
13264                                 
13265                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
13266                                 *sp++ = ins;
13267                                 ip += 4;
13268                                 break;
13269                         }
13270                         case CEE_STLOC:
13271                                 CHECK_STACK (1);
13272                                 --sp;
13273                                 CHECK_OPSIZE (4);
13274                                 n = read16 (ip + 2);
13275                                 CHECK_LOCAL (n);
13276                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
13277                                         UNVERIFIED;
13278                                 emit_stloc_ir (cfg, sp, header, n);
13279                                 ip += 4;
13280                                 inline_costs += 1;
13281                                 break;
13282                         case CEE_LOCALLOC:
13283                                 CHECK_STACK (1);
13284                                 --sp;
13285                                 if (sp != stack_start) 
13286                                         UNVERIFIED;
13287                                 if (cfg->method != method) 
13288                                         /* 
13289                                          * Inlining this into a loop in a parent could lead to 
13290                                          * stack overflows which is different behavior than the
13291                                          * non-inlined case, thus disable inlining in this case.
13292                                          */
13293                                         INLINE_FAILURE("localloc");
13294
13295                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
13296                                 ins->dreg = alloc_preg (cfg);
13297                                 ins->sreg1 = sp [0]->dreg;
13298                                 ins->type = STACK_PTR;
13299                                 MONO_ADD_INS (cfg->cbb, ins);
13300
13301                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
13302                                 if (init_locals)
13303                                         ins->flags |= MONO_INST_INIT;
13304
13305                                 *sp++ = ins;
13306                                 ip += 2;
13307                                 break;
13308                         case CEE_ENDFILTER: {
13309                                 MonoExceptionClause *clause, *nearest;
13310                                 int cc;
13311
13312                                 CHECK_STACK (1);
13313                                 --sp;
13314                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
13315                                         UNVERIFIED;
13316                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
13317                                 ins->sreg1 = (*sp)->dreg;
13318                                 MONO_ADD_INS (cfg->cbb, ins);
13319                                 start_new_bblock = 1;
13320                                 ip += 2;
13321
13322                                 nearest = NULL;
13323                                 for (cc = 0; cc < header->num_clauses; ++cc) {
13324                                         clause = &header->clauses [cc];
13325                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
13326                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
13327                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
13328                                                 nearest = clause;
13329                                 }
13330                                 g_assert (nearest);
13331                                 if ((ip - header->code) != nearest->handler_offset)
13332                                         UNVERIFIED;
13333
13334                                 break;
13335                         }
13336                         case CEE_UNALIGNED_:
13337                                 ins_flag |= MONO_INST_UNALIGNED;
13338                                 /* FIXME: record alignment? we can assume 1 for now */
13339                                 CHECK_OPSIZE (3);
13340                                 ip += 3;
13341                                 break;
13342                         case CEE_VOLATILE_:
13343                                 ins_flag |= MONO_INST_VOLATILE;
13344                                 ip += 2;
13345                                 break;
13346                         case CEE_TAIL_:
13347                                 ins_flag   |= MONO_INST_TAILCALL;
13348                                 cfg->flags |= MONO_CFG_HAS_TAIL;
13349                                 /* Can't inline tail calls at this time */
13350                                 inline_costs += 100000;
13351                                 ip += 2;
13352                                 break;
13353                         case CEE_INITOBJ:
13354                                 CHECK_STACK (1);
13355                                 --sp;
13356                                 CHECK_OPSIZE (6);
13357                                 token = read32 (ip + 2);
13358                                 klass = mini_get_class (method, token, generic_context);
13359                                 CHECK_TYPELOAD (klass);
13360                                 if (generic_class_is_reference_type (cfg, klass))
13361                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
13362                                 else
13363                                         mini_emit_initobj (cfg, *sp, NULL, klass);
13364                                 ip += 6;
13365                                 inline_costs += 1;
13366                                 break;
13367                         case CEE_CONSTRAINED_:
13368                                 CHECK_OPSIZE (6);
13369                                 token = read32 (ip + 2);
13370                                 constrained_class = mini_get_class (method, token, generic_context);
13371                                 CHECK_TYPELOAD (constrained_class);
13372                                 ip += 6;
13373                                 break;
13374                         case CEE_CPBLK:
13375                         case CEE_INITBLK: {
13376                                 MonoInst *iargs [3];
13377                                 CHECK_STACK (3);
13378                                 sp -= 3;
13379
13380                                 /* Skip optimized paths for volatile operations. */
13381                                 if ((ip [1] == CEE_CPBLK) && !(ins_flag & MONO_INST_VOLATILE) && (cfg->opt & MONO_OPT_INTRINS) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
13382                                         mini_emit_memcpy (cfg, sp [0]->dreg, 0, sp [1]->dreg, 0, sp [2]->inst_c0, 0);
13383                                 } else if ((ip [1] == CEE_INITBLK) && !(ins_flag & MONO_INST_VOLATILE) && (cfg->opt & MONO_OPT_INTRINS) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5) && (sp [1]->opcode == OP_ICONST) && (sp [1]->inst_c0 == 0)) {
13384                                         /* emit_memset only works when val == 0 */
13385                                         mini_emit_memset (cfg, sp [0]->dreg, 0, sp [2]->inst_c0, sp [1]->inst_c0, 0);
13386                                 } else {
13387                                         MonoInst *call;
13388                                         iargs [0] = sp [0];
13389                                         iargs [1] = sp [1];
13390                                         iargs [2] = sp [2];
13391                                         if (ip [1] == CEE_CPBLK) {
13392                                                 /*
13393                                                  * FIXME: It's unclear whether we should be emitting both the acquire
13394                                                  * and release barriers for cpblk. It is technically both a load and
13395                                                  * store operation, so it seems like that's the sensible thing to do.
13396                                                  *
13397                                                  * FIXME: We emit full barriers on both sides of the operation for
13398                                                  * simplicity. We should have a separate atomic memcpy method instead.
13399                                                  */
13400                                                 MonoMethod *memcpy_method = get_memcpy_method ();
13401
13402                                                 if (ins_flag & MONO_INST_VOLATILE)
13403                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
13404
13405                                                 call = mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
13406                                                 call->flags |= ins_flag;
13407
13408                                                 if (ins_flag & MONO_INST_VOLATILE)
13409                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
13410                                         } else {
13411                                                 MonoMethod *memset_method = get_memset_method ();
13412                                                 if (ins_flag & MONO_INST_VOLATILE) {
13413                                                         /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
13414                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
13415                                                 }
13416                                                 call = mono_emit_method_call (cfg, memset_method, iargs, NULL);
13417                                                 call->flags |= ins_flag;
13418                                         }
13419                                 }
13420                                 ip += 2;
13421                                 ins_flag = 0;
13422                                 inline_costs += 1;
13423                                 break;
13424                         }
13425                         case CEE_NO_:
13426                                 CHECK_OPSIZE (3);
13427                                 if (ip [2] & 0x1)
13428                                         ins_flag |= MONO_INST_NOTYPECHECK;
13429                                 if (ip [2] & 0x2)
13430                                         ins_flag |= MONO_INST_NORANGECHECK;
13431                                 /* we ignore the no-nullcheck for now since we
13432                                  * really do it explicitly only when doing callvirt->call
13433                                  */
13434                                 ip += 3;
13435                                 break;
13436                         case CEE_RETHROW: {
13437                                 MonoInst *load;
13438                                 int handler_offset = -1;
13439
13440                                 for (i = 0; i < header->num_clauses; ++i) {
13441                                         MonoExceptionClause *clause = &header->clauses [i];
13442                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
13443                                                 handler_offset = clause->handler_offset;
13444                                                 break;
13445                                         }
13446                                 }
13447
13448                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
13449
13450                                 if (handler_offset == -1)
13451                                         UNVERIFIED;
13452
13453                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
13454                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
13455                                 ins->sreg1 = load->dreg;
13456                                 MONO_ADD_INS (cfg->cbb, ins);
13457
13458                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
13459                                 MONO_ADD_INS (cfg->cbb, ins);
13460
13461                                 sp = stack_start;
13462                                 link_bblock (cfg, cfg->cbb, end_bblock);
13463                                 start_new_bblock = 1;
13464                                 ip += 2;
13465                                 break;
13466                         }
13467                         case CEE_SIZEOF: {
13468                                 guint32 val;
13469                                 int ialign;
13470
13471                                 CHECK_STACK_OVF (1);
13472                                 CHECK_OPSIZE (6);
13473                                 token = read32 (ip + 2);
13474                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
13475                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
13476                                         CHECK_CFG_ERROR;
13477
13478                                         val = mono_type_size (type, &ialign);
13479                                 } else {
13480                                         MonoClass *klass = mini_get_class (method, token, generic_context);
13481                                         CHECK_TYPELOAD (klass);
13482
13483                                         val = mono_type_size (&klass->byval_arg, &ialign);
13484
13485                                         if (mini_is_gsharedvt_klass (klass))
13486                                                 GSHAREDVT_FAILURE (*ip);
13487                                 }
13488                                 EMIT_NEW_ICONST (cfg, ins, val);
13489                                 *sp++= ins;
13490                                 ip += 6;
13491                                 break;
13492                         }
13493                         case CEE_REFANYTYPE: {
13494                                 MonoInst *src_var, *src;
13495
13496                                 GSHAREDVT_FAILURE (*ip);
13497
13498                                 CHECK_STACK (1);
13499                                 --sp;
13500
13501                                 // FIXME:
13502                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
13503                                 if (!src_var)
13504                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
13505                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
13506                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
13507                                 *sp++ = ins;
13508                                 ip += 2;
13509                                 break;
13510                         }
13511                         case CEE_READONLY_:
13512                                 readonly = TRUE;
13513                                 ip += 2;
13514                                 break;
13515
13516                         case CEE_UNUSED56:
13517                         case CEE_UNUSED57:
13518                         case CEE_UNUSED70:
13519                         case CEE_UNUSED:
13520                         case CEE_UNUSED99:
13521                                 UNVERIFIED;
13522                                 
13523                         default:
13524                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
13525                                 UNVERIFIED;
13526                         }
13527                         break;
13528                 }
13529                 case CEE_UNUSED58:
13530                 case CEE_UNUSED1:
13531                         UNVERIFIED;
13532
13533                 default:
13534                         g_warning ("opcode 0x%02x not handled", *ip);
13535                         UNVERIFIED;
13536                 }
13537         }
13538         if (start_new_bblock != 1)
13539                 UNVERIFIED;
13540
13541         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
13542         if (cfg->cbb->next_bb) {
13543                 /* This could already be set because of inlining, #693905 */
13544                 MonoBasicBlock *bb = cfg->cbb;
13545
13546                 while (bb->next_bb)
13547                         bb = bb->next_bb;
13548                 bb->next_bb = end_bblock;
13549         } else {
13550                 cfg->cbb->next_bb = end_bblock;
13551         }
13552
13553         if (cfg->method == method && cfg->domainvar) {
13554                 MonoInst *store;
13555                 MonoInst *get_domain;
13556
13557                 cfg->cbb = init_localsbb;
13558
13559                 if ((get_domain = mono_get_domain_intrinsic (cfg))) {
13560                         MONO_ADD_INS (cfg->cbb, get_domain);
13561                 } else {
13562                         get_domain = mono_emit_jit_icall (cfg, mono_domain_get, NULL);
13563                 }
13564                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
13565                 MONO_ADD_INS (cfg->cbb, store);
13566         }
13567
13568 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
13569         if (cfg->compile_aot)
13570                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
13571                 mono_get_got_var (cfg);
13572 #endif
13573
13574         if (cfg->method == method && cfg->got_var)
13575                 mono_emit_load_got_addr (cfg);
13576
13577         if (init_localsbb) {
13578                 cfg->cbb = init_localsbb;
13579                 cfg->ip = NULL;
13580                 for (i = 0; i < header->num_locals; ++i) {
13581                         emit_init_local (cfg, i, header->locals [i], init_locals);
13582                 }
13583         }
13584
13585         if (cfg->init_ref_vars && cfg->method == method) {
13586                 /* Emit initialization for ref vars */
13587                 // FIXME: Avoid duplication initialization for IL locals.
13588                 for (i = 0; i < cfg->num_varinfo; ++i) {
13589                         MonoInst *ins = cfg->varinfo [i];
13590
13591                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
13592                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
13593                 }
13594         }
13595
13596         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
13597                 cfg->cbb = init_localsbb;
13598                 emit_push_lmf (cfg);
13599         }
13600
13601         cfg->cbb = init_localsbb;
13602         emit_instrumentation_call (cfg, mono_profiler_method_enter);
13603
13604         if (seq_points) {
13605                 MonoBasicBlock *bb;
13606
13607                 /*
13608                  * Make seq points at backward branch targets interruptable.
13609                  */
13610                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
13611                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
13612                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
13613         }
13614
13615         /* Add a sequence point for method entry/exit events */
13616         if (seq_points && cfg->gen_sdb_seq_points) {
13617                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
13618                 MONO_ADD_INS (init_localsbb, ins);
13619                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
13620                 MONO_ADD_INS (cfg->bb_exit, ins);
13621         }
13622
13623         /*
13624          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
13625          * the code they refer to was dead (#11880).
13626          */
13627         if (sym_seq_points) {
13628                 for (i = 0; i < header->code_size; ++i) {
13629                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
13630                                 MonoInst *ins;
13631
13632                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
13633                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
13634                         }
13635                 }
13636         }
13637
13638         cfg->ip = NULL;
13639
13640         if (cfg->method == method) {
13641                 MonoBasicBlock *bb;
13642                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13643                         bb->region = mono_find_block_region (cfg, bb->real_offset);
13644                         if (cfg->spvars)
13645                                 mono_create_spvar_for_region (cfg, bb->region);
13646                         if (cfg->verbose_level > 2)
13647                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
13648                 }
13649         } else {
13650                 MonoBasicBlock *bb;
13651                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
13652                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
13653                         bb->real_offset = inline_offset;
13654                 }
13655         }
13656
13657         if (inline_costs < 0) {
13658                 char *mname;
13659
13660                 /* Method is too large */
13661                 mname = mono_method_full_name (method, TRUE);
13662                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
13663                 g_free (mname);
13664         }
13665
13666         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
13667                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
13668
13669         goto cleanup;
13670
13671 mono_error_exit:
13672         g_assert (!mono_error_ok (&cfg->error));
13673         goto cleanup;
13674  
13675  exception_exit:
13676         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
13677         goto cleanup;
13678
13679  unverified:
13680         set_exception_type_from_invalid_il (cfg, method, ip);
13681         goto cleanup;
13682
13683  cleanup:
13684         g_slist_free (class_inits);
13685         mono_basic_block_free (original_bb);
13686         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
13687         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
13688         if (cfg->exception_type)
13689                 return -1;
13690         else
13691                 return inline_costs;
13692 }
13693
13694 static int
13695 store_membase_reg_to_store_membase_imm (int opcode)
13696 {
13697         switch (opcode) {
13698         case OP_STORE_MEMBASE_REG:
13699                 return OP_STORE_MEMBASE_IMM;
13700         case OP_STOREI1_MEMBASE_REG:
13701                 return OP_STOREI1_MEMBASE_IMM;
13702         case OP_STOREI2_MEMBASE_REG:
13703                 return OP_STOREI2_MEMBASE_IMM;
13704         case OP_STOREI4_MEMBASE_REG:
13705                 return OP_STOREI4_MEMBASE_IMM;
13706         case OP_STOREI8_MEMBASE_REG:
13707                 return OP_STOREI8_MEMBASE_IMM;
13708         default:
13709                 g_assert_not_reached ();
13710         }
13711
13712         return -1;
13713 }               
13714
13715 int
13716 mono_op_to_op_imm (int opcode)
13717 {
13718         switch (opcode) {
13719         case OP_IADD:
13720                 return OP_IADD_IMM;
13721         case OP_ISUB:
13722                 return OP_ISUB_IMM;
13723         case OP_IDIV:
13724                 return OP_IDIV_IMM;
13725         case OP_IDIV_UN:
13726                 return OP_IDIV_UN_IMM;
13727         case OP_IREM:
13728                 return OP_IREM_IMM;
13729         case OP_IREM_UN:
13730                 return OP_IREM_UN_IMM;
13731         case OP_IMUL:
13732                 return OP_IMUL_IMM;
13733         case OP_IAND:
13734                 return OP_IAND_IMM;
13735         case OP_IOR:
13736                 return OP_IOR_IMM;
13737         case OP_IXOR:
13738                 return OP_IXOR_IMM;
13739         case OP_ISHL:
13740                 return OP_ISHL_IMM;
13741         case OP_ISHR:
13742                 return OP_ISHR_IMM;
13743         case OP_ISHR_UN:
13744                 return OP_ISHR_UN_IMM;
13745
13746         case OP_LADD:
13747                 return OP_LADD_IMM;
13748         case OP_LSUB:
13749                 return OP_LSUB_IMM;
13750         case OP_LAND:
13751                 return OP_LAND_IMM;
13752         case OP_LOR:
13753                 return OP_LOR_IMM;
13754         case OP_LXOR:
13755                 return OP_LXOR_IMM;
13756         case OP_LSHL:
13757                 return OP_LSHL_IMM;
13758         case OP_LSHR:
13759                 return OP_LSHR_IMM;
13760         case OP_LSHR_UN:
13761                 return OP_LSHR_UN_IMM;
13762 #if SIZEOF_REGISTER == 8
13763         case OP_LREM:
13764                 return OP_LREM_IMM;
13765 #endif
13766
13767         case OP_COMPARE:
13768                 return OP_COMPARE_IMM;
13769         case OP_ICOMPARE:
13770                 return OP_ICOMPARE_IMM;
13771         case OP_LCOMPARE:
13772                 return OP_LCOMPARE_IMM;
13773
13774         case OP_STORE_MEMBASE_REG:
13775                 return OP_STORE_MEMBASE_IMM;
13776         case OP_STOREI1_MEMBASE_REG:
13777                 return OP_STOREI1_MEMBASE_IMM;
13778         case OP_STOREI2_MEMBASE_REG:
13779                 return OP_STOREI2_MEMBASE_IMM;
13780         case OP_STOREI4_MEMBASE_REG:
13781                 return OP_STOREI4_MEMBASE_IMM;
13782
13783 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13784         case OP_X86_PUSH:
13785                 return OP_X86_PUSH_IMM;
13786         case OP_X86_COMPARE_MEMBASE_REG:
13787                 return OP_X86_COMPARE_MEMBASE_IMM;
13788 #endif
13789 #if defined(TARGET_AMD64)
13790         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13791                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13792 #endif
13793         case OP_VOIDCALL_REG:
13794                 return OP_VOIDCALL;
13795         case OP_CALL_REG:
13796                 return OP_CALL;
13797         case OP_LCALL_REG:
13798                 return OP_LCALL;
13799         case OP_FCALL_REG:
13800                 return OP_FCALL;
13801         case OP_LOCALLOC:
13802                 return OP_LOCALLOC_IMM;
13803         }
13804
13805         return -1;
13806 }
13807
13808 static int
13809 ldind_to_load_membase (int opcode)
13810 {
13811         switch (opcode) {
13812         case CEE_LDIND_I1:
13813                 return OP_LOADI1_MEMBASE;
13814         case CEE_LDIND_U1:
13815                 return OP_LOADU1_MEMBASE;
13816         case CEE_LDIND_I2:
13817                 return OP_LOADI2_MEMBASE;
13818         case CEE_LDIND_U2:
13819                 return OP_LOADU2_MEMBASE;
13820         case CEE_LDIND_I4:
13821                 return OP_LOADI4_MEMBASE;
13822         case CEE_LDIND_U4:
13823                 return OP_LOADU4_MEMBASE;
13824         case CEE_LDIND_I:
13825                 return OP_LOAD_MEMBASE;
13826         case CEE_LDIND_REF:
13827                 return OP_LOAD_MEMBASE;
13828         case CEE_LDIND_I8:
13829                 return OP_LOADI8_MEMBASE;
13830         case CEE_LDIND_R4:
13831                 return OP_LOADR4_MEMBASE;
13832         case CEE_LDIND_R8:
13833                 return OP_LOADR8_MEMBASE;
13834         default:
13835                 g_assert_not_reached ();
13836         }
13837
13838         return -1;
13839 }
13840
13841 static int
13842 stind_to_store_membase (int opcode)
13843 {
13844         switch (opcode) {
13845         case CEE_STIND_I1:
13846                 return OP_STOREI1_MEMBASE_REG;
13847         case CEE_STIND_I2:
13848                 return OP_STOREI2_MEMBASE_REG;
13849         case CEE_STIND_I4:
13850                 return OP_STOREI4_MEMBASE_REG;
13851         case CEE_STIND_I:
13852         case CEE_STIND_REF:
13853                 return OP_STORE_MEMBASE_REG;
13854         case CEE_STIND_I8:
13855                 return OP_STOREI8_MEMBASE_REG;
13856         case CEE_STIND_R4:
13857                 return OP_STORER4_MEMBASE_REG;
13858         case CEE_STIND_R8:
13859                 return OP_STORER8_MEMBASE_REG;
13860         default:
13861                 g_assert_not_reached ();
13862         }
13863
13864         return -1;
13865 }
13866
13867 int
13868 mono_load_membase_to_load_mem (int opcode)
13869 {
13870         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13871 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13872         switch (opcode) {
13873         case OP_LOAD_MEMBASE:
13874                 return OP_LOAD_MEM;
13875         case OP_LOADU1_MEMBASE:
13876                 return OP_LOADU1_MEM;
13877         case OP_LOADU2_MEMBASE:
13878                 return OP_LOADU2_MEM;
13879         case OP_LOADI4_MEMBASE:
13880                 return OP_LOADI4_MEM;
13881         case OP_LOADU4_MEMBASE:
13882                 return OP_LOADU4_MEM;
13883 #if SIZEOF_REGISTER == 8
13884         case OP_LOADI8_MEMBASE:
13885                 return OP_LOADI8_MEM;
13886 #endif
13887         }
13888 #endif
13889
13890         return -1;
13891 }
13892
13893 static inline int
13894 op_to_op_dest_membase (int store_opcode, int opcode)
13895 {
13896 #if defined(TARGET_X86)
13897         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13898                 return -1;
13899
13900         switch (opcode) {
13901         case OP_IADD:
13902                 return OP_X86_ADD_MEMBASE_REG;
13903         case OP_ISUB:
13904                 return OP_X86_SUB_MEMBASE_REG;
13905         case OP_IAND:
13906                 return OP_X86_AND_MEMBASE_REG;
13907         case OP_IOR:
13908                 return OP_X86_OR_MEMBASE_REG;
13909         case OP_IXOR:
13910                 return OP_X86_XOR_MEMBASE_REG;
13911         case OP_ADD_IMM:
13912         case OP_IADD_IMM:
13913                 return OP_X86_ADD_MEMBASE_IMM;
13914         case OP_SUB_IMM:
13915         case OP_ISUB_IMM:
13916                 return OP_X86_SUB_MEMBASE_IMM;
13917         case OP_AND_IMM:
13918         case OP_IAND_IMM:
13919                 return OP_X86_AND_MEMBASE_IMM;
13920         case OP_OR_IMM:
13921         case OP_IOR_IMM:
13922                 return OP_X86_OR_MEMBASE_IMM;
13923         case OP_XOR_IMM:
13924         case OP_IXOR_IMM:
13925                 return OP_X86_XOR_MEMBASE_IMM;
13926         case OP_MOVE:
13927                 return OP_NOP;
13928         }
13929 #endif
13930
13931 #if defined(TARGET_AMD64)
13932         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13933                 return -1;
13934
13935         switch (opcode) {
13936         case OP_IADD:
13937                 return OP_X86_ADD_MEMBASE_REG;
13938         case OP_ISUB:
13939                 return OP_X86_SUB_MEMBASE_REG;
13940         case OP_IAND:
13941                 return OP_X86_AND_MEMBASE_REG;
13942         case OP_IOR:
13943                 return OP_X86_OR_MEMBASE_REG;
13944         case OP_IXOR:
13945                 return OP_X86_XOR_MEMBASE_REG;
13946         case OP_IADD_IMM:
13947                 return OP_X86_ADD_MEMBASE_IMM;
13948         case OP_ISUB_IMM:
13949                 return OP_X86_SUB_MEMBASE_IMM;
13950         case OP_IAND_IMM:
13951                 return OP_X86_AND_MEMBASE_IMM;
13952         case OP_IOR_IMM:
13953                 return OP_X86_OR_MEMBASE_IMM;
13954         case OP_IXOR_IMM:
13955                 return OP_X86_XOR_MEMBASE_IMM;
13956         case OP_LADD:
13957                 return OP_AMD64_ADD_MEMBASE_REG;
13958         case OP_LSUB:
13959                 return OP_AMD64_SUB_MEMBASE_REG;
13960         case OP_LAND:
13961                 return OP_AMD64_AND_MEMBASE_REG;
13962         case OP_LOR:
13963                 return OP_AMD64_OR_MEMBASE_REG;
13964         case OP_LXOR:
13965                 return OP_AMD64_XOR_MEMBASE_REG;
13966         case OP_ADD_IMM:
13967         case OP_LADD_IMM:
13968                 return OP_AMD64_ADD_MEMBASE_IMM;
13969         case OP_SUB_IMM:
13970         case OP_LSUB_IMM:
13971                 return OP_AMD64_SUB_MEMBASE_IMM;
13972         case OP_AND_IMM:
13973         case OP_LAND_IMM:
13974                 return OP_AMD64_AND_MEMBASE_IMM;
13975         case OP_OR_IMM:
13976         case OP_LOR_IMM:
13977                 return OP_AMD64_OR_MEMBASE_IMM;
13978         case OP_XOR_IMM:
13979         case OP_LXOR_IMM:
13980                 return OP_AMD64_XOR_MEMBASE_IMM;
13981         case OP_MOVE:
13982                 return OP_NOP;
13983         }
13984 #endif
13985
13986         return -1;
13987 }
13988
13989 static inline int
13990 op_to_op_store_membase (int store_opcode, int opcode)
13991 {
13992 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13993         switch (opcode) {
13994         case OP_ICEQ:
13995                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13996                         return OP_X86_SETEQ_MEMBASE;
13997         case OP_CNE:
13998                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13999                         return OP_X86_SETNE_MEMBASE;
14000         }
14001 #endif
14002
14003         return -1;
14004 }
14005
14006 static inline int
14007 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
14008 {
14009 #ifdef TARGET_X86
14010         /* FIXME: This has sign extension issues */
14011         /*
14012         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
14013                 return OP_X86_COMPARE_MEMBASE8_IMM;
14014         */
14015
14016         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
14017                 return -1;
14018
14019         switch (opcode) {
14020         case OP_X86_PUSH:
14021                 return OP_X86_PUSH_MEMBASE;
14022         case OP_COMPARE_IMM:
14023         case OP_ICOMPARE_IMM:
14024                 return OP_X86_COMPARE_MEMBASE_IMM;
14025         case OP_COMPARE:
14026         case OP_ICOMPARE:
14027                 return OP_X86_COMPARE_MEMBASE_REG;
14028         }
14029 #endif
14030
14031 #ifdef TARGET_AMD64
14032         /* FIXME: This has sign extension issues */
14033         /*
14034         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
14035                 return OP_X86_COMPARE_MEMBASE8_IMM;
14036         */
14037
14038         switch (opcode) {
14039         case OP_X86_PUSH:
14040                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
14041                         return OP_X86_PUSH_MEMBASE;
14042                 break;
14043                 /* FIXME: This only works for 32 bit immediates
14044         case OP_COMPARE_IMM:
14045         case OP_LCOMPARE_IMM:
14046                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
14047                         return OP_AMD64_COMPARE_MEMBASE_IMM;
14048                 */
14049         case OP_ICOMPARE_IMM:
14050                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
14051                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
14052                 break;
14053         case OP_COMPARE:
14054         case OP_LCOMPARE:
14055                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
14056                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
14057                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
14058                         return OP_AMD64_COMPARE_MEMBASE_REG;
14059                 break;
14060         case OP_ICOMPARE:
14061                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
14062                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
14063                 break;
14064         }
14065 #endif
14066
14067         return -1;
14068 }
14069
14070 static inline int
14071 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
14072 {
14073 #ifdef TARGET_X86
14074         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
14075                 return -1;
14076         
14077         switch (opcode) {
14078         case OP_COMPARE:
14079         case OP_ICOMPARE:
14080                 return OP_X86_COMPARE_REG_MEMBASE;
14081         case OP_IADD:
14082                 return OP_X86_ADD_REG_MEMBASE;
14083         case OP_ISUB:
14084                 return OP_X86_SUB_REG_MEMBASE;
14085         case OP_IAND:
14086                 return OP_X86_AND_REG_MEMBASE;
14087         case OP_IOR:
14088                 return OP_X86_OR_REG_MEMBASE;
14089         case OP_IXOR:
14090                 return OP_X86_XOR_REG_MEMBASE;
14091         }
14092 #endif
14093
14094 #ifdef TARGET_AMD64
14095         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
14096                 switch (opcode) {
14097                 case OP_ICOMPARE:
14098                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
14099                 case OP_IADD:
14100                         return OP_X86_ADD_REG_MEMBASE;
14101                 case OP_ISUB:
14102                         return OP_X86_SUB_REG_MEMBASE;
14103                 case OP_IAND:
14104                         return OP_X86_AND_REG_MEMBASE;
14105                 case OP_IOR:
14106                         return OP_X86_OR_REG_MEMBASE;
14107                 case OP_IXOR:
14108                         return OP_X86_XOR_REG_MEMBASE;
14109                 }
14110         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
14111                 switch (opcode) {
14112                 case OP_COMPARE:
14113                 case OP_LCOMPARE:
14114                         return OP_AMD64_COMPARE_REG_MEMBASE;
14115                 case OP_LADD:
14116                         return OP_AMD64_ADD_REG_MEMBASE;
14117                 case OP_LSUB:
14118                         return OP_AMD64_SUB_REG_MEMBASE;
14119                 case OP_LAND:
14120                         return OP_AMD64_AND_REG_MEMBASE;
14121                 case OP_LOR:
14122                         return OP_AMD64_OR_REG_MEMBASE;
14123                 case OP_LXOR:
14124                         return OP_AMD64_XOR_REG_MEMBASE;
14125                 }
14126         }
14127 #endif
14128
14129         return -1;
14130 }
14131
14132 int
14133 mono_op_to_op_imm_noemul (int opcode)
14134 {
14135         switch (opcode) {
14136 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
14137         case OP_LSHR:
14138         case OP_LSHL:
14139         case OP_LSHR_UN:
14140                 return -1;
14141 #endif
14142 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
14143         case OP_IDIV:
14144         case OP_IDIV_UN:
14145         case OP_IREM:
14146         case OP_IREM_UN:
14147                 return -1;
14148 #endif
14149 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
14150         case OP_IMUL:
14151                 return -1;
14152 #endif
14153         default:
14154                 return mono_op_to_op_imm (opcode);
14155         }
14156 }
14157
14158 /**
14159  * mono_handle_global_vregs:
14160  *
14161  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
14162  * for them.
14163  */
14164 void
14165 mono_handle_global_vregs (MonoCompile *cfg)
14166 {
14167         gint32 *vreg_to_bb;
14168         MonoBasicBlock *bb;
14169         int i, pos;
14170
14171         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
14172
14173 #ifdef MONO_ARCH_SIMD_INTRINSICS
14174         if (cfg->uses_simd_intrinsics)
14175                 mono_simd_simplify_indirection (cfg);
14176 #endif
14177
14178         /* Find local vregs used in more than one bb */
14179         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
14180                 MonoInst *ins = bb->code;       
14181                 int block_num = bb->block_num;
14182
14183                 if (cfg->verbose_level > 2)
14184                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
14185
14186                 cfg->cbb = bb;
14187                 for (; ins; ins = ins->next) {
14188                         const char *spec = INS_INFO (ins->opcode);
14189                         int regtype = 0, regindex;
14190                         gint32 prev_bb;
14191
14192                         if (G_UNLIKELY (cfg->verbose_level > 2))
14193                                 mono_print_ins (ins);
14194
14195                         g_assert (ins->opcode >= MONO_CEE_LAST);
14196
14197                         for (regindex = 0; regindex < 4; regindex ++) {
14198                                 int vreg = 0;
14199
14200                                 if (regindex == 0) {
14201                                         regtype = spec [MONO_INST_DEST];
14202                                         if (regtype == ' ')
14203                                                 continue;
14204                                         vreg = ins->dreg;
14205                                 } else if (regindex == 1) {
14206                                         regtype = spec [MONO_INST_SRC1];
14207                                         if (regtype == ' ')
14208                                                 continue;
14209                                         vreg = ins->sreg1;
14210                                 } else if (regindex == 2) {
14211                                         regtype = spec [MONO_INST_SRC2];
14212                                         if (regtype == ' ')
14213                                                 continue;
14214                                         vreg = ins->sreg2;
14215                                 } else if (regindex == 3) {
14216                                         regtype = spec [MONO_INST_SRC3];
14217                                         if (regtype == ' ')
14218                                                 continue;
14219                                         vreg = ins->sreg3;
14220                                 }
14221
14222 #if SIZEOF_REGISTER == 4
14223                                 /* In the LLVM case, the long opcodes are not decomposed */
14224                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
14225                                         /*
14226                                          * Since some instructions reference the original long vreg,
14227                                          * and some reference the two component vregs, it is quite hard
14228                                          * to determine when it needs to be global. So be conservative.
14229                                          */
14230                                         if (!get_vreg_to_inst (cfg, vreg)) {
14231                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
14232
14233                                                 if (cfg->verbose_level > 2)
14234                                                         printf ("LONG VREG R%d made global.\n", vreg);
14235                                         }
14236
14237                                         /*
14238                                          * Make the component vregs volatile since the optimizations can
14239                                          * get confused otherwise.
14240                                          */
14241                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
14242                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
14243                                 }
14244 #endif
14245
14246                                 g_assert (vreg != -1);
14247
14248                                 prev_bb = vreg_to_bb [vreg];
14249                                 if (prev_bb == 0) {
14250                                         /* 0 is a valid block num */
14251                                         vreg_to_bb [vreg] = block_num + 1;
14252                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
14253                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
14254                                                 continue;
14255
14256                                         if (!get_vreg_to_inst (cfg, vreg)) {
14257                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14258                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
14259
14260                                                 switch (regtype) {
14261                                                 case 'i':
14262                                                         if (vreg_is_ref (cfg, vreg))
14263                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
14264                                                         else
14265                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
14266                                                         break;
14267                                                 case 'l':
14268                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
14269                                                         break;
14270                                                 case 'f':
14271                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
14272                                                         break;
14273                                                 case 'v':
14274                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
14275                                                         break;
14276                                                 default:
14277                                                         g_assert_not_reached ();
14278                                                 }
14279                                         }
14280
14281                                         /* Flag as having been used in more than one bb */
14282                                         vreg_to_bb [vreg] = -1;
14283                                 }
14284                         }
14285                 }
14286         }
14287
14288         /* If a variable is used in only one bblock, convert it into a local vreg */
14289         for (i = 0; i < cfg->num_varinfo; i++) {
14290                 MonoInst *var = cfg->varinfo [i];
14291                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
14292
14293                 switch (var->type) {
14294                 case STACK_I4:
14295                 case STACK_OBJ:
14296                 case STACK_PTR:
14297                 case STACK_MP:
14298                 case STACK_VTYPE:
14299 #if SIZEOF_REGISTER == 8
14300                 case STACK_I8:
14301 #endif
14302 #if !defined(TARGET_X86)
14303                 /* Enabling this screws up the fp stack on x86 */
14304                 case STACK_R8:
14305 #endif
14306                         if (mono_arch_is_soft_float ())
14307                                 break;
14308
14309                         /*
14310                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
14311                                 break;
14312                         */
14313
14314                         /* Arguments are implicitly global */
14315                         /* Putting R4 vars into registers doesn't work currently */
14316                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
14317                         if ((var->opcode != OP_ARG) && (var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && (vreg_to_bb [var->dreg] != -1) && (var->klass->byval_arg.type != MONO_TYPE_R4) && !cfg->disable_vreg_to_lvreg && var != cfg->gsharedvt_info_var && var != cfg->gsharedvt_locals_var && var != cfg->lmf_addr_var) {
14318                                 /* 
14319                                  * Make that the variable's liveness interval doesn't contain a call, since
14320                                  * that would cause the lvreg to be spilled, making the whole optimization
14321                                  * useless.
14322                                  */
14323                                 /* This is too slow for JIT compilation */
14324 #if 0
14325                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
14326                                         MonoInst *ins;
14327                                         int def_index, call_index, ins_index;
14328                                         gboolean spilled = FALSE;
14329
14330                                         def_index = -1;
14331                                         call_index = -1;
14332                                         ins_index = 0;
14333                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
14334                                                 const char *spec = INS_INFO (ins->opcode);
14335
14336                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
14337                                                         def_index = ins_index;
14338
14339                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
14340                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
14341                                                         if (call_index > def_index) {
14342                                                                 spilled = TRUE;
14343                                                                 break;
14344                                                         }
14345                                                 }
14346
14347                                                 if (MONO_IS_CALL (ins))
14348                                                         call_index = ins_index;
14349
14350                                                 ins_index ++;
14351                                         }
14352
14353                                         if (spilled)
14354                                                 break;
14355                                 }
14356 #endif
14357
14358                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14359                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
14360                                 var->flags |= MONO_INST_IS_DEAD;
14361                                 cfg->vreg_to_inst [var->dreg] = NULL;
14362                         }
14363                         break;
14364                 }
14365         }
14366
14367         /* 
14368          * Compress the varinfo and vars tables so the liveness computation is faster and
14369          * takes up less space.
14370          */
14371         pos = 0;
14372         for (i = 0; i < cfg->num_varinfo; ++i) {
14373                 MonoInst *var = cfg->varinfo [i];
14374                 if (pos < i && cfg->locals_start == i)
14375                         cfg->locals_start = pos;
14376                 if (!(var->flags & MONO_INST_IS_DEAD)) {
14377                         if (pos < i) {
14378                                 cfg->varinfo [pos] = cfg->varinfo [i];
14379                                 cfg->varinfo [pos]->inst_c0 = pos;
14380                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
14381                                 cfg->vars [pos].idx = pos;
14382 #if SIZEOF_REGISTER == 4
14383                                 if (cfg->varinfo [pos]->type == STACK_I8) {
14384                                         /* Modify the two component vars too */
14385                                         MonoInst *var1;
14386
14387                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
14388                                         var1->inst_c0 = pos;
14389                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
14390                                         var1->inst_c0 = pos;
14391                                 }
14392 #endif
14393                         }
14394                         pos ++;
14395                 }
14396         }
14397         cfg->num_varinfo = pos;
14398         if (cfg->locals_start > cfg->num_varinfo)
14399                 cfg->locals_start = cfg->num_varinfo;
14400 }
14401
14402 /*
14403  * mono_allocate_gsharedvt_vars:
14404  *
14405  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
14406  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
14407  */
14408 void
14409 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
14410 {
14411         int i;
14412
14413         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
14414
14415         for (i = 0; i < cfg->num_varinfo; ++i) {
14416                 MonoInst *ins = cfg->varinfo [i];
14417                 int idx;
14418
14419                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
14420                         if (i >= cfg->locals_start) {
14421                                 /* Local */
14422                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
14423                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
14424                                 ins->opcode = OP_GSHAREDVT_LOCAL;
14425                                 ins->inst_imm = idx;
14426                         } else {
14427                                 /* Arg */
14428                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
14429                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
14430                         }
14431                 }
14432         }
14433 }
14434
14435 /**
14436  * mono_spill_global_vars:
14437  *
14438  *   Generate spill code for variables which are not allocated to registers, 
14439  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
14440  * code is generated which could be optimized by the local optimization passes.
14441  */
14442 void
14443 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
14444 {
14445         MonoBasicBlock *bb;
14446         char spec2 [16];
14447         int orig_next_vreg;
14448         guint32 *vreg_to_lvreg;
14449         guint32 *lvregs;
14450         guint32 i, lvregs_len;
14451         gboolean dest_has_lvreg = FALSE;
14452         MonoStackType stacktypes [128];
14453         MonoInst **live_range_start, **live_range_end;
14454         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
14455
14456         *need_local_opts = FALSE;
14457
14458         memset (spec2, 0, sizeof (spec2));
14459
14460         /* FIXME: Move this function to mini.c */
14461         stacktypes ['i'] = STACK_PTR;
14462         stacktypes ['l'] = STACK_I8;
14463         stacktypes ['f'] = STACK_R8;
14464 #ifdef MONO_ARCH_SIMD_INTRINSICS
14465         stacktypes ['x'] = STACK_VTYPE;
14466 #endif
14467
14468 #if SIZEOF_REGISTER == 4
14469         /* Create MonoInsts for longs */
14470         for (i = 0; i < cfg->num_varinfo; i++) {
14471                 MonoInst *ins = cfg->varinfo [i];
14472
14473                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
14474                         switch (ins->type) {
14475                         case STACK_R8:
14476                         case STACK_I8: {
14477                                 MonoInst *tree;
14478
14479                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
14480                                         break;
14481
14482                                 g_assert (ins->opcode == OP_REGOFFSET);
14483
14484                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
14485                                 g_assert (tree);
14486                                 tree->opcode = OP_REGOFFSET;
14487                                 tree->inst_basereg = ins->inst_basereg;
14488                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
14489
14490                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
14491                                 g_assert (tree);
14492                                 tree->opcode = OP_REGOFFSET;
14493                                 tree->inst_basereg = ins->inst_basereg;
14494                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
14495                                 break;
14496                         }
14497                         default:
14498                                 break;
14499                         }
14500                 }
14501         }
14502 #endif
14503
14504         if (cfg->compute_gc_maps) {
14505                 /* registers need liveness info even for !non refs */
14506                 for (i = 0; i < cfg->num_varinfo; i++) {
14507                         MonoInst *ins = cfg->varinfo [i];
14508
14509                         if (ins->opcode == OP_REGVAR)
14510                                 ins->flags |= MONO_INST_GC_TRACK;
14511                 }
14512         }
14513                 
14514         /* FIXME: widening and truncation */
14515
14516         /*
14517          * As an optimization, when a variable allocated to the stack is first loaded into 
14518          * an lvreg, we will remember the lvreg and use it the next time instead of loading
14519          * the variable again.
14520          */
14521         orig_next_vreg = cfg->next_vreg;
14522         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
14523         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * 1024);
14524         lvregs_len = 0;
14525
14526         /* 
14527          * These arrays contain the first and last instructions accessing a given
14528          * variable.
14529          * Since we emit bblocks in the same order we process them here, and we
14530          * don't split live ranges, these will precisely describe the live range of
14531          * the variable, i.e. the instruction range where a valid value can be found
14532          * in the variables location.
14533          * The live range is computed using the liveness info computed by the liveness pass.
14534          * We can't use vmv->range, since that is an abstract live range, and we need
14535          * one which is instruction precise.
14536          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
14537          */
14538         /* FIXME: Only do this if debugging info is requested */
14539         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
14540         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
14541         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
14542         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
14543         
14544         /* Add spill loads/stores */
14545         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
14546                 MonoInst *ins;
14547
14548                 if (cfg->verbose_level > 2)
14549                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
14550
14551                 /* Clear vreg_to_lvreg array */
14552                 for (i = 0; i < lvregs_len; i++)
14553                         vreg_to_lvreg [lvregs [i]] = 0;
14554                 lvregs_len = 0;
14555
14556                 cfg->cbb = bb;
14557                 MONO_BB_FOR_EACH_INS (bb, ins) {
14558                         const char *spec = INS_INFO (ins->opcode);
14559                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
14560                         gboolean store, no_lvreg;
14561                         int sregs [MONO_MAX_SRC_REGS];
14562
14563                         if (G_UNLIKELY (cfg->verbose_level > 2))
14564                                 mono_print_ins (ins);
14565
14566                         if (ins->opcode == OP_NOP)
14567                                 continue;
14568
14569                         /* 
14570                          * We handle LDADDR here as well, since it can only be decomposed
14571                          * when variable addresses are known.
14572                          */
14573                         if (ins->opcode == OP_LDADDR) {
14574                                 MonoInst *var = (MonoInst *)ins->inst_p0;
14575
14576                                 if (var->opcode == OP_VTARG_ADDR) {
14577                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
14578                                         MonoInst *vtaddr = var->inst_left;
14579                                         if (vtaddr->opcode == OP_REGVAR) {
14580                                                 ins->opcode = OP_MOVE;
14581                                                 ins->sreg1 = vtaddr->dreg;
14582                                         }
14583                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
14584                                                 ins->opcode = OP_LOAD_MEMBASE;
14585                                                 ins->inst_basereg = vtaddr->inst_basereg;
14586                                                 ins->inst_offset = vtaddr->inst_offset;
14587                                         } else
14588                                                 NOT_IMPLEMENTED;
14589                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
14590                                         /* gsharedvt arg passed by ref */
14591                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
14592
14593                                         ins->opcode = OP_LOAD_MEMBASE;
14594                                         ins->inst_basereg = var->inst_basereg;
14595                                         ins->inst_offset = var->inst_offset;
14596                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
14597                                         MonoInst *load, *load2, *load3;
14598                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
14599                                         int reg1, reg2, reg3;
14600                                         MonoInst *info_var = cfg->gsharedvt_info_var;
14601                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
14602
14603                                         /*
14604                                          * gsharedvt local.
14605                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
14606                                          */
14607
14608                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
14609
14610                                         g_assert (info_var);
14611                                         g_assert (locals_var);
14612
14613                                         /* Mark the instruction used to compute the locals var as used */
14614                                         cfg->gsharedvt_locals_var_ins = NULL;
14615
14616                                         /* Load the offset */
14617                                         if (info_var->opcode == OP_REGOFFSET) {
14618                                                 reg1 = alloc_ireg (cfg);
14619                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
14620                                         } else if (info_var->opcode == OP_REGVAR) {
14621                                                 load = NULL;
14622                                                 reg1 = info_var->dreg;
14623                                         } else {
14624                                                 g_assert_not_reached ();
14625                                         }
14626                                         reg2 = alloc_ireg (cfg);
14627                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
14628                                         /* Load the locals area address */
14629                                         reg3 = alloc_ireg (cfg);
14630                                         if (locals_var->opcode == OP_REGOFFSET) {
14631                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
14632                                         } else if (locals_var->opcode == OP_REGVAR) {
14633                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
14634                                         } else {
14635                                                 g_assert_not_reached ();
14636                                         }
14637                                         /* Compute the address */
14638                                         ins->opcode = OP_PADD;
14639                                         ins->sreg1 = reg3;
14640                                         ins->sreg2 = reg2;
14641
14642                                         mono_bblock_insert_before_ins (bb, ins, load3);
14643                                         mono_bblock_insert_before_ins (bb, load3, load2);
14644                                         if (load)
14645                                                 mono_bblock_insert_before_ins (bb, load2, load);
14646                                 } else {
14647                                         g_assert (var->opcode == OP_REGOFFSET);
14648
14649                                         ins->opcode = OP_ADD_IMM;
14650                                         ins->sreg1 = var->inst_basereg;
14651                                         ins->inst_imm = var->inst_offset;
14652                                 }
14653
14654                                 *need_local_opts = TRUE;
14655                                 spec = INS_INFO (ins->opcode);
14656                         }
14657
14658                         if (ins->opcode < MONO_CEE_LAST) {
14659                                 mono_print_ins (ins);
14660                                 g_assert_not_reached ();
14661                         }
14662
14663                         /*
14664                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
14665                          * src register.
14666                          * FIXME:
14667                          */
14668                         if (MONO_IS_STORE_MEMBASE (ins)) {
14669                                 tmp_reg = ins->dreg;
14670                                 ins->dreg = ins->sreg2;
14671                                 ins->sreg2 = tmp_reg;
14672                                 store = TRUE;
14673
14674                                 spec2 [MONO_INST_DEST] = ' ';
14675                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14676                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14677                                 spec2 [MONO_INST_SRC3] = ' ';
14678                                 spec = spec2;
14679                         } else if (MONO_IS_STORE_MEMINDEX (ins))
14680                                 g_assert_not_reached ();
14681                         else
14682                                 store = FALSE;
14683                         no_lvreg = FALSE;
14684
14685                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
14686                                 printf ("\t %.3s %d", spec, ins->dreg);
14687                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
14688                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
14689                                         printf (" %d", sregs [srcindex]);
14690                                 printf ("\n");
14691                         }
14692
14693                         /***************/
14694                         /*    DREG     */
14695                         /***************/
14696                         regtype = spec [MONO_INST_DEST];
14697                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
14698                         prev_dreg = -1;
14699
14700                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
14701                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
14702                                 MonoInst *store_ins;
14703                                 int store_opcode;
14704                                 MonoInst *def_ins = ins;
14705                                 int dreg = ins->dreg; /* The original vreg */
14706
14707                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
14708
14709                                 if (var->opcode == OP_REGVAR) {
14710                                         ins->dreg = var->dreg;
14711                                 } else if ((ins->dreg == ins->sreg1) && (spec [MONO_INST_DEST] == 'i') && (spec [MONO_INST_SRC1] == 'i') && !vreg_to_lvreg [ins->dreg] && (op_to_op_dest_membase (store_opcode, ins->opcode) != -1)) {
14712                                         /* 
14713                                          * Instead of emitting a load+store, use a _membase opcode.
14714                                          */
14715                                         g_assert (var->opcode == OP_REGOFFSET);
14716                                         if (ins->opcode == OP_MOVE) {
14717                                                 NULLIFY_INS (ins);
14718                                                 def_ins = NULL;
14719                                         } else {
14720                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
14721                                                 ins->inst_basereg = var->inst_basereg;
14722                                                 ins->inst_offset = var->inst_offset;
14723                                                 ins->dreg = -1;
14724                                         }
14725                                         spec = INS_INFO (ins->opcode);
14726                                 } else {
14727                                         guint32 lvreg;
14728
14729                                         g_assert (var->opcode == OP_REGOFFSET);
14730
14731                                         prev_dreg = ins->dreg;
14732
14733                                         /* Invalidate any previous lvreg for this vreg */
14734                                         vreg_to_lvreg [ins->dreg] = 0;
14735
14736                                         lvreg = 0;
14737
14738                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14739                                                 regtype = 'l';
14740                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14741                                         }
14742
14743                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14744
14745 #if SIZEOF_REGISTER != 8
14746                                         if (regtype == 'l') {
14747                                                 NEW_STORE_MEMBASE (cfg, store_ins, OP_STOREI4_MEMBASE_REG, var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET, MONO_LVREG_LS (ins->dreg));
14748                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14749                                                 NEW_STORE_MEMBASE (cfg, store_ins, OP_STOREI4_MEMBASE_REG, var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET, MONO_LVREG_MS (ins->dreg));
14750                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14751                                                 def_ins = store_ins;
14752                                         }
14753                                         else
14754 #endif
14755                                         {
14756                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14757
14758                                                 /* Try to fuse the store into the instruction itself */
14759                                                 /* FIXME: Add more instructions */
14760                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14761                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14762                                                         ins->inst_imm = ins->inst_c0;
14763                                                         ins->inst_destbasereg = var->inst_basereg;
14764                                                         ins->inst_offset = var->inst_offset;
14765                                                         spec = INS_INFO (ins->opcode);
14766                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14767                                                         ins->opcode = store_opcode;
14768                                                         ins->inst_destbasereg = var->inst_basereg;
14769                                                         ins->inst_offset = var->inst_offset;
14770
14771                                                         no_lvreg = TRUE;
14772
14773                                                         tmp_reg = ins->dreg;
14774                                                         ins->dreg = ins->sreg2;
14775                                                         ins->sreg2 = tmp_reg;
14776                                                         store = TRUE;
14777
14778                                                         spec2 [MONO_INST_DEST] = ' ';
14779                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14780                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14781                                                         spec2 [MONO_INST_SRC3] = ' ';
14782                                                         spec = spec2;
14783                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14784                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14785                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14786                                                         ins->dreg = -1;
14787                                                         ins->inst_basereg = var->inst_basereg;
14788                                                         ins->inst_offset = var->inst_offset;
14789                                                         spec = INS_INFO (ins->opcode);
14790                                                 } else {
14791                                                         /* printf ("INS: "); mono_print_ins (ins); */
14792                                                         /* Create a store instruction */
14793                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14794
14795                                                         /* Insert it after the instruction */
14796                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14797
14798                                                         def_ins = store_ins;
14799
14800                                                         /* 
14801                                                          * We can't assign ins->dreg to var->dreg here, since the
14802                                                          * sregs could use it. So set a flag, and do it after
14803                                                          * the sregs.
14804                                                          */
14805                                                         if ((!cfg->backend->use_fpstack || ((store_opcode != OP_STORER8_MEMBASE_REG) && (store_opcode != OP_STORER4_MEMBASE_REG))) && !((var)->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
14806                                                                 dest_has_lvreg = TRUE;
14807                                                 }
14808                                         }
14809                                 }
14810
14811                                 if (def_ins && !live_range_start [dreg]) {
14812                                         live_range_start [dreg] = def_ins;
14813                                         live_range_start_bb [dreg] = bb;
14814                                 }
14815
14816                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14817                                         MonoInst *tmp;
14818
14819                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14820                                         tmp->inst_c1 = dreg;
14821                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14822                                 }
14823                         }
14824
14825                         /************/
14826                         /*  SREGS   */
14827                         /************/
14828                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14829                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14830                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14831                                 sreg = sregs [srcindex];
14832
14833                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14834                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14835                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14836                                         MonoInst *use_ins = ins;
14837                                         MonoInst *load_ins;
14838                                         guint32 load_opcode;
14839
14840                                         if (var->opcode == OP_REGVAR) {
14841                                                 sregs [srcindex] = var->dreg;
14842                                                 //mono_inst_set_src_registers (ins, sregs);
14843                                                 live_range_end [sreg] = use_ins;
14844                                                 live_range_end_bb [sreg] = bb;
14845
14846                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14847                                                         MonoInst *tmp;
14848
14849                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14850                                                         /* var->dreg is a hreg */
14851                                                         tmp->inst_c1 = sreg;
14852                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14853                                                 }
14854
14855                                                 continue;
14856                                         }
14857
14858                                         g_assert (var->opcode == OP_REGOFFSET);
14859                                                 
14860                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14861
14862                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14863
14864                                         if (vreg_to_lvreg [sreg]) {
14865                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14866
14867                                                 /* The variable is already loaded to an lvreg */
14868                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14869                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14870                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14871                                                 //mono_inst_set_src_registers (ins, sregs);
14872                                                 continue;
14873                                         }
14874
14875                                         /* Try to fuse the load into the instruction */
14876                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14877                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14878                                                 sregs [0] = var->inst_basereg;
14879                                                 //mono_inst_set_src_registers (ins, sregs);
14880                                                 ins->inst_offset = var->inst_offset;
14881                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14882                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14883                                                 sregs [1] = var->inst_basereg;
14884                                                 //mono_inst_set_src_registers (ins, sregs);
14885                                                 ins->inst_offset = var->inst_offset;
14886                                         } else {
14887                                                 if (MONO_IS_REAL_MOVE (ins)) {
14888                                                         ins->opcode = OP_NOP;
14889                                                         sreg = ins->dreg;
14890                                                 } else {
14891                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14892
14893                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14894
14895                                                         if ((!cfg->backend->use_fpstack || ((load_opcode != OP_LOADR8_MEMBASE) && (load_opcode != OP_LOADR4_MEMBASE))) && !((var)->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && !no_lvreg) {
14896                                                                 if (var->dreg == prev_dreg) {
14897                                                                         /*
14898                                                                          * sreg refers to the value loaded by the load
14899                                                                          * emitted below, but we need to use ins->dreg
14900                                                                          * since it refers to the store emitted earlier.
14901                                                                          */
14902                                                                         sreg = ins->dreg;
14903                                                                 }
14904                                                                 g_assert (sreg != -1);
14905                                                                 vreg_to_lvreg [var->dreg] = sreg;
14906                                                                 g_assert (lvregs_len < 1024);
14907                                                                 lvregs [lvregs_len ++] = var->dreg;
14908                                                         }
14909                                                 }
14910
14911                                                 sregs [srcindex] = sreg;
14912                                                 //mono_inst_set_src_registers (ins, sregs);
14913
14914 #if SIZEOF_REGISTER != 8
14915                                                 if (regtype == 'l') {
14916                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14917                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14918                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14919                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14920                                                         use_ins = load_ins;
14921                                                 }
14922                                                 else
14923 #endif
14924                                                 {
14925 #if SIZEOF_REGISTER == 4
14926                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14927 #endif
14928                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14929                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14930                                                         use_ins = load_ins;
14931                                                 }
14932                                         }
14933
14934                                         if (var->dreg < orig_next_vreg) {
14935                                                 live_range_end [var->dreg] = use_ins;
14936                                                 live_range_end_bb [var->dreg] = bb;
14937                                         }
14938
14939                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14940                                                 MonoInst *tmp;
14941
14942                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14943                                                 tmp->inst_c1 = var->dreg;
14944                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14945                                         }
14946                                 }
14947                         }
14948                         mono_inst_set_src_registers (ins, sregs);
14949
14950                         if (dest_has_lvreg) {
14951                                 g_assert (ins->dreg != -1);
14952                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14953                                 g_assert (lvregs_len < 1024);
14954                                 lvregs [lvregs_len ++] = prev_dreg;
14955                                 dest_has_lvreg = FALSE;
14956                         }
14957
14958                         if (store) {
14959                                 tmp_reg = ins->dreg;
14960                                 ins->dreg = ins->sreg2;
14961                                 ins->sreg2 = tmp_reg;
14962                         }
14963
14964                         if (MONO_IS_CALL (ins)) {
14965                                 /* Clear vreg_to_lvreg array */
14966                                 for (i = 0; i < lvregs_len; i++)
14967                                         vreg_to_lvreg [lvregs [i]] = 0;
14968                                 lvregs_len = 0;
14969                         } else if (ins->opcode == OP_NOP) {
14970                                 ins->dreg = -1;
14971                                 MONO_INST_NULLIFY_SREGS (ins);
14972                         }
14973
14974                         if (cfg->verbose_level > 2)
14975                                 mono_print_ins_index (1, ins);
14976                 }
14977
14978                 /* Extend the live range based on the liveness info */
14979                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14980                         for (i = 0; i < cfg->num_varinfo; i ++) {
14981                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14982
14983                                 if (vreg_is_volatile (cfg, vi->vreg))
14984                                         /* The liveness info is incomplete */
14985                                         continue;
14986
14987                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14988                                         /* Live from at least the first ins of this bb */
14989                                         live_range_start [vi->vreg] = bb->code;
14990                                         live_range_start_bb [vi->vreg] = bb;
14991                                 }
14992
14993                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14994                                         /* Live at least until the last ins of this bb */
14995                                         live_range_end [vi->vreg] = bb->last_ins;
14996                                         live_range_end_bb [vi->vreg] = bb;
14997                                 }
14998                         }
14999                 }
15000         }
15001         
15002         /*
15003          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
15004          * by storing the current native offset into MonoMethodVar->live_range_start/end.
15005          */
15006         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
15007                 for (i = 0; i < cfg->num_varinfo; ++i) {
15008                         int vreg = MONO_VARINFO (cfg, i)->vreg;
15009                         MonoInst *ins;
15010
15011                         if (live_range_start [vreg]) {
15012                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
15013                                 ins->inst_c0 = i;
15014                                 ins->inst_c1 = vreg;
15015                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
15016                         }
15017                         if (live_range_end [vreg]) {
15018                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
15019                                 ins->inst_c0 = i;
15020                                 ins->inst_c1 = vreg;
15021                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
15022                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
15023                                 else
15024                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
15025                         }
15026                 }
15027         }
15028
15029         if (cfg->gsharedvt_locals_var_ins) {
15030                 /* Nullify if unused */
15031                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
15032                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
15033         }
15034
15035         g_free (live_range_start);
15036         g_free (live_range_end);
15037         g_free (live_range_start_bb);
15038         g_free (live_range_end_bb);
15039 }
15040
15041 /**
15042  * FIXME:
15043  * - use 'iadd' instead of 'int_add'
15044  * - handling ovf opcodes: decompose in method_to_ir.
15045  * - unify iregs/fregs
15046  *   -> partly done, the missing parts are:
15047  *   - a more complete unification would involve unifying the hregs as well, so
15048  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
15049  *     would no longer map to the machine hregs, so the code generators would need to
15050  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
15051  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
15052  *     fp/non-fp branches speeds it up by about 15%.
15053  * - use sext/zext opcodes instead of shifts
15054  * - add OP_ICALL
15055  * - get rid of TEMPLOADs if possible and use vregs instead
15056  * - clean up usage of OP_P/OP_ opcodes
15057  * - cleanup usage of DUMMY_USE
15058  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
15059  *   stack
15060  * - set the stack type and allocate a dreg in the EMIT_NEW macros
15061  * - get rid of all the <foo>2 stuff when the new JIT is ready.
15062  * - make sure handle_stack_args () is called before the branch is emitted
15063  * - when the new IR is done, get rid of all unused stuff
15064  * - COMPARE/BEQ as separate instructions or unify them ?
15065  *   - keeping them separate allows specialized compare instructions like
15066  *     compare_imm, compare_membase
15067  *   - most back ends unify fp compare+branch, fp compare+ceq
15068  * - integrate mono_save_args into inline_method
15069  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
15070  * - handle long shift opts on 32 bit platforms somehow: they require 
15071  *   3 sregs (2 for arg1 and 1 for arg2)
15072  * - make byref a 'normal' type.
15073  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
15074  *   variable if needed.
15075  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
15076  *   like inline_method.
15077  * - remove inlining restrictions
15078  * - fix LNEG and enable cfold of INEG
15079  * - generalize x86 optimizations like ldelema as a peephole optimization
15080  * - add store_mem_imm for amd64
15081  * - optimize the loading of the interruption flag in the managed->native wrappers
15082  * - avoid special handling of OP_NOP in passes
15083  * - move code inserting instructions into one function/macro.
15084  * - try a coalescing phase after liveness analysis
15085  * - add float -> vreg conversion + local optimizations on !x86
15086  * - figure out how to handle decomposed branches during optimizations, ie.
15087  *   compare+branch, op_jump_table+op_br etc.
15088  * - promote RuntimeXHandles to vregs
15089  * - vtype cleanups:
15090  *   - add a NEW_VARLOADA_VREG macro
15091  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
15092  *   accessing vtype fields.
15093  * - get rid of I8CONST on 64 bit platforms
15094  * - dealing with the increase in code size due to branches created during opcode
15095  *   decomposition:
15096  *   - use extended basic blocks
15097  *     - all parts of the JIT
15098  *     - handle_global_vregs () && local regalloc
15099  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
15100  * - sources of increase in code size:
15101  *   - vtypes
15102  *   - long compares
15103  *   - isinst and castclass
15104  *   - lvregs not allocated to global registers even if used multiple times
15105  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
15106  *   meaningful.
15107  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
15108  * - add all micro optimizations from the old JIT
15109  * - put tree optimizations into the deadce pass
15110  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
15111  *   specific function.
15112  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
15113  *   fcompare + branchCC.
15114  * - create a helper function for allocating a stack slot, taking into account 
15115  *   MONO_CFG_HAS_SPILLUP.
15116  * - merge r68207.
15117  * - merge the ia64 switch changes.
15118  * - optimize mono_regstate2_alloc_int/float.
15119  * - fix the pessimistic handling of variables accessed in exception handler blocks.
15120  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
15121  *   parts of the tree could be separated by other instructions, killing the tree
15122  *   arguments, or stores killing loads etc. Also, should we fold loads into other
15123  *   instructions if the result of the load is used multiple times ?
15124  * - make the REM_IMM optimization in mini-x86.c arch-independent.
15125  * - LAST MERGE: 108395.
15126  * - when returning vtypes in registers, generate IR and append it to the end of the
15127  *   last bb instead of doing it in the epilog.
15128  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
15129  */
15130
15131 /*
15132
15133 NOTES
15134 -----
15135
15136 - When to decompose opcodes:
15137   - earlier: this makes some optimizations hard to implement, since the low level IR
15138   no longer contains the neccessary information. But it is easier to do.
15139   - later: harder to implement, enables more optimizations.
15140 - Branches inside bblocks:
15141   - created when decomposing complex opcodes. 
15142     - branches to another bblock: harmless, but not tracked by the branch 
15143       optimizations, so need to branch to a label at the start of the bblock.
15144     - branches to inside the same bblock: very problematic, trips up the local
15145       reg allocator. Can be fixed by spitting the current bblock, but that is a
15146       complex operation, since some local vregs can become global vregs etc.
15147 - Local/global vregs:
15148   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
15149     local register allocator.
15150   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
15151     structure, created by mono_create_var (). Assigned to hregs or the stack by
15152     the global register allocator.
15153 - When to do optimizations like alu->alu_imm:
15154   - earlier -> saves work later on since the IR will be smaller/simpler
15155   - later -> can work on more instructions
15156 - Handling of valuetypes:
15157   - When a vtype is pushed on the stack, a new temporary is created, an 
15158     instruction computing its address (LDADDR) is emitted and pushed on
15159     the stack. Need to optimize cases when the vtype is used immediately as in
15160     argument passing, stloc etc.
15161 - Instead of the to_end stuff in the old JIT, simply call the function handling
15162   the values on the stack before emitting the last instruction of the bb.
15163 */
15164
15165 #endif /* DISABLE_JIT */