Merge pull request #4419 from BrzVlad/fix-oom-nre
[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 #include <mono/utils/mono-compiler.h>
16
17 #ifndef DISABLE_JIT
18
19 #include <signal.h>
20
21 #ifdef HAVE_UNISTD_H
22 #include <unistd.h>
23 #endif
24
25 #include <math.h>
26 #include <string.h>
27 #include <ctype.h>
28
29 #ifdef HAVE_SYS_TIME_H
30 #include <sys/time.h>
31 #endif
32
33 #ifdef HAVE_ALLOCA_H
34 #include <alloca.h>
35 #endif
36
37 #include <mono/utils/memcheck.h>
38 #include "mini.h"
39 #include <mono/metadata/abi-details.h>
40 #include <mono/metadata/assembly.h>
41 #include <mono/metadata/attrdefs.h>
42 #include <mono/metadata/loader.h>
43 #include <mono/metadata/tabledefs.h>
44 #include <mono/metadata/class.h>
45 #include <mono/metadata/object.h>
46 #include <mono/metadata/exception.h>
47 #include <mono/metadata/opcodes.h>
48 #include <mono/metadata/mono-endian.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/tabledefs.h>
51 #include <mono/metadata/marshal.h>
52 #include <mono/metadata/debug-helpers.h>
53 #include <mono/metadata/mono-debug.h>
54 #include <mono/metadata/mono-debug-debugger.h>
55 #include <mono/metadata/gc-internals.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/security-core-clr.h>
59 #include <mono/metadata/profiler-private.h>
60 #include <mono/metadata/profiler.h>
61 #include <mono/metadata/monitor.h>
62 #include <mono/metadata/debug-mono-symfile.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 #include <mono/utils/mono-threads-coop.h>
68
69 #include "trace.h"
70
71 #include "ir-emit.h"
72
73 #include "jit-icalls.h"
74 #include "jit.h"
75 #include "debugger-agent.h"
76 #include "seq-points.h"
77 #include "aot-compiler.h"
78 #include "mini-llvm.h"
79
80 #define BRANCH_COST 10
81 #define INLINE_LENGTH_LIMIT 20
82
83 /* These have 'cfg' as an implicit argument */
84 #define INLINE_FAILURE(msg) do {                                                                        \
85         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
86                 inline_failure (cfg, msg);                                                                              \
87                 goto exception_exit;                                                                                    \
88         } \
89         } while (0)
90 #define CHECK_CFG_EXCEPTION do {\
91                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
92                         goto exception_exit;                                            \
93         } while (0)
94 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
95                 field_access_failure ((cfg), (method), (field));                        \
96                 goto exception_exit;    \
97         } while (0)
98 #define GENERIC_SHARING_FAILURE(opcode) do {            \
99                 if (cfg->gshared) {                                                                     \
100                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
101                         goto exception_exit;    \
102                 }                       \
103         } while (0)
104 #define GSHAREDVT_FAILURE(opcode) do {          \
105         if (cfg->gsharedvt) {                                                                                           \
106                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
107                 goto exception_exit;                                                                                    \
108         }                                                                                                                                       \
109         } while (0)
110 #define OUT_OF_MEMORY_FAILURE do {      \
111                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
112                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
113                 goto exception_exit;    \
114         } while (0)
115 #define DISABLE_AOT(cfg) do { \
116                 if ((cfg)->verbose_level >= 2)                                            \
117                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
118                 (cfg)->disable_aot = TRUE;                                                        \
119         } while (0)
120 #define LOAD_ERROR do { \
121                 break_on_unverified ();                                                         \
122                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
123                 goto exception_exit;                                                                    \
124         } while (0)
125
126 #define TYPE_LOAD_ERROR(klass) do { \
127                 cfg->exception_ptr = klass; \
128                 LOAD_ERROR;                                     \
129         } while (0)
130
131 #define CHECK_CFG_ERROR do {\
132                 if (!mono_error_ok (&cfg->error)) { \
133                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
134                         goto mono_error_exit; \
135                 } \
136         } while (0)
137
138 /* Determine whenever 'ins' represents a load of the 'this' argument */
139 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
140
141 static int ldind_to_load_membase (int opcode);
142 static int stind_to_store_membase (int opcode);
143
144 int mono_op_to_op_imm (int opcode);
145 int mono_op_to_op_imm_noemul (int opcode);
146
147 MONO_API MonoInst* mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig, MonoInst **args);
148
149 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
150                                                   guchar *ip, guint real_offset, gboolean inline_always);
151 static MonoInst*
152 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
153
154 inline static MonoInst*
155 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg);
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_trampoline;
161 static MonoMethodSignature *helper_sig_jit_thread_attach;
162 static MonoMethodSignature *helper_sig_get_tls_tramp;
163 static MonoMethodSignature *helper_sig_set_tls_tramp;
164
165 /* type loading helpers */
166 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
167 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
168
169 /*
170  * Instruction metadata
171  */
172 #ifdef MINI_OP
173 #undef MINI_OP
174 #endif
175 #ifdef MINI_OP3
176 #undef MINI_OP3
177 #endif
178 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
179 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
180 #define NONE ' '
181 #define IREG 'i'
182 #define FREG 'f'
183 #define VREG 'v'
184 #define XREG 'x'
185 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
186 #define LREG IREG
187 #else
188 #define LREG 'l'
189 #endif
190 /* keep in sync with the enum in mini.h */
191 const char
192 ins_info[] = {
193 #include "mini-ops.h"
194 };
195 #undef MINI_OP
196 #undef MINI_OP3
197
198 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
199 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
200 /* 
201  * This should contain the index of the last sreg + 1. This is not the same
202  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
203  */
204 const gint8 ins_sreg_counts[] = {
205 #include "mini-ops.h"
206 };
207 #undef MINI_OP
208 #undef MINI_OP3
209
210 guint32
211 mono_alloc_ireg (MonoCompile *cfg)
212 {
213         return alloc_ireg (cfg);
214 }
215
216 guint32
217 mono_alloc_lreg (MonoCompile *cfg)
218 {
219         return alloc_lreg (cfg);
220 }
221
222 guint32
223 mono_alloc_freg (MonoCompile *cfg)
224 {
225         return alloc_freg (cfg);
226 }
227
228 guint32
229 mono_alloc_preg (MonoCompile *cfg)
230 {
231         return alloc_preg (cfg);
232 }
233
234 guint32
235 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
236 {
237         return alloc_dreg (cfg, stack_type);
238 }
239
240 /*
241  * mono_alloc_ireg_ref:
242  *
243  *   Allocate an IREG, and mark it as holding a GC ref.
244  */
245 guint32
246 mono_alloc_ireg_ref (MonoCompile *cfg)
247 {
248         return alloc_ireg_ref (cfg);
249 }
250
251 /*
252  * mono_alloc_ireg_mp:
253  *
254  *   Allocate an IREG, and mark it as holding a managed pointer.
255  */
256 guint32
257 mono_alloc_ireg_mp (MonoCompile *cfg)
258 {
259         return alloc_ireg_mp (cfg);
260 }
261
262 /*
263  * mono_alloc_ireg_copy:
264  *
265  *   Allocate an IREG with the same GC type as VREG.
266  */
267 guint32
268 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
269 {
270         if (vreg_is_ref (cfg, vreg))
271                 return alloc_ireg_ref (cfg);
272         else if (vreg_is_mp (cfg, vreg))
273                 return alloc_ireg_mp (cfg);
274         else
275                 return alloc_ireg (cfg);
276 }
277
278 guint
279 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
280 {
281         if (type->byref)
282                 return OP_MOVE;
283
284         type = mini_get_underlying_type (type);
285 handle_enum:
286         switch (type->type) {
287         case MONO_TYPE_I1:
288         case MONO_TYPE_U1:
289                 return OP_MOVE;
290         case MONO_TYPE_I2:
291         case MONO_TYPE_U2:
292                 return OP_MOVE;
293         case MONO_TYPE_I4:
294         case MONO_TYPE_U4:
295                 return OP_MOVE;
296         case MONO_TYPE_I:
297         case MONO_TYPE_U:
298         case MONO_TYPE_PTR:
299         case MONO_TYPE_FNPTR:
300                 return OP_MOVE;
301         case MONO_TYPE_CLASS:
302         case MONO_TYPE_STRING:
303         case MONO_TYPE_OBJECT:
304         case MONO_TYPE_SZARRAY:
305         case MONO_TYPE_ARRAY:    
306                 return OP_MOVE;
307         case MONO_TYPE_I8:
308         case MONO_TYPE_U8:
309 #if SIZEOF_REGISTER == 8
310                 return OP_MOVE;
311 #else
312                 return OP_LMOVE;
313 #endif
314         case MONO_TYPE_R4:
315                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
316         case MONO_TYPE_R8:
317                 return OP_FMOVE;
318         case MONO_TYPE_VALUETYPE:
319                 if (type->data.klass->enumtype) {
320                         type = mono_class_enum_basetype (type->data.klass);
321                         goto handle_enum;
322                 }
323                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
324                         return OP_XMOVE;
325                 return OP_VMOVE;
326         case MONO_TYPE_TYPEDBYREF:
327                 return OP_VMOVE;
328         case MONO_TYPE_GENERICINST:
329                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
330                         return OP_XMOVE;
331                 type = &type->data.generic_class->container_class->byval_arg;
332                 goto handle_enum;
333         case MONO_TYPE_VAR:
334         case MONO_TYPE_MVAR:
335                 g_assert (cfg->gshared);
336                 if (mini_type_var_is_vt (type))
337                         return OP_VMOVE;
338                 else
339                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
340         default:
341                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
342         }
343         return -1;
344 }
345
346 void
347 mono_print_bb (MonoBasicBlock *bb, const char *msg)
348 {
349         int i;
350         MonoInst *tree;
351
352         printf ("\n%s %d: [IN: ", msg, bb->block_num);
353         for (i = 0; i < bb->in_count; ++i)
354                 printf (" BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
355         printf (", OUT: ");
356         for (i = 0; i < bb->out_count; ++i)
357                 printf (" BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
358         printf (" ]\n");
359         for (tree = bb->code; tree; tree = tree->next)
360                 mono_print_ins_index (-1, tree);
361 }
362
363 void
364 mono_create_helper_signatures (void)
365 {
366         helper_sig_domain_get = mono_create_icall_signature ("ptr");
367         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
368         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
369         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
370         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
371         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
372 }
373
374 static MONO_NEVER_INLINE void
375 break_on_unverified (void)
376 {
377         if (mini_get_debug_options ()->break_on_unverified)
378                 G_BREAKPOINT ();
379 }
380
381 static MONO_NEVER_INLINE void
382 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
383 {
384         char *method_fname = mono_method_full_name (method, TRUE);
385         char *field_fname = mono_field_full_name (field);
386         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
387         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
388         g_free (method_fname);
389         g_free (field_fname);
390 }
391
392 static MONO_NEVER_INLINE void
393 inline_failure (MonoCompile *cfg, const char *msg)
394 {
395         if (cfg->verbose_level >= 2)
396                 printf ("inline failed: %s\n", msg);
397         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
398 }
399
400 static MONO_NEVER_INLINE void
401 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
402 {
403         if (cfg->verbose_level > 2)                                                                                     \
404                 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);
405         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
406 }
407
408 static MONO_NEVER_INLINE void
409 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
410 {
411         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);
412         if (cfg->verbose_level >= 2)
413                 printf ("%s\n", cfg->exception_message);
414         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
415 }
416
417 /*
418  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
419  * foo<T> (int i) { ldarg.0; box T; }
420  */
421 #define UNVERIFIED do { \
422         if (cfg->gsharedvt) { \
423                 if (cfg->verbose_level > 2)                                                                     \
424                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
425                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
426                 goto exception_exit;                                                                                    \
427         }                                                                                                                                       \
428         break_on_unverified ();                                                                                         \
429         goto unverified;                                                                                                        \
430 } while (0)
431
432 #define GET_BBLOCK(cfg,tblock,ip) do {  \
433                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
434                 if (!(tblock)) {        \
435                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
436             NEW_BBLOCK (cfg, (tblock)); \
437                         (tblock)->cil_code = (ip);      \
438                         ADD_BBLOCK (cfg, (tblock));     \
439                 } \
440         } while (0)
441
442 #if defined(TARGET_X86) || defined(TARGET_AMD64)
443 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
444                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
445                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
446                 (dest)->sreg1 = (sr1); \
447                 (dest)->sreg2 = (sr2); \
448                 (dest)->inst_imm = (imm); \
449                 (dest)->backend.shift_amount = (shift); \
450                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
451         } while (0)
452 #endif
453
454 /* Emit conversions so both operands of a binary opcode are of the same type */
455 static void
456 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
457 {
458         MonoInst *arg1 = *arg1_ref;
459         MonoInst *arg2 = *arg2_ref;
460
461         if (cfg->r4fp &&
462                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
463                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
464                 MonoInst *conv;
465
466                 /* Mixing r4/r8 is allowed by the spec */
467                 if (arg1->type == STACK_R4) {
468                         int dreg = alloc_freg (cfg);
469
470                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
471                         conv->type = STACK_R8;
472                         ins->sreg1 = dreg;
473                         *arg1_ref = conv;
474                 }
475                 if (arg2->type == STACK_R4) {
476                         int dreg = alloc_freg (cfg);
477
478                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
479                         conv->type = STACK_R8;
480                         ins->sreg2 = dreg;
481                         *arg2_ref = conv;
482                 }
483         }
484
485 #if SIZEOF_REGISTER == 8
486         /* FIXME: Need to add many more cases */
487         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
488                 MonoInst *widen;
489
490                 int dr = alloc_preg (cfg);
491                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
492                 (ins)->sreg2 = widen->dreg;
493         }
494 #endif
495 }
496
497 #define ADD_BINOP(op) do {      \
498                 MONO_INST_NEW (cfg, ins, (op)); \
499                 sp -= 2;        \
500                 ins->sreg1 = sp [0]->dreg;      \
501                 ins->sreg2 = sp [1]->dreg;      \
502                 type_from_op (cfg, ins, sp [0], sp [1]);        \
503                 CHECK_TYPE (ins);       \
504                 /* Have to insert a widening op */               \
505         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
506         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
507         MONO_ADD_INS ((cfg)->cbb, (ins)); \
508         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
509         } while (0)
510
511 #define ADD_UNOP(op) do {       \
512                 MONO_INST_NEW (cfg, ins, (op)); \
513                 sp--;   \
514                 ins->sreg1 = sp [0]->dreg;      \
515                 type_from_op (cfg, ins, sp [0], NULL);  \
516                 CHECK_TYPE (ins);       \
517         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
518         MONO_ADD_INS ((cfg)->cbb, (ins)); \
519                 *sp++ = mono_decompose_opcode (cfg, ins);       \
520         } while (0)
521
522 #define ADD_BINCOND(next_block) do {    \
523                 MonoInst *cmp;  \
524                 sp -= 2; \
525                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
526                 cmp->sreg1 = sp [0]->dreg;      \
527                 cmp->sreg2 = sp [1]->dreg;      \
528                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
529                 CHECK_TYPE (cmp);       \
530                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
531                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
532                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
533                 GET_BBLOCK (cfg, tblock, target);               \
534                 link_bblock (cfg, cfg->cbb, tblock);    \
535                 ins->inst_true_bb = tblock;     \
536                 if ((next_block)) {     \
537                         link_bblock (cfg, cfg->cbb, (next_block));      \
538                         ins->inst_false_bb = (next_block);      \
539                         start_new_bblock = 1;   \
540                 } else {        \
541                         GET_BBLOCK (cfg, tblock, ip);           \
542                         link_bblock (cfg, cfg->cbb, tblock);    \
543                         ins->inst_false_bb = tblock;    \
544                         start_new_bblock = 2;   \
545                 }       \
546                 if (sp != stack_start) {                                                                        \
547                     handle_stack_args (cfg, stack_start, sp - stack_start); \
548                         CHECK_UNVERIFIABLE (cfg); \
549                 } \
550         MONO_ADD_INS (cfg->cbb, cmp); \
551                 MONO_ADD_INS (cfg->cbb, ins);   \
552         } while (0)
553
554 /* *
555  * link_bblock: Links two basic blocks
556  *
557  * links two basic blocks in the control flow graph, the 'from'
558  * argument is the starting block and the 'to' argument is the block
559  * the control flow ends to after 'from'.
560  */
561 static void
562 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
563 {
564         MonoBasicBlock **newa;
565         int i, found;
566
567 #if 0
568         if (from->cil_code) {
569                 if (to->cil_code)
570                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
571                 else
572                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
573         } else {
574                 if (to->cil_code)
575                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
576                 else
577                         printf ("edge from entry to exit\n");
578         }
579 #endif
580
581         found = FALSE;
582         for (i = 0; i < from->out_count; ++i) {
583                 if (to == from->out_bb [i]) {
584                         found = TRUE;
585                         break;
586                 }
587         }
588         if (!found) {
589                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
590                 for (i = 0; i < from->out_count; ++i) {
591                         newa [i] = from->out_bb [i];
592                 }
593                 newa [i] = to;
594                 from->out_count++;
595                 from->out_bb = newa;
596         }
597
598         found = FALSE;
599         for (i = 0; i < to->in_count; ++i) {
600                 if (from == to->in_bb [i]) {
601                         found = TRUE;
602                         break;
603                 }
604         }
605         if (!found) {
606                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
607                 for (i = 0; i < to->in_count; ++i) {
608                         newa [i] = to->in_bb [i];
609                 }
610                 newa [i] = from;
611                 to->in_count++;
612                 to->in_bb = newa;
613         }
614 }
615
616 void
617 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
618 {
619         link_bblock (cfg, from, to);
620 }
621
622 /**
623  * mono_find_block_region:
624  *
625  *   We mark each basic block with a region ID. We use that to avoid BB
626  *   optimizations when blocks are in different regions.
627  *
628  * Returns:
629  *   A region token that encodes where this region is, and information
630  *   about the clause owner for this block.
631  *
632  *   The region encodes the try/catch/filter clause that owns this block
633  *   as well as the type.  -1 is a special value that represents a block
634  *   that is in none of try/catch/filter.
635  */
636 static int
637 mono_find_block_region (MonoCompile *cfg, int offset)
638 {
639         MonoMethodHeader *header = cfg->header;
640         MonoExceptionClause *clause;
641         int i;
642
643         for (i = 0; i < header->num_clauses; ++i) {
644                 clause = &header->clauses [i];
645                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
646                     (offset < (clause->handler_offset)))
647                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
648                            
649                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
650                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
651                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
652                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
653                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
654                         else
655                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
656                 }
657         }
658         for (i = 0; i < header->num_clauses; ++i) {
659                 clause = &header->clauses [i];
660
661                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
662                         return ((i + 1) << 8) | clause->flags;
663         }
664
665         return -1;
666 }
667
668 static gboolean
669 ip_in_finally_clause (MonoCompile *cfg, int offset)
670 {
671         MonoMethodHeader *header = cfg->header;
672         MonoExceptionClause *clause;
673         int i;
674
675         for (i = 0; i < header->num_clauses; ++i) {
676                 clause = &header->clauses [i];
677                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
678                         continue;
679
680                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
681                         return TRUE;
682         }
683         return FALSE;
684 }
685
686 static GList*
687 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
688 {
689         MonoMethodHeader *header = cfg->header;
690         MonoExceptionClause *clause;
691         int i;
692         GList *res = NULL;
693
694         for (i = 0; i < header->num_clauses; ++i) {
695                 clause = &header->clauses [i];
696                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
697                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
698                         if (clause->flags == type)
699                                 res = g_list_append (res, clause);
700                 }
701         }
702         return res;
703 }
704
705 static void
706 mono_create_spvar_for_region (MonoCompile *cfg, int region)
707 {
708         MonoInst *var;
709
710         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
711         if (var)
712                 return;
713
714         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
715         /* prevent it from being register allocated */
716         var->flags |= MONO_INST_VOLATILE;
717
718         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
719 }
720
721 MonoInst *
722 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
723 {
724         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
725 }
726
727 static MonoInst*
728 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
729 {
730         MonoInst *var;
731
732         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
733         if (var)
734                 return var;
735
736         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
737         /* prevent it from being register allocated */
738         var->flags |= MONO_INST_VOLATILE;
739
740         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
741
742         return var;
743 }
744
745 /*
746  * Returns the type used in the eval stack when @type is loaded.
747  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
748  */
749 void
750 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
751 {
752         MonoClass *klass;
753
754         type = mini_get_underlying_type (type);
755         inst->klass = klass = mono_class_from_mono_type (type);
756         if (type->byref) {
757                 inst->type = STACK_MP;
758                 return;
759         }
760
761 handle_enum:
762         switch (type->type) {
763         case MONO_TYPE_VOID:
764                 inst->type = STACK_INV;
765                 return;
766         case MONO_TYPE_I1:
767         case MONO_TYPE_U1:
768         case MONO_TYPE_I2:
769         case MONO_TYPE_U2:
770         case MONO_TYPE_I4:
771         case MONO_TYPE_U4:
772                 inst->type = STACK_I4;
773                 return;
774         case MONO_TYPE_I:
775         case MONO_TYPE_U:
776         case MONO_TYPE_PTR:
777         case MONO_TYPE_FNPTR:
778                 inst->type = STACK_PTR;
779                 return;
780         case MONO_TYPE_CLASS:
781         case MONO_TYPE_STRING:
782         case MONO_TYPE_OBJECT:
783         case MONO_TYPE_SZARRAY:
784         case MONO_TYPE_ARRAY:    
785                 inst->type = STACK_OBJ;
786                 return;
787         case MONO_TYPE_I8:
788         case MONO_TYPE_U8:
789                 inst->type = STACK_I8;
790                 return;
791         case MONO_TYPE_R4:
792                 inst->type = cfg->r4_stack_type;
793                 break;
794         case MONO_TYPE_R8:
795                 inst->type = STACK_R8;
796                 return;
797         case MONO_TYPE_VALUETYPE:
798                 if (type->data.klass->enumtype) {
799                         type = mono_class_enum_basetype (type->data.klass);
800                         goto handle_enum;
801                 } else {
802                         inst->klass = klass;
803                         inst->type = STACK_VTYPE;
804                         return;
805                 }
806         case MONO_TYPE_TYPEDBYREF:
807                 inst->klass = mono_defaults.typed_reference_class;
808                 inst->type = STACK_VTYPE;
809                 return;
810         case MONO_TYPE_GENERICINST:
811                 type = &type->data.generic_class->container_class->byval_arg;
812                 goto handle_enum;
813         case MONO_TYPE_VAR:
814         case MONO_TYPE_MVAR:
815                 g_assert (cfg->gshared);
816                 if (mini_is_gsharedvt_type (type)) {
817                         g_assert (cfg->gsharedvt);
818                         inst->type = STACK_VTYPE;
819                 } else {
820                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
821                 }
822                 return;
823         default:
824                 g_error ("unknown type 0x%02x in eval stack type", type->type);
825         }
826 }
827
828 /*
829  * The following tables are used to quickly validate the IL code in type_from_op ().
830  */
831 static const char
832 bin_num_table [STACK_MAX] [STACK_MAX] = {
833         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
834         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
835         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
836         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
837         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
838         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
839         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
840         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
841         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
842 };
843
844 static const char 
845 neg_table [] = {
846         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
847 };
848
849 /* reduce the size of this table */
850 static const char
851 bin_int_table [STACK_MAX] [STACK_MAX] = {
852         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
853         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
854         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
856         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
857         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
859         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
860 };
861
862 static const char
863 bin_comp_table [STACK_MAX] [STACK_MAX] = {
864 /*      Inv i  L  p  F  &  O  vt r4 */
865         {0},
866         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
867         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
868         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
869         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
870         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
871         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
872         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
873         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
874 };
875
876 /* reduce the size of this table */
877 static const char
878 shift_table [STACK_MAX] [STACK_MAX] = {
879         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
880         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
881         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
883         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
884         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
885         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
886         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
887 };
888
889 /*
890  * Tables to map from the non-specific opcode to the matching
891  * type-specific opcode.
892  */
893 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
894 static const guint16
895 binops_op_map [STACK_MAX] = {
896         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
897 };
898
899 /* handles from CEE_NEG to CEE_CONV_U8 */
900 static const guint16
901 unops_op_map [STACK_MAX] = {
902         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
903 };
904
905 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
906 static const guint16
907 ovfops_op_map [STACK_MAX] = {
908         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
909 };
910
911 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
912 static const guint16
913 ovf2ops_op_map [STACK_MAX] = {
914         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
915 };
916
917 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
918 static const guint16
919 ovf3ops_op_map [STACK_MAX] = {
920         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
921 };
922
923 /* handles from CEE_BEQ to CEE_BLT_UN */
924 static const guint16
925 beqops_op_map [STACK_MAX] = {
926         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
927 };
928
929 /* handles from CEE_CEQ to CEE_CLT_UN */
930 static const guint16
931 ceqops_op_map [STACK_MAX] = {
932         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
933 };
934
935 /*
936  * Sets ins->type (the type on the eval stack) according to the
937  * type of the opcode and the arguments to it.
938  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
939  *
940  * FIXME: this function sets ins->type unconditionally in some cases, but
941  * it should set it to invalid for some types (a conv.x on an object)
942  */
943 static void
944 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
945 {
946         switch (ins->opcode) {
947         /* binops */
948         case CEE_ADD:
949         case CEE_SUB:
950         case CEE_MUL:
951         case CEE_DIV:
952         case CEE_REM:
953                 /* FIXME: check unverifiable args for STACK_MP */
954                 ins->type = bin_num_table [src1->type] [src2->type];
955                 ins->opcode += binops_op_map [ins->type];
956                 break;
957         case CEE_DIV_UN:
958         case CEE_REM_UN:
959         case CEE_AND:
960         case CEE_OR:
961         case CEE_XOR:
962                 ins->type = bin_int_table [src1->type] [src2->type];
963                 ins->opcode += binops_op_map [ins->type];
964                 break;
965         case CEE_SHL:
966         case CEE_SHR:
967         case CEE_SHR_UN:
968                 ins->type = shift_table [src1->type] [src2->type];
969                 ins->opcode += binops_op_map [ins->type];
970                 break;
971         case OP_COMPARE:
972         case OP_LCOMPARE:
973         case OP_ICOMPARE:
974                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
975                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
976                         ins->opcode = OP_LCOMPARE;
977                 else if (src1->type == STACK_R4)
978                         ins->opcode = OP_RCOMPARE;
979                 else if (src1->type == STACK_R8)
980                         ins->opcode = OP_FCOMPARE;
981                 else
982                         ins->opcode = OP_ICOMPARE;
983                 break;
984         case OP_ICOMPARE_IMM:
985                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
986                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
987                         ins->opcode = OP_LCOMPARE_IMM;          
988                 break;
989         case CEE_BEQ:
990         case CEE_BGE:
991         case CEE_BGT:
992         case CEE_BLE:
993         case CEE_BLT:
994         case CEE_BNE_UN:
995         case CEE_BGE_UN:
996         case CEE_BGT_UN:
997         case CEE_BLE_UN:
998         case CEE_BLT_UN:
999                 ins->opcode += beqops_op_map [src1->type];
1000                 break;
1001         case OP_CEQ:
1002                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1003                 ins->opcode += ceqops_op_map [src1->type];
1004                 break;
1005         case OP_CGT:
1006         case OP_CGT_UN:
1007         case OP_CLT:
1008         case OP_CLT_UN:
1009                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1010                 ins->opcode += ceqops_op_map [src1->type];
1011                 break;
1012         /* unops */
1013         case CEE_NEG:
1014                 ins->type = neg_table [src1->type];
1015                 ins->opcode += unops_op_map [ins->type];
1016                 break;
1017         case CEE_NOT:
1018                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1019                         ins->type = src1->type;
1020                 else
1021                         ins->type = STACK_INV;
1022                 ins->opcode += unops_op_map [ins->type];
1023                 break;
1024         case CEE_CONV_I1:
1025         case CEE_CONV_I2:
1026         case CEE_CONV_I4:
1027         case CEE_CONV_U4:
1028                 ins->type = STACK_I4;
1029                 ins->opcode += unops_op_map [src1->type];
1030                 break;
1031         case CEE_CONV_R_UN:
1032                 ins->type = STACK_R8;
1033                 switch (src1->type) {
1034                 case STACK_I4:
1035                 case STACK_PTR:
1036                         ins->opcode = OP_ICONV_TO_R_UN;
1037                         break;
1038                 case STACK_I8:
1039                         ins->opcode = OP_LCONV_TO_R_UN; 
1040                         break;
1041                 }
1042                 break;
1043         case CEE_CONV_OVF_I1:
1044         case CEE_CONV_OVF_U1:
1045         case CEE_CONV_OVF_I2:
1046         case CEE_CONV_OVF_U2:
1047         case CEE_CONV_OVF_I4:
1048         case CEE_CONV_OVF_U4:
1049                 ins->type = STACK_I4;
1050                 ins->opcode += ovf3ops_op_map [src1->type];
1051                 break;
1052         case CEE_CONV_OVF_I_UN:
1053         case CEE_CONV_OVF_U_UN:
1054                 ins->type = STACK_PTR;
1055                 ins->opcode += ovf2ops_op_map [src1->type];
1056                 break;
1057         case CEE_CONV_OVF_I1_UN:
1058         case CEE_CONV_OVF_I2_UN:
1059         case CEE_CONV_OVF_I4_UN:
1060         case CEE_CONV_OVF_U1_UN:
1061         case CEE_CONV_OVF_U2_UN:
1062         case CEE_CONV_OVF_U4_UN:
1063                 ins->type = STACK_I4;
1064                 ins->opcode += ovf2ops_op_map [src1->type];
1065                 break;
1066         case CEE_CONV_U:
1067                 ins->type = STACK_PTR;
1068                 switch (src1->type) {
1069                 case STACK_I4:
1070                         ins->opcode = OP_ICONV_TO_U;
1071                         break;
1072                 case STACK_PTR:
1073                 case STACK_MP:
1074 #if SIZEOF_VOID_P == 8
1075                         ins->opcode = OP_LCONV_TO_U;
1076 #else
1077                         ins->opcode = OP_MOVE;
1078 #endif
1079                         break;
1080                 case STACK_I8:
1081                         ins->opcode = OP_LCONV_TO_U;
1082                         break;
1083                 case STACK_R8:
1084                         ins->opcode = OP_FCONV_TO_U;
1085                         break;
1086                 }
1087                 break;
1088         case CEE_CONV_I8:
1089         case CEE_CONV_U8:
1090                 ins->type = STACK_I8;
1091                 ins->opcode += unops_op_map [src1->type];
1092                 break;
1093         case CEE_CONV_OVF_I8:
1094         case CEE_CONV_OVF_U8:
1095                 ins->type = STACK_I8;
1096                 ins->opcode += ovf3ops_op_map [src1->type];
1097                 break;
1098         case CEE_CONV_OVF_U8_UN:
1099         case CEE_CONV_OVF_I8_UN:
1100                 ins->type = STACK_I8;
1101                 ins->opcode += ovf2ops_op_map [src1->type];
1102                 break;
1103         case CEE_CONV_R4:
1104                 ins->type = cfg->r4_stack_type;
1105                 ins->opcode += unops_op_map [src1->type];
1106                 break;
1107         case CEE_CONV_R8:
1108                 ins->type = STACK_R8;
1109                 ins->opcode += unops_op_map [src1->type];
1110                 break;
1111         case OP_CKFINITE:
1112                 ins->type = STACK_R8;           
1113                 break;
1114         case CEE_CONV_U2:
1115         case CEE_CONV_U1:
1116                 ins->type = STACK_I4;
1117                 ins->opcode += ovfops_op_map [src1->type];
1118                 break;
1119         case CEE_CONV_I:
1120         case CEE_CONV_OVF_I:
1121         case CEE_CONV_OVF_U:
1122                 ins->type = STACK_PTR;
1123                 ins->opcode += ovfops_op_map [src1->type];
1124                 break;
1125         case CEE_ADD_OVF:
1126         case CEE_ADD_OVF_UN:
1127         case CEE_MUL_OVF:
1128         case CEE_MUL_OVF_UN:
1129         case CEE_SUB_OVF:
1130         case CEE_SUB_OVF_UN:
1131                 ins->type = bin_num_table [src1->type] [src2->type];
1132                 ins->opcode += ovfops_op_map [src1->type];
1133                 if (ins->type == STACK_R8)
1134                         ins->type = STACK_INV;
1135                 break;
1136         case OP_LOAD_MEMBASE:
1137                 ins->type = STACK_PTR;
1138                 break;
1139         case OP_LOADI1_MEMBASE:
1140         case OP_LOADU1_MEMBASE:
1141         case OP_LOADI2_MEMBASE:
1142         case OP_LOADU2_MEMBASE:
1143         case OP_LOADI4_MEMBASE:
1144         case OP_LOADU4_MEMBASE:
1145                 ins->type = STACK_PTR;
1146                 break;
1147         case OP_LOADI8_MEMBASE:
1148                 ins->type = STACK_I8;
1149                 break;
1150         case OP_LOADR4_MEMBASE:
1151                 ins->type = cfg->r4_stack_type;
1152                 break;
1153         case OP_LOADR8_MEMBASE:
1154                 ins->type = STACK_R8;
1155                 break;
1156         default:
1157                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1158                 break;
1159         }
1160
1161         if (ins->type == STACK_MP)
1162                 ins->klass = mono_defaults.object_class;
1163 }
1164
1165 static const char 
1166 ldind_type [] = {
1167         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1168 };
1169
1170 #if 0
1171
1172 static const char
1173 param_table [STACK_MAX] [STACK_MAX] = {
1174         {0},
1175 };
1176
1177 static int
1178 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1179 {
1180         int i;
1181
1182         if (sig->hasthis) {
1183                 switch (args->type) {
1184                 case STACK_I4:
1185                 case STACK_I8:
1186                 case STACK_R8:
1187                 case STACK_VTYPE:
1188                 case STACK_INV:
1189                         return 0;
1190                 }
1191                 args++;
1192         }
1193         for (i = 0; i < sig->param_count; ++i) {
1194                 switch (args [i].type) {
1195                 case STACK_INV:
1196                         return 0;
1197                 case STACK_MP:
1198                         if (!sig->params [i]->byref)
1199                                 return 0;
1200                         continue;
1201                 case STACK_OBJ:
1202                         if (sig->params [i]->byref)
1203                                 return 0;
1204                         switch (sig->params [i]->type) {
1205                         case MONO_TYPE_CLASS:
1206                         case MONO_TYPE_STRING:
1207                         case MONO_TYPE_OBJECT:
1208                         case MONO_TYPE_SZARRAY:
1209                         case MONO_TYPE_ARRAY:
1210                                 break;
1211                         default:
1212                                 return 0;
1213                         }
1214                         continue;
1215                 case STACK_R8:
1216                         if (sig->params [i]->byref)
1217                                 return 0;
1218                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1219                                 return 0;
1220                         continue;
1221                 case STACK_PTR:
1222                 case STACK_I4:
1223                 case STACK_I8:
1224                 case STACK_VTYPE:
1225                         break;
1226                 }
1227                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1228                         return 0;*/
1229         }
1230         return 1;
1231 }
1232 #endif
1233
1234 /*
1235  * When we need a pointer to the current domain many times in a method, we
1236  * call mono_domain_get() once and we store the result in a local variable.
1237  * This function returns the variable that represents the MonoDomain*.
1238  */
1239 inline static MonoInst *
1240 mono_get_domainvar (MonoCompile *cfg)
1241 {
1242         if (!cfg->domainvar)
1243                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1244         return cfg->domainvar;
1245 }
1246
1247 /*
1248  * The got_var contains the address of the Global Offset Table when AOT 
1249  * compiling.
1250  */
1251 MonoInst *
1252 mono_get_got_var (MonoCompile *cfg)
1253 {
1254         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1255                 return NULL;
1256         if (!cfg->got_var) {
1257                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1258         }
1259         return cfg->got_var;
1260 }
1261
1262 static MonoInst *
1263 mono_get_vtable_var (MonoCompile *cfg)
1264 {
1265         g_assert (cfg->gshared);
1266
1267         if (!cfg->rgctx_var) {
1268                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1269                 /* force the var to be stack allocated */
1270                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1271         }
1272
1273         return cfg->rgctx_var;
1274 }
1275
1276 static MonoType*
1277 type_from_stack_type (MonoInst *ins) {
1278         switch (ins->type) {
1279         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1280         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1281         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1282         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1283         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1284         case STACK_MP:
1285                 return &ins->klass->this_arg;
1286         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1287         case STACK_VTYPE: return &ins->klass->byval_arg;
1288         default:
1289                 g_error ("stack type %d to monotype not handled\n", ins->type);
1290         }
1291         return NULL;
1292 }
1293
1294 static G_GNUC_UNUSED int
1295 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1296 {
1297         t = mono_type_get_underlying_type (t);
1298         switch (t->type) {
1299         case MONO_TYPE_I1:
1300         case MONO_TYPE_U1:
1301         case MONO_TYPE_I2:
1302         case MONO_TYPE_U2:
1303         case MONO_TYPE_I4:
1304         case MONO_TYPE_U4:
1305                 return STACK_I4;
1306         case MONO_TYPE_I:
1307         case MONO_TYPE_U:
1308         case MONO_TYPE_PTR:
1309         case MONO_TYPE_FNPTR:
1310                 return STACK_PTR;
1311         case MONO_TYPE_CLASS:
1312         case MONO_TYPE_STRING:
1313         case MONO_TYPE_OBJECT:
1314         case MONO_TYPE_SZARRAY:
1315         case MONO_TYPE_ARRAY:    
1316                 return STACK_OBJ;
1317         case MONO_TYPE_I8:
1318         case MONO_TYPE_U8:
1319                 return STACK_I8;
1320         case MONO_TYPE_R4:
1321                 return cfg->r4_stack_type;
1322         case MONO_TYPE_R8:
1323                 return STACK_R8;
1324         case MONO_TYPE_VALUETYPE:
1325         case MONO_TYPE_TYPEDBYREF:
1326                 return STACK_VTYPE;
1327         case MONO_TYPE_GENERICINST:
1328                 if (mono_type_generic_inst_is_valuetype (t))
1329                         return STACK_VTYPE;
1330                 else
1331                         return STACK_OBJ;
1332                 break;
1333         default:
1334                 g_assert_not_reached ();
1335         }
1336
1337         return -1;
1338 }
1339
1340 static MonoClass*
1341 array_access_to_klass (int opcode)
1342 {
1343         switch (opcode) {
1344         case CEE_LDELEM_U1:
1345                 return mono_defaults.byte_class;
1346         case CEE_LDELEM_U2:
1347                 return mono_defaults.uint16_class;
1348         case CEE_LDELEM_I:
1349         case CEE_STELEM_I:
1350                 return mono_defaults.int_class;
1351         case CEE_LDELEM_I1:
1352         case CEE_STELEM_I1:
1353                 return mono_defaults.sbyte_class;
1354         case CEE_LDELEM_I2:
1355         case CEE_STELEM_I2:
1356                 return mono_defaults.int16_class;
1357         case CEE_LDELEM_I4:
1358         case CEE_STELEM_I4:
1359                 return mono_defaults.int32_class;
1360         case CEE_LDELEM_U4:
1361                 return mono_defaults.uint32_class;
1362         case CEE_LDELEM_I8:
1363         case CEE_STELEM_I8:
1364                 return mono_defaults.int64_class;
1365         case CEE_LDELEM_R4:
1366         case CEE_STELEM_R4:
1367                 return mono_defaults.single_class;
1368         case CEE_LDELEM_R8:
1369         case CEE_STELEM_R8:
1370                 return mono_defaults.double_class;
1371         case CEE_LDELEM_REF:
1372         case CEE_STELEM_REF:
1373                 return mono_defaults.object_class;
1374         default:
1375                 g_assert_not_reached ();
1376         }
1377         return NULL;
1378 }
1379
1380 /*
1381  * We try to share variables when possible
1382  */
1383 static MonoInst *
1384 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1385 {
1386         MonoInst *res;
1387         int pos, vnum;
1388
1389         /* inlining can result in deeper stacks */ 
1390         if (slot >= cfg->header->max_stack)
1391                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1392
1393         pos = ins->type - 1 + slot * STACK_MAX;
1394
1395         switch (ins->type) {
1396         case STACK_I4:
1397         case STACK_I8:
1398         case STACK_R8:
1399         case STACK_PTR:
1400         case STACK_MP:
1401         case STACK_OBJ:
1402                 if ((vnum = cfg->intvars [pos]))
1403                         return cfg->varinfo [vnum];
1404                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1405                 cfg->intvars [pos] = res->inst_c0;
1406                 break;
1407         default:
1408                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1409         }
1410         return res;
1411 }
1412
1413 static void
1414 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1415 {
1416         /* 
1417          * Don't use this if a generic_context is set, since that means AOT can't
1418          * look up the method using just the image+token.
1419          * table == 0 means this is a reference made from a wrapper.
1420          */
1421         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1422                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1423                 jump_info_token->image = image;
1424                 jump_info_token->token = token;
1425                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1426         }
1427 }
1428
1429 /*
1430  * This function is called to handle items that are left on the evaluation stack
1431  * at basic block boundaries. What happens is that we save the values to local variables
1432  * and we reload them later when first entering the target basic block (with the
1433  * handle_loaded_temps () function).
1434  * A single joint point will use the same variables (stored in the array bb->out_stack or
1435  * bb->in_stack, if the basic block is before or after the joint point).
1436  *
1437  * This function needs to be called _before_ emitting the last instruction of
1438  * the bb (i.e. before emitting a branch).
1439  * If the stack merge fails at a join point, cfg->unverifiable is set.
1440  */
1441 static void
1442 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1443 {
1444         int i, bindex;
1445         MonoBasicBlock *bb = cfg->cbb;
1446         MonoBasicBlock *outb;
1447         MonoInst *inst, **locals;
1448         gboolean found;
1449
1450         if (!count)
1451                 return;
1452         if (cfg->verbose_level > 3)
1453                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1454         if (!bb->out_scount) {
1455                 bb->out_scount = count;
1456                 //printf ("bblock %d has out:", bb->block_num);
1457                 found = FALSE;
1458                 for (i = 0; i < bb->out_count; ++i) {
1459                         outb = bb->out_bb [i];
1460                         /* exception handlers are linked, but they should not be considered for stack args */
1461                         if (outb->flags & BB_EXCEPTION_HANDLER)
1462                                 continue;
1463                         //printf (" %d", outb->block_num);
1464                         if (outb->in_stack) {
1465                                 found = TRUE;
1466                                 bb->out_stack = outb->in_stack;
1467                                 break;
1468                         }
1469                 }
1470                 //printf ("\n");
1471                 if (!found) {
1472                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1473                         for (i = 0; i < count; ++i) {
1474                                 /* 
1475                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1476                                  * stack slot and if they are of the same type.
1477                                  * This won't cause conflicts since if 'local' is used to 
1478                                  * store one of the values in the in_stack of a bblock, then
1479                                  * the same variable will be used for the same outgoing stack 
1480                                  * slot as well. 
1481                                  * This doesn't work when inlining methods, since the bblocks
1482                                  * in the inlined methods do not inherit their in_stack from
1483                                  * the bblock they are inlined to. See bug #58863 for an
1484                                  * example.
1485                                  */
1486                                 if (cfg->inlined_method)
1487                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1488                                 else
1489                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1490                         }
1491                 }
1492         }
1493
1494         for (i = 0; i < bb->out_count; ++i) {
1495                 outb = bb->out_bb [i];
1496                 /* exception handlers are linked, but they should not be considered for stack args */
1497                 if (outb->flags & BB_EXCEPTION_HANDLER)
1498                         continue;
1499                 if (outb->in_scount) {
1500                         if (outb->in_scount != bb->out_scount) {
1501                                 cfg->unverifiable = TRUE;
1502                                 return;
1503                         }
1504                         continue; /* check they are the same locals */
1505                 }
1506                 outb->in_scount = count;
1507                 outb->in_stack = bb->out_stack;
1508         }
1509
1510         locals = bb->out_stack;
1511         cfg->cbb = bb;
1512         for (i = 0; i < count; ++i) {
1513                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1514                 inst->cil_code = sp [i]->cil_code;
1515                 sp [i] = locals [i];
1516                 if (cfg->verbose_level > 3)
1517                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1518         }
1519
1520         /*
1521          * It is possible that the out bblocks already have in_stack assigned, and
1522          * the in_stacks differ. In this case, we will store to all the different 
1523          * in_stacks.
1524          */
1525
1526         found = TRUE;
1527         bindex = 0;
1528         while (found) {
1529                 /* Find a bblock which has a different in_stack */
1530                 found = FALSE;
1531                 while (bindex < bb->out_count) {
1532                         outb = bb->out_bb [bindex];
1533                         /* exception handlers are linked, but they should not be considered for stack args */
1534                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1535                                 bindex++;
1536                                 continue;
1537                         }
1538                         if (outb->in_stack != locals) {
1539                                 for (i = 0; i < count; ++i) {
1540                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1541                                         inst->cil_code = sp [i]->cil_code;
1542                                         sp [i] = locals [i];
1543                                         if (cfg->verbose_level > 3)
1544                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1545                                 }
1546                                 locals = outb->in_stack;
1547                                 found = TRUE;
1548                                 break;
1549                         }
1550                         bindex ++;
1551                 }
1552         }
1553 }
1554
1555 static MonoInst*
1556 emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1557 {
1558         MonoInst *ins;
1559
1560         if (cfg->compile_aot) {
1561                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1562         } else {
1563                 MonoJumpInfo ji;
1564                 gpointer target;
1565                 MonoError error;
1566
1567                 ji.type = patch_type;
1568                 ji.data.target = data;
1569                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1570                 mono_error_assert_ok (&error);
1571
1572                 EMIT_NEW_PCONST (cfg, ins, target);
1573         }
1574         return ins;
1575 }
1576
1577 MonoInst*
1578 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1579 {
1580         return emit_runtime_constant (cfg, patch_type, data);
1581 }
1582
1583 static void 
1584 mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, int align)
1585 {
1586         int val_reg;
1587
1588         g_assert (val == 0);
1589
1590         if (align == 0)
1591                 align = 4;
1592
1593         if ((size <= SIZEOF_REGISTER) && (size <= align)) {
1594                 switch (size) {
1595                 case 1:
1596                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, destreg, offset, val);
1597                         return;
1598                 case 2:
1599                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI2_MEMBASE_IMM, destreg, offset, val);
1600                         return;
1601                 case 4:
1602                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, destreg, offset, val);
1603                         return;
1604 #if SIZEOF_REGISTER == 8
1605                 case 8:
1606                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI8_MEMBASE_IMM, destreg, offset, val);
1607                         return;
1608 #endif
1609                 }
1610         }
1611
1612         val_reg = alloc_preg (cfg);
1613
1614         if (SIZEOF_REGISTER == 8)
1615                 MONO_EMIT_NEW_I8CONST (cfg, val_reg, val);
1616         else
1617                 MONO_EMIT_NEW_ICONST (cfg, val_reg, val);
1618
1619         if (align < 4) {
1620                 /* This could be optimized further if neccesary */
1621                 while (size >= 1) {
1622                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1623                         offset += 1;
1624                         size -= 1;
1625                 }
1626                 return;
1627         }       
1628
1629         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1630                 if (offset % 8) {
1631                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1632                         offset += 4;
1633                         size -= 4;
1634                 }
1635                 while (size >= 8) {
1636                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, offset, val_reg);
1637                         offset += 8;
1638                         size -= 8;
1639                 }
1640         }       
1641
1642         while (size >= 4) {
1643                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1644                 offset += 4;
1645                 size -= 4;
1646         }
1647         while (size >= 2) {
1648                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, val_reg);
1649                 offset += 2;
1650                 size -= 2;
1651         }
1652         while (size >= 1) {
1653                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1654                 offset += 1;
1655                 size -= 1;
1656         }
1657 }
1658
1659 void 
1660 mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
1661 {
1662         int cur_reg;
1663
1664         if (align == 0)
1665                 align = 4;
1666
1667         /*FIXME arbitrary hack to avoid unbound code expansion.*/
1668         g_assert (size < 10000);
1669
1670         if (align < 4) {
1671                 /* This could be optimized further if neccesary */
1672                 while (size >= 1) {
1673                         cur_reg = alloc_preg (cfg);
1674                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1675                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1676                         doffset += 1;
1677                         soffset += 1;
1678                         size -= 1;
1679                 }
1680         }
1681
1682         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1683                 while (size >= 8) {
1684                         cur_reg = alloc_preg (cfg);
1685                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI8_MEMBASE, cur_reg, srcreg, soffset);
1686                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, doffset, cur_reg);
1687                         doffset += 8;
1688                         soffset += 8;
1689                         size -= 8;
1690                 }
1691         }       
1692
1693         while (size >= 4) {
1694                 cur_reg = alloc_preg (cfg);
1695                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, cur_reg, srcreg, soffset);
1696                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, doffset, cur_reg);
1697                 doffset += 4;
1698                 soffset += 4;
1699                 size -= 4;
1700         }
1701         while (size >= 2) {
1702                 cur_reg = alloc_preg (cfg);
1703                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, cur_reg, srcreg, soffset);
1704                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, doffset, cur_reg);
1705                 doffset += 2;
1706                 soffset += 2;
1707                 size -= 2;
1708         }
1709         while (size >= 1) {
1710                 cur_reg = alloc_preg (cfg);
1711                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1712                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1713                 doffset += 1;
1714                 soffset += 1;
1715                 size -= 1;
1716         }
1717 }
1718
1719 static MonoInst*
1720 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1721 {
1722         int tls_offset = mono_tls_get_tls_offset (key);
1723
1724         if (cfg->compile_aot)
1725                 return NULL;
1726
1727         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1728                 MonoInst *ins;
1729                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1730                 ins->dreg = mono_alloc_preg (cfg);
1731                 ins->inst_offset = tls_offset;
1732                 return ins;
1733         }
1734         return NULL;
1735 }
1736
1737 static MonoInst*
1738 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1739 {
1740         int tls_offset = mono_tls_get_tls_offset (key);
1741
1742         if (cfg->compile_aot)
1743                 return NULL;
1744
1745         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1746                 MonoInst *ins;
1747                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1748                 ins->sreg1 = value->dreg;
1749                 ins->inst_offset = tls_offset;
1750                 return ins;
1751         }
1752         return NULL;
1753 }
1754
1755
1756 MonoInst*
1757 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1758 {
1759         MonoInst *fast_tls = NULL;
1760
1761         if (!mini_get_debug_options ()->use_fallback_tls)
1762                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1763
1764         if (fast_tls) {
1765                 MONO_ADD_INS (cfg->cbb, fast_tls);
1766                 return fast_tls;
1767         }
1768
1769         if (cfg->compile_aot) {
1770                 MonoInst *addr;
1771                 /*
1772                  * tls getters are critical pieces of code and we don't want to resolve them
1773                  * through the standard plt/tramp mechanism since we might expose ourselves
1774                  * to crashes and infinite recursions.
1775                  */
1776                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1777                 return mono_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1778         } else {
1779                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1780                 return mono_emit_jit_icall (cfg, getter, NULL);
1781         }
1782 }
1783
1784 static MonoInst*
1785 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1786 {
1787         MonoInst *fast_tls = NULL;
1788
1789         if (!mini_get_debug_options ()->use_fallback_tls)
1790                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1791
1792         if (fast_tls) {
1793                 MONO_ADD_INS (cfg->cbb, fast_tls);
1794                 return fast_tls;
1795         }
1796
1797         if (cfg->compile_aot) {
1798                 MonoInst *addr;
1799                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1800                 return mono_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1801         } else {
1802                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1803                 return mono_emit_jit_icall (cfg, setter, &value);
1804         }
1805 }
1806
1807 /*
1808  * emit_push_lmf:
1809  *
1810  *   Emit IR to push the current LMF onto the LMF stack.
1811  */
1812 static void
1813 emit_push_lmf (MonoCompile *cfg)
1814 {
1815         /*
1816          * Emit IR to push the LMF:
1817          * lmf_addr = <lmf_addr from tls>
1818          * lmf->lmf_addr = lmf_addr
1819          * lmf->prev_lmf = *lmf_addr
1820          * *lmf_addr = lmf
1821          */
1822         MonoInst *ins, *lmf_ins;
1823
1824         if (!cfg->lmf_ir)
1825                 return;
1826
1827         if (cfg->lmf_ir_mono_lmf) {
1828                 MonoInst *lmf_vara_ins, *lmf_ins;
1829                 /* Load current lmf */
1830                 lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF);
1831                 g_assert (lmf_ins);
1832                 EMIT_NEW_VARLOADA (cfg, lmf_vara_ins, cfg->lmf_var, NULL);
1833                 /* Save previous_lmf */
1834                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_vara_ins->dreg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), lmf_ins->dreg);
1835                 /* Set new LMF */
1836                 mono_create_tls_set (cfg, lmf_vara_ins, TLS_KEY_LMF);
1837         } else {
1838                 int lmf_reg, prev_lmf_reg;
1839                 /*
1840                  * Store lmf_addr in a variable, so it can be allocated to a global register.
1841                  */
1842                 if (!cfg->lmf_addr_var)
1843                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1844
1845 #ifdef HOST_WIN32
1846                 ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1847                 g_assert (ins);
1848                 int jit_tls_dreg = ins->dreg;
1849
1850                 lmf_reg = alloc_preg (cfg);
1851                 EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1852 #else
1853                 lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1854                 g_assert (lmf_ins);
1855 #endif
1856                 lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1857
1858                 EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1859                 lmf_reg = ins->dreg;
1860
1861                 prev_lmf_reg = alloc_preg (cfg);
1862                 /* Save previous_lmf */
1863                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1864                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1865                 /* Set new lmf */
1866                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1867         }
1868 }
1869
1870 /*
1871  * emit_pop_lmf:
1872  *
1873  *   Emit IR to pop the current LMF from the LMF stack.
1874  */
1875 static void
1876 emit_pop_lmf (MonoCompile *cfg)
1877 {
1878         int lmf_reg, lmf_addr_reg;
1879         MonoInst *ins;
1880
1881         if (!cfg->lmf_ir)
1882                 return;
1883
1884         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1885         lmf_reg = ins->dreg;
1886
1887         if (cfg->lmf_ir_mono_lmf) {
1888                 /* Load previous_lmf */
1889                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, alloc_preg (cfg), lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1890                 /* Set new LMF */
1891                 mono_create_tls_set (cfg, ins, TLS_KEY_LMF);
1892         } else {
1893                 int prev_lmf_reg;
1894                 /*
1895                  * Emit IR to pop the LMF:
1896                  * *(lmf->lmf_addr) = lmf->prev_lmf
1897                  */
1898                 /* This could be called before emit_push_lmf () */
1899                 if (!cfg->lmf_addr_var)
1900                         cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1901                 lmf_addr_reg = cfg->lmf_addr_var->dreg;
1902
1903                 prev_lmf_reg = alloc_preg (cfg);
1904                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1905                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1906         }
1907 }
1908
1909 static void
1910 emit_instrumentation_call (MonoCompile *cfg, void *func)
1911 {
1912         MonoInst *iargs [1];
1913
1914         /*
1915          * Avoid instrumenting inlined methods since it can
1916          * distort profiling results.
1917          */
1918         if (cfg->method != cfg->current_method)
1919                 return;
1920
1921         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1922                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1923                 mono_emit_jit_icall (cfg, func, iargs);
1924         }
1925 }
1926
1927 static int
1928 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1929 {
1930 handle_enum:
1931         type = mini_get_underlying_type (type);
1932         switch (type->type) {
1933         case MONO_TYPE_VOID:
1934                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1935         case MONO_TYPE_I1:
1936         case MONO_TYPE_U1:
1937         case MONO_TYPE_I2:
1938         case MONO_TYPE_U2:
1939         case MONO_TYPE_I4:
1940         case MONO_TYPE_U4:
1941                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1942         case MONO_TYPE_I:
1943         case MONO_TYPE_U:
1944         case MONO_TYPE_PTR:
1945         case MONO_TYPE_FNPTR:
1946                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1947         case MONO_TYPE_CLASS:
1948         case MONO_TYPE_STRING:
1949         case MONO_TYPE_OBJECT:
1950         case MONO_TYPE_SZARRAY:
1951         case MONO_TYPE_ARRAY:    
1952                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1953         case MONO_TYPE_I8:
1954         case MONO_TYPE_U8:
1955                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1956         case MONO_TYPE_R4:
1957                 if (cfg->r4fp)
1958                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1959                 else
1960                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1961         case MONO_TYPE_R8:
1962                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1963         case MONO_TYPE_VALUETYPE:
1964                 if (type->data.klass->enumtype) {
1965                         type = mono_class_enum_basetype (type->data.klass);
1966                         goto handle_enum;
1967                 } else
1968                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1969         case MONO_TYPE_TYPEDBYREF:
1970                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1971         case MONO_TYPE_GENERICINST:
1972                 type = &type->data.generic_class->container_class->byval_arg;
1973                 goto handle_enum;
1974         case MONO_TYPE_VAR:
1975         case MONO_TYPE_MVAR:
1976                 /* gsharedvt */
1977                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1978         default:
1979                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1980         }
1981         return -1;
1982 }
1983
1984 //XXX this ignores if t is byref
1985 #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)))))
1986
1987 /*
1988  * target_type_is_incompatible:
1989  * @cfg: MonoCompile context
1990  *
1991  * Check that the item @arg on the evaluation stack can be stored
1992  * in the target type (can be a local, or field, etc).
1993  * The cfg arg can be used to check if we need verification or just
1994  * validity checks.
1995  *
1996  * Returns: non-0 value if arg can't be stored on a target.
1997  */
1998 static int
1999 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2000 {
2001         MonoType *simple_type;
2002         MonoClass *klass;
2003
2004         if (target->byref) {
2005                 /* FIXME: check that the pointed to types match */
2006                 if (arg->type == STACK_MP) {
2007                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
2008                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
2009                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
2010
2011                         /* if the target is native int& or same type */
2012                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
2013                                 return 0;
2014
2015                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
2016                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
2017                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
2018                                 return 0;
2019                         return 1;
2020                 }
2021                 if (arg->type == STACK_PTR)
2022                         return 0;
2023                 return 1;
2024         }
2025
2026         simple_type = mini_get_underlying_type (target);
2027         switch (simple_type->type) {
2028         case MONO_TYPE_VOID:
2029                 return 1;
2030         case MONO_TYPE_I1:
2031         case MONO_TYPE_U1:
2032         case MONO_TYPE_I2:
2033         case MONO_TYPE_U2:
2034         case MONO_TYPE_I4:
2035         case MONO_TYPE_U4:
2036                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2037                         return 1;
2038                 return 0;
2039         case MONO_TYPE_PTR:
2040                 /* STACK_MP is needed when setting pinned locals */
2041                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2042                         return 1;
2043                 return 0;
2044         case MONO_TYPE_I:
2045         case MONO_TYPE_U:
2046         case MONO_TYPE_FNPTR:
2047                 /* 
2048                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
2049                  * in native int. (#688008).
2050                  */
2051                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2052                         return 1;
2053                 return 0;
2054         case MONO_TYPE_CLASS:
2055         case MONO_TYPE_STRING:
2056         case MONO_TYPE_OBJECT:
2057         case MONO_TYPE_SZARRAY:
2058         case MONO_TYPE_ARRAY:    
2059                 if (arg->type != STACK_OBJ)
2060                         return 1;
2061                 /* FIXME: check type compatibility */
2062                 return 0;
2063         case MONO_TYPE_I8:
2064         case MONO_TYPE_U8:
2065                 if (arg->type != STACK_I8)
2066                         return 1;
2067                 return 0;
2068         case MONO_TYPE_R4:
2069                 if (arg->type != cfg->r4_stack_type)
2070                         return 1;
2071                 return 0;
2072         case MONO_TYPE_R8:
2073                 if (arg->type != STACK_R8)
2074                         return 1;
2075                 return 0;
2076         case MONO_TYPE_VALUETYPE:
2077                 if (arg->type != STACK_VTYPE)
2078                         return 1;
2079                 klass = mono_class_from_mono_type (simple_type);
2080                 if (klass != arg->klass)
2081                         return 1;
2082                 return 0;
2083         case MONO_TYPE_TYPEDBYREF:
2084                 if (arg->type != STACK_VTYPE)
2085                         return 1;
2086                 klass = mono_class_from_mono_type (simple_type);
2087                 if (klass != arg->klass)
2088                         return 1;
2089                 return 0;
2090         case MONO_TYPE_GENERICINST:
2091                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2092                         MonoClass *target_class;
2093                         if (arg->type != STACK_VTYPE)
2094                                 return 1;
2095                         klass = mono_class_from_mono_type (simple_type);
2096                         target_class = mono_class_from_mono_type (target);
2097                         /* The second cases is needed when doing partial sharing */
2098                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
2099                                 return 1;
2100                         return 0;
2101                 } else {
2102                         if (arg->type != STACK_OBJ)
2103                                 return 1;
2104                         /* FIXME: check type compatibility */
2105                         return 0;
2106                 }
2107         case MONO_TYPE_VAR:
2108         case MONO_TYPE_MVAR:
2109                 g_assert (cfg->gshared);
2110                 if (mini_type_var_is_vt (simple_type)) {
2111                         if (arg->type != STACK_VTYPE)
2112                                 return 1;
2113                 } else {
2114                         if (arg->type != STACK_OBJ)
2115                                 return 1;
2116                 }
2117                 return 0;
2118         default:
2119                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2120         }
2121         return 1;
2122 }
2123
2124 /*
2125  * Prepare arguments for passing to a function call.
2126  * Return a non-zero value if the arguments can't be passed to the given
2127  * signature.
2128  * The type checks are not yet complete and some conversions may need
2129  * casts on 32 or 64 bit architectures.
2130  *
2131  * FIXME: implement this using target_type_is_incompatible ()
2132  */
2133 static int
2134 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2135 {
2136         MonoType *simple_type;
2137         int i;
2138
2139         if (sig->hasthis) {
2140                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2141                         return 1;
2142                 args++;
2143         }
2144         for (i = 0; i < sig->param_count; ++i) {
2145                 if (sig->params [i]->byref) {
2146                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2147                                 return 1;
2148                         continue;
2149                 }
2150                 simple_type = mini_get_underlying_type (sig->params [i]);
2151 handle_enum:
2152                 switch (simple_type->type) {
2153                 case MONO_TYPE_VOID:
2154                         return 1;
2155                         continue;
2156                 case MONO_TYPE_I1:
2157                 case MONO_TYPE_U1:
2158                 case MONO_TYPE_I2:
2159                 case MONO_TYPE_U2:
2160                 case MONO_TYPE_I4:
2161                 case MONO_TYPE_U4:
2162                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2163                                 return 1;
2164                         continue;
2165                 case MONO_TYPE_I:
2166                 case MONO_TYPE_U:
2167                 case MONO_TYPE_PTR:
2168                 case MONO_TYPE_FNPTR:
2169                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2170                                 return 1;
2171                         continue;
2172                 case MONO_TYPE_CLASS:
2173                 case MONO_TYPE_STRING:
2174                 case MONO_TYPE_OBJECT:
2175                 case MONO_TYPE_SZARRAY:
2176                 case MONO_TYPE_ARRAY:    
2177                         if (args [i]->type != STACK_OBJ)
2178                                 return 1;
2179                         continue;
2180                 case MONO_TYPE_I8:
2181                 case MONO_TYPE_U8:
2182                         if (args [i]->type != STACK_I8)
2183                                 return 1;
2184                         continue;
2185                 case MONO_TYPE_R4:
2186                         if (args [i]->type != cfg->r4_stack_type)
2187                                 return 1;
2188                         continue;
2189                 case MONO_TYPE_R8:
2190                         if (args [i]->type != STACK_R8)
2191                                 return 1;
2192                         continue;
2193                 case MONO_TYPE_VALUETYPE:
2194                         if (simple_type->data.klass->enumtype) {
2195                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2196                                 goto handle_enum;
2197                         }
2198                         if (args [i]->type != STACK_VTYPE)
2199                                 return 1;
2200                         continue;
2201                 case MONO_TYPE_TYPEDBYREF:
2202                         if (args [i]->type != STACK_VTYPE)
2203                                 return 1;
2204                         continue;
2205                 case MONO_TYPE_GENERICINST:
2206                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2207                         goto handle_enum;
2208                 case MONO_TYPE_VAR:
2209                 case MONO_TYPE_MVAR:
2210                         /* gsharedvt */
2211                         if (args [i]->type != STACK_VTYPE)
2212                                 return 1;
2213                         continue;
2214                 default:
2215                         g_error ("unknown type 0x%02x in check_call_signature",
2216                                  simple_type->type);
2217                 }
2218         }
2219         return 0;
2220 }
2221
2222 static int
2223 callvirt_to_call (int opcode)
2224 {
2225         switch (opcode) {
2226         case OP_CALL_MEMBASE:
2227                 return OP_CALL;
2228         case OP_VOIDCALL_MEMBASE:
2229                 return OP_VOIDCALL;
2230         case OP_FCALL_MEMBASE:
2231                 return OP_FCALL;
2232         case OP_RCALL_MEMBASE:
2233                 return OP_RCALL;
2234         case OP_VCALL_MEMBASE:
2235                 return OP_VCALL;
2236         case OP_LCALL_MEMBASE:
2237                 return OP_LCALL;
2238         default:
2239                 g_assert_not_reached ();
2240         }
2241
2242         return -1;
2243 }
2244
2245 static int
2246 callvirt_to_call_reg (int opcode)
2247 {
2248         switch (opcode) {
2249         case OP_CALL_MEMBASE:
2250                 return OP_CALL_REG;
2251         case OP_VOIDCALL_MEMBASE:
2252                 return OP_VOIDCALL_REG;
2253         case OP_FCALL_MEMBASE:
2254                 return OP_FCALL_REG;
2255         case OP_RCALL_MEMBASE:
2256                 return OP_RCALL_REG;
2257         case OP_VCALL_MEMBASE:
2258                 return OP_VCALL_REG;
2259         case OP_LCALL_MEMBASE:
2260                 return OP_LCALL_REG;
2261         default:
2262                 g_assert_not_reached ();
2263         }
2264
2265         return -1;
2266 }
2267
2268 /* Either METHOD or IMT_ARG needs to be set */
2269 static void
2270 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2271 {
2272         int method_reg;
2273
2274         if (COMPILE_LLVM (cfg)) {
2275                 if (imt_arg) {
2276                         method_reg = alloc_preg (cfg);
2277                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2278                 } else {
2279                         MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2280                         method_reg = ins->dreg;
2281                 }
2282
2283 #ifdef ENABLE_LLVM
2284                 call->imt_arg_reg = method_reg;
2285 #endif
2286                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2287                 return;
2288         }
2289
2290         if (imt_arg) {
2291                 method_reg = alloc_preg (cfg);
2292                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2293         } else {
2294                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2295                 method_reg = ins->dreg;
2296         }
2297
2298         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2299 }
2300
2301 static MonoJumpInfo *
2302 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2303 {
2304         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2305
2306         ji->ip.i = ip;
2307         ji->type = type;
2308         ji->data.target = target;
2309
2310         return ji;
2311 }
2312
2313 static int
2314 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2315 {
2316         if (cfg->gshared)
2317                 return mono_class_check_context_used (klass);
2318         else
2319                 return 0;
2320 }
2321
2322 static int
2323 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2324 {
2325         if (cfg->gshared)
2326                 return mono_method_check_context_used (method);
2327         else
2328                 return 0;
2329 }
2330
2331 /*
2332  * check_method_sharing:
2333  *
2334  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2335  */
2336 static void
2337 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2338 {
2339         gboolean pass_vtable = FALSE;
2340         gboolean pass_mrgctx = FALSE;
2341
2342         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2343                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2344                 gboolean sharable = FALSE;
2345
2346                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2347                         sharable = TRUE;
2348
2349                 /*
2350                  * Pass vtable iff target method might
2351                  * be shared, which means that sharing
2352                  * is enabled for its class and its
2353                  * context is sharable (and it's not a
2354                  * generic method).
2355                  */
2356                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2357                         pass_vtable = TRUE;
2358         }
2359
2360         if (mini_method_get_context (cmethod) &&
2361                 mini_method_get_context (cmethod)->method_inst) {
2362                 g_assert (!pass_vtable);
2363
2364                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2365                         pass_mrgctx = TRUE;
2366                 } else {
2367                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2368                                 pass_mrgctx = TRUE;
2369                 }
2370         }
2371
2372         if (out_pass_vtable)
2373                 *out_pass_vtable = pass_vtable;
2374         if (out_pass_mrgctx)
2375                 *out_pass_mrgctx = pass_mrgctx;
2376 }
2377
2378 inline static MonoCallInst *
2379 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2380                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2381 {
2382         MonoType *sig_ret;
2383         MonoCallInst *call;
2384 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2385         int i;
2386 #endif
2387
2388         if (cfg->llvm_only)
2389                 tail = FALSE;
2390
2391         if (tail) {
2392                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2393
2394                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2395         } else
2396                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2397
2398         call->args = args;
2399         call->signature = sig;
2400         call->rgctx_reg = rgctx;
2401         sig_ret = mini_get_underlying_type (sig->ret);
2402
2403         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2404
2405         if (tail) {
2406                 if (mini_type_is_vtype (sig_ret)) {
2407                         call->vret_var = cfg->vret_addr;
2408                         //g_assert_not_reached ();
2409                 }
2410         } else if (mini_type_is_vtype (sig_ret)) {
2411                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2412                 MonoInst *loada;
2413
2414                 temp->backend.is_pinvoke = sig->pinvoke;
2415
2416                 /*
2417                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2418                  * address of return value to increase optimization opportunities.
2419                  * Before vtype decomposition, the dreg of the call ins itself represents the
2420                  * fact the call modifies the return value. After decomposition, the call will
2421                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2422                  * will be transformed into an LDADDR.
2423                  */
2424                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2425                 loada->dreg = alloc_preg (cfg);
2426                 loada->inst_p0 = temp;
2427                 /* We reference the call too since call->dreg could change during optimization */
2428                 loada->inst_p1 = call;
2429                 MONO_ADD_INS (cfg->cbb, loada);
2430
2431                 call->inst.dreg = temp->dreg;
2432
2433                 call->vret_var = loada;
2434         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2435                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2436
2437 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2438         if (COMPILE_SOFT_FLOAT (cfg)) {
2439                 /* 
2440                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2441                  * an icall, but that cannot be done during the call sequence since it would clobber
2442                  * the call registers + the stack. So we do it before emitting the call.
2443                  */
2444                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2445                         MonoType *t;
2446                         MonoInst *in = call->args [i];
2447
2448                         if (i >= sig->hasthis)
2449                                 t = sig->params [i - sig->hasthis];
2450                         else
2451                                 t = &mono_defaults.int_class->byval_arg;
2452                         t = mono_type_get_underlying_type (t);
2453
2454                         if (!t->byref && t->type == MONO_TYPE_R4) {
2455                                 MonoInst *iargs [1];
2456                                 MonoInst *conv;
2457
2458                                 iargs [0] = in;
2459                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2460
2461                                 /* The result will be in an int vreg */
2462                                 call->args [i] = conv;
2463                         }
2464                 }
2465         }
2466 #endif
2467
2468         call->need_unbox_trampoline = unbox_trampoline;
2469
2470 #ifdef ENABLE_LLVM
2471         if (COMPILE_LLVM (cfg))
2472                 mono_llvm_emit_call (cfg, call);
2473         else
2474                 mono_arch_emit_call (cfg, call);
2475 #else
2476         mono_arch_emit_call (cfg, call);
2477 #endif
2478
2479         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2480         cfg->flags |= MONO_CFG_HAS_CALLS;
2481         
2482         return call;
2483 }
2484
2485 static void
2486 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2487 {
2488         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2489         cfg->uses_rgctx_reg = TRUE;
2490         call->rgctx_reg = TRUE;
2491 #ifdef ENABLE_LLVM
2492         call->rgctx_arg_reg = rgctx_reg;
2493 #endif
2494 }       
2495
2496 inline static MonoInst*
2497 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2498 {
2499         MonoCallInst *call;
2500         MonoInst *ins;
2501         int rgctx_reg = -1;
2502         gboolean check_sp = FALSE;
2503
2504         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2505                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2506
2507                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2508                         check_sp = TRUE;
2509         }
2510
2511         if (rgctx_arg) {
2512                 rgctx_reg = mono_alloc_preg (cfg);
2513                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2514         }
2515
2516         if (check_sp) {
2517                 if (!cfg->stack_inbalance_var)
2518                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2519
2520                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2521                 ins->dreg = cfg->stack_inbalance_var->dreg;
2522                 MONO_ADD_INS (cfg->cbb, ins);
2523         }
2524
2525         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2526
2527         call->inst.sreg1 = addr->dreg;
2528
2529         if (imt_arg)
2530                 emit_imt_argument (cfg, call, NULL, imt_arg);
2531
2532         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2533
2534         if (check_sp) {
2535                 int sp_reg;
2536
2537                 sp_reg = mono_alloc_preg (cfg);
2538
2539                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2540                 ins->dreg = sp_reg;
2541                 MONO_ADD_INS (cfg->cbb, ins);
2542
2543                 /* Restore the stack so we don't crash when throwing the exception */
2544                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2545                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2546                 MONO_ADD_INS (cfg->cbb, ins);
2547
2548                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2549                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2550         }
2551
2552         if (rgctx_arg)
2553                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2554
2555         return (MonoInst*)call;
2556 }
2557
2558 static MonoInst*
2559 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2560
2561 static MonoInst*
2562 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2563
2564 static MonoInst*
2565 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2566                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2567 {
2568 #ifndef DISABLE_REMOTING
2569         gboolean might_be_remote = FALSE;
2570 #endif
2571         gboolean virtual_ = this_ins != NULL;
2572         gboolean enable_for_aot = TRUE;
2573         int context_used;
2574         MonoCallInst *call;
2575         MonoInst *call_target = NULL;
2576         int rgctx_reg = 0;
2577         gboolean need_unbox_trampoline;
2578
2579         if (!sig)
2580                 sig = mono_method_signature (method);
2581
2582         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2583                 g_assert_not_reached ();
2584
2585         if (rgctx_arg) {
2586                 rgctx_reg = mono_alloc_preg (cfg);
2587                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2588         }
2589
2590         if (method->string_ctor) {
2591                 /* Create the real signature */
2592                 /* FIXME: Cache these */
2593                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2594                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2595
2596                 sig = ctor_sig;
2597         }
2598
2599         context_used = mini_method_check_context_used (cfg, method);
2600
2601 #ifndef DISABLE_REMOTING
2602         might_be_remote = this_ins && sig->hasthis &&
2603                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2604                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2605
2606         if (might_be_remote && context_used) {
2607                 MonoInst *addr;
2608
2609                 g_assert (cfg->gshared);
2610
2611                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2612
2613                 return mono_emit_calli (cfg, sig, args, addr, NULL, NULL);
2614         }
2615 #endif
2616
2617         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2618                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2619
2620         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2621
2622         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2623
2624 #ifndef DISABLE_REMOTING
2625         if (might_be_remote)
2626                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2627         else
2628 #endif
2629                 call->method = method;
2630         call->inst.flags |= MONO_INST_HAS_METHOD;
2631         call->inst.inst_left = this_ins;
2632         call->tail_call = tail;
2633
2634         if (virtual_) {
2635                 int vtable_reg, slot_reg, this_reg;
2636                 int offset;
2637
2638                 this_reg = this_ins->dreg;
2639
2640                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2641                         MonoInst *dummy_use;
2642
2643                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2644
2645                         /* Make a call to delegate->invoke_impl */
2646                         call->inst.inst_basereg = this_reg;
2647                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2648                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2649
2650                         /* We must emit a dummy use here because the delegate trampoline will
2651                         replace the 'this' argument with the delegate target making this activation
2652                         no longer a root for the delegate.
2653                         This is an issue for delegates that target collectible code such as dynamic
2654                         methods of GC'able assemblies.
2655
2656                         For a test case look into #667921.
2657
2658                         FIXME: a dummy use is not the best way to do it as the local register allocator
2659                         will put it on a caller save register and spil it around the call. 
2660                         Ideally, we would either put it on a callee save register or only do the store part.  
2661                          */
2662                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2663
2664                         return (MonoInst*)call;
2665                 }
2666
2667                 if ((!cfg->compile_aot || enable_for_aot) && 
2668                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2669                          (MONO_METHOD_IS_FINAL (method) &&
2670                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2671                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2672                         /* 
2673                          * the method is not virtual, we just need to ensure this is not null
2674                          * and then we can call the method directly.
2675                          */
2676 #ifndef DISABLE_REMOTING
2677                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2678                                 /* 
2679                                  * The check above ensures method is not gshared, this is needed since
2680                                  * gshared methods can't have wrappers.
2681                                  */
2682                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2683                         }
2684 #endif
2685
2686                         if (!method->string_ctor)
2687                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2688
2689                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2690                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2691                         /*
2692                          * the method is virtual, but we can statically dispatch since either
2693                          * it's class or the method itself are sealed.
2694                          * But first we need to ensure it's not a null reference.
2695                          */
2696                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2697
2698                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2699                 } else if (call_target) {
2700                         vtable_reg = alloc_preg (cfg);
2701                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2702
2703                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2704                         call->inst.sreg1 = call_target->dreg;
2705                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2706                 } else {
2707                         vtable_reg = alloc_preg (cfg);
2708                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2709                         if (mono_class_is_interface (method->klass)) {
2710                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2711                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2712                                 slot_reg = vtable_reg;
2713                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2714                         } else {
2715                                 slot_reg = vtable_reg;
2716                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2717                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2718                                 if (imt_arg) {
2719                                         g_assert (mono_method_signature (method)->generic_param_count);
2720                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2721                                 }
2722                         }
2723
2724                         call->inst.sreg1 = slot_reg;
2725                         call->inst.inst_offset = offset;
2726                         call->is_virtual = TRUE;
2727                 }
2728         }
2729
2730         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2731
2732         if (rgctx_arg)
2733                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2734
2735         return (MonoInst*)call;
2736 }
2737
2738 MonoInst*
2739 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2740 {
2741         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2742 }
2743
2744 MonoInst*
2745 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2746                                            MonoInst **args)
2747 {
2748         MonoCallInst *call;
2749
2750         g_assert (sig);
2751
2752         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2753         call->fptr = func;
2754
2755         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2756
2757         return (MonoInst*)call;
2758 }
2759
2760 MonoInst*
2761 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2762 {
2763         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2764
2765         g_assert (info);
2766
2767         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2768 }
2769
2770 /*
2771  * mono_emit_abs_call:
2772  *
2773  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2774  */
2775 inline static MonoInst*
2776 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2777                                         MonoMethodSignature *sig, MonoInst **args)
2778 {
2779         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2780         MonoInst *ins;
2781
2782         /* 
2783          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2784          * handle it.
2785          */
2786         if (cfg->abs_patches == NULL)
2787                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2788         g_hash_table_insert (cfg->abs_patches, ji, ji);
2789         ins = mono_emit_native_call (cfg, ji, sig, args);
2790         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2791         return ins;
2792 }
2793
2794 static MonoMethodSignature*
2795 sig_to_rgctx_sig (MonoMethodSignature *sig)
2796 {
2797         // FIXME: memory allocation
2798         MonoMethodSignature *res;
2799         int i;
2800
2801         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2802         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2803         res->param_count = sig->param_count + 1;
2804         for (i = 0; i < sig->param_count; ++i)
2805                 res->params [i] = sig->params [i];
2806         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2807         return res;
2808 }
2809
2810 /* Make an indirect call to FSIG passing an additional argument */
2811 static MonoInst*
2812 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2813 {
2814         MonoMethodSignature *csig;
2815         MonoInst *args_buf [16];
2816         MonoInst **args;
2817         int i, pindex, tmp_reg;
2818
2819         /* Make a call with an rgctx/extra arg */
2820         if (fsig->param_count + 2 < 16)
2821                 args = args_buf;
2822         else
2823                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2824         pindex = 0;
2825         if (fsig->hasthis)
2826                 args [pindex ++] = orig_args [0];
2827         for (i = 0; i < fsig->param_count; ++i)
2828                 args [pindex ++] = orig_args [fsig->hasthis + i];
2829         tmp_reg = alloc_preg (cfg);
2830         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2831         csig = sig_to_rgctx_sig (fsig);
2832         return mono_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2833 }
2834
2835 /* Emit an indirect call to the function descriptor ADDR */
2836 static MonoInst*
2837 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2838 {
2839         int addr_reg, arg_reg;
2840         MonoInst *call_target;
2841
2842         g_assert (cfg->llvm_only);
2843
2844         /*
2845          * addr points to a <addr, arg> pair, load both of them, and
2846          * make a call to addr, passing arg as an extra arg.
2847          */
2848         addr_reg = alloc_preg (cfg);
2849         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2850         arg_reg = alloc_preg (cfg);
2851         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2852
2853         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2854 }
2855
2856 static gboolean
2857 direct_icalls_enabled (MonoCompile *cfg)
2858 {
2859         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2860 #ifdef TARGET_AMD64
2861         if (cfg->compile_llvm && !cfg->llvm_only)
2862                 return FALSE;
2863 #endif
2864         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2865                 return FALSE;
2866         return TRUE;
2867 }
2868
2869 MonoInst*
2870 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2871 {
2872         /*
2873          * Call the jit icall without a wrapper if possible.
2874          * The wrapper is needed for the following reasons:
2875          * - to handle exceptions thrown using mono_raise_exceptions () from the
2876          *   icall function. The EH code needs the lmf frame pushed by the
2877          *   wrapper to be able to unwind back to managed code.
2878          * - to be able to do stack walks for asynchronously suspended
2879          *   threads when debugging.
2880          */
2881         if (info->no_raise && direct_icalls_enabled (cfg)) {
2882                 char *name;
2883                 int costs;
2884
2885                 if (!info->wrapper_method) {
2886                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2887                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2888                         g_free (name);
2889                         mono_memory_barrier ();
2890                 }
2891
2892                 /*
2893                  * Inline the wrapper method, which is basically a call to the C icall, and
2894                  * an exception check.
2895                  */
2896                 costs = inline_method (cfg, info->wrapper_method, NULL,
2897                                                            args, NULL, il_offset, TRUE);
2898                 g_assert (costs > 0);
2899                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2900
2901                 return args [0];
2902         } else {
2903                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2904         }
2905 }
2906  
2907 static MonoInst*
2908 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2909 {
2910         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2911                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2912                         int widen_op = -1;
2913
2914                         /* 
2915                          * Native code might return non register sized integers 
2916                          * without initializing the upper bits.
2917                          */
2918                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2919                         case OP_LOADI1_MEMBASE:
2920                                 widen_op = OP_ICONV_TO_I1;
2921                                 break;
2922                         case OP_LOADU1_MEMBASE:
2923                                 widen_op = OP_ICONV_TO_U1;
2924                                 break;
2925                         case OP_LOADI2_MEMBASE:
2926                                 widen_op = OP_ICONV_TO_I2;
2927                                 break;
2928                         case OP_LOADU2_MEMBASE:
2929                                 widen_op = OP_ICONV_TO_U2;
2930                                 break;
2931                         default:
2932                                 break;
2933                         }
2934
2935                         if (widen_op != -1) {
2936                                 int dreg = alloc_preg (cfg);
2937                                 MonoInst *widen;
2938
2939                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2940                                 widen->type = ins->type;
2941                                 ins = widen;
2942                         }
2943                 }
2944         }
2945
2946         return ins;
2947 }
2948
2949
2950 static void
2951 emit_method_access_failure (MonoCompile *cfg, MonoMethod *method, MonoMethod *cil_method)
2952 {
2953         MonoInst *args [16];
2954
2955         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (method), method, MONO_RGCTX_INFO_METHOD);
2956         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cil_method), cil_method, MONO_RGCTX_INFO_METHOD);
2957
2958         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2959 }
2960
2961 static MonoMethod*
2962 get_memcpy_method (void)
2963 {
2964         static MonoMethod *memcpy_method = NULL;
2965         if (!memcpy_method) {
2966                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2967                 if (!memcpy_method)
2968                         g_error ("Old corlib found. Install a new one");
2969         }
2970         return memcpy_method;
2971 }
2972
2973 static void
2974 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
2975 {
2976         MonoClassField *field;
2977         gpointer iter = NULL;
2978
2979         while ((field = mono_class_get_fields (klass, &iter))) {
2980                 int foffset;
2981
2982                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
2983                         continue;
2984                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
2985                 if (mini_type_is_reference (mono_field_get_type (field))) {
2986                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
2987                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
2988                 } else {
2989                         MonoClass *field_class = mono_class_from_mono_type (field->type);
2990                         if (field_class->has_references)
2991                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
2992                 }
2993         }
2994 }
2995
2996 static void
2997 emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2998 {
2999         int card_table_shift_bits;
3000         gpointer card_table_mask;
3001         guint8 *card_table;
3002         MonoInst *dummy_use;
3003         int nursery_shift_bits;
3004         size_t nursery_size;
3005
3006         if (!cfg->gen_write_barriers)
3007                 return;
3008
3009         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3010
3011         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
3012
3013         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
3014                 MonoInst *wbarrier;
3015
3016                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
3017                 wbarrier->sreg1 = ptr->dreg;
3018                 wbarrier->sreg2 = value->dreg;
3019                 MONO_ADD_INS (cfg->cbb, wbarrier);
3020         } else if (card_table && !cfg->compile_aot && !mono_gc_card_table_nursery_check ()) {
3021                 int offset_reg = alloc_preg (cfg);
3022                 int card_reg;
3023                 MonoInst *ins;
3024
3025                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
3026                 if (card_table_mask)
3027                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
3028
3029                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
3030                  * IMM's larger than 32bits.
3031                  */
3032                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
3033                 card_reg = ins->dreg;
3034
3035                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
3036                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
3037         } else {
3038                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
3039                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
3040         }
3041
3042         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
3043 }
3044
3045 static gboolean
3046 mono_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
3047 {
3048         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
3049         unsigned need_wb = 0;
3050
3051         if (align == 0)
3052                 align = 4;
3053
3054         /*types with references can't have alignment smaller than sizeof(void*) */
3055         if (align < SIZEOF_VOID_P)
3056                 return FALSE;
3057
3058         /*This value cannot be bigger than 32 due to the way we calculate the required wb bitmap.*/
3059         if (size > 32 * SIZEOF_VOID_P)
3060                 return FALSE;
3061
3062         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
3063
3064         /* We don't unroll more than 5 stores to avoid code bloat. */
3065         if (size > 5 * SIZEOF_VOID_P) {
3066                 /*This is harmless and simplify mono_gc_wbarrier_value_copy_bitmap */
3067                 size += (SIZEOF_VOID_P - 1);
3068                 size &= ~(SIZEOF_VOID_P - 1);
3069
3070                 EMIT_NEW_ICONST (cfg, iargs [2], size);
3071                 EMIT_NEW_ICONST (cfg, iargs [3], need_wb);
3072                 mono_emit_jit_icall (cfg, mono_gc_wbarrier_value_copy_bitmap, iargs);
3073                 return TRUE;
3074         }
3075
3076         destreg = iargs [0]->dreg;
3077         srcreg = iargs [1]->dreg;
3078         offset = 0;
3079
3080         dest_ptr_reg = alloc_preg (cfg);
3081         tmp_reg = alloc_preg (cfg);
3082
3083         /*tmp = dreg*/
3084         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
3085
3086         while (size >= SIZEOF_VOID_P) {
3087                 MonoInst *load_inst;
3088                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
3089                 load_inst->dreg = tmp_reg;
3090                 load_inst->inst_basereg = srcreg;
3091                 load_inst->inst_offset = offset;
3092                 MONO_ADD_INS (cfg->cbb, load_inst);
3093
3094                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
3095
3096                 if (need_wb & 0x1)
3097                         emit_write_barrier (cfg, iargs [0], load_inst);
3098
3099                 offset += SIZEOF_VOID_P;
3100                 size -= SIZEOF_VOID_P;
3101                 need_wb >>= 1;
3102
3103                 /*tmp += sizeof (void*)*/
3104                 if (size >= SIZEOF_VOID_P) {
3105                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
3106                         MONO_ADD_INS (cfg->cbb, iargs [0]);
3107                 }
3108         }
3109
3110         /* Those cannot be references since size < sizeof (void*) */
3111         while (size >= 4) {
3112                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
3113                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
3114                 offset += 4;
3115                 size -= 4;
3116         }
3117
3118         while (size >= 2) {
3119                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
3120                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
3121                 offset += 2;
3122                 size -= 2;
3123         }
3124
3125         while (size >= 1) {
3126                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
3127                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
3128                 offset += 1;
3129                 size -= 1;
3130         }
3131
3132         return TRUE;
3133 }
3134
3135 /*
3136  * Emit code to copy a valuetype of type @klass whose address is stored in
3137  * @src->dreg to memory whose address is stored at @dest->dreg.
3138  */
3139 void
3140 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
3141 {
3142         MonoInst *iargs [4];
3143         int n;
3144         guint32 align = 0;
3145         MonoMethod *memcpy_method;
3146         MonoInst *size_ins = NULL;
3147         MonoInst *memcpy_ins = NULL;
3148
3149         g_assert (klass);
3150         if (cfg->gshared)
3151                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3152
3153         /*
3154          * This check breaks with spilled vars... need to handle it during verification anyway.
3155          * g_assert (klass && klass == src->klass && klass == dest->klass);
3156          */
3157
3158         if (mini_is_gsharedvt_klass (klass)) {
3159                 g_assert (!native);
3160                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3161                 memcpy_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3162         }
3163
3164         if (native)
3165                 n = mono_class_native_size (klass, &align);
3166         else
3167                 n = mono_class_value_size (klass, &align);
3168
3169         /* if native is true there should be no references in the struct */
3170         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3171                 /* Avoid barriers when storing to the stack */
3172                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3173                           (dest->opcode == OP_LDADDR))) {
3174                         int context_used;
3175
3176                         iargs [0] = dest;
3177                         iargs [1] = src;
3178
3179                         context_used = mini_class_check_context_used (cfg, klass);
3180
3181                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3182                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mono_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3183                                 return;
3184                         } else if (context_used) {
3185                                 iargs [2] = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3186                         }  else {
3187                                 iargs [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3188                                 if (!cfg->compile_aot)
3189                                         mono_class_compute_gc_descriptor (klass);
3190                         }
3191
3192                         if (size_ins)
3193                                 mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3194                         else
3195                                 mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3196                         return;
3197                 }
3198         }
3199
3200         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3201                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3202                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3203         } else {
3204                 iargs [0] = dest;
3205                 iargs [1] = src;
3206                 if (size_ins)
3207                         iargs [2] = size_ins;
3208                 else
3209                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3210                 
3211                 memcpy_method = get_memcpy_method ();
3212                 if (memcpy_ins)
3213                         mono_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3214                 else
3215                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3216         }
3217 }
3218
3219 static MonoMethod*
3220 get_memset_method (void)
3221 {
3222         static MonoMethod *memset_method = NULL;
3223         if (!memset_method) {
3224                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3225                 if (!memset_method)
3226                         g_error ("Old corlib found. Install a new one");
3227         }
3228         return memset_method;
3229 }
3230
3231 void
3232 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3233 {
3234         MonoInst *iargs [3];
3235         int n;
3236         guint32 align;
3237         MonoMethod *memset_method;
3238         MonoInst *size_ins = NULL;
3239         MonoInst *bzero_ins = NULL;
3240         static MonoMethod *bzero_method;
3241
3242         /* FIXME: Optimize this for the case when dest is an LDADDR */
3243         mono_class_init (klass);
3244         if (mini_is_gsharedvt_klass (klass)) {
3245                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3246                 bzero_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3247                 if (!bzero_method)
3248                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3249                 g_assert (bzero_method);
3250                 iargs [0] = dest;
3251                 iargs [1] = size_ins;
3252                 mono_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3253                 return;
3254         }
3255
3256         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3257
3258         n = mono_class_value_size (klass, &align);
3259
3260         if (n <= sizeof (gpointer) * 8) {
3261                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3262         }
3263         else {
3264                 memset_method = get_memset_method ();
3265                 iargs [0] = dest;
3266                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3267                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3268                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3269         }
3270 }
3271
3272 /*
3273  * emit_get_rgctx:
3274  *
3275  *   Emit IR to return either the this pointer for instance method,
3276  * or the mrgctx for static methods.
3277  */
3278 static MonoInst*
3279 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3280 {
3281         MonoInst *this_ins = NULL;
3282
3283         g_assert (cfg->gshared);
3284
3285         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3286                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3287                 !method->klass->valuetype)
3288                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
3289
3290         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3291                 MonoInst *mrgctx_loc, *mrgctx_var;
3292
3293                 g_assert (!this_ins);
3294                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3295
3296                 mrgctx_loc = mono_get_vtable_var (cfg);
3297                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3298
3299                 return mrgctx_var;
3300         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3301                 MonoInst *vtable_loc, *vtable_var;
3302
3303                 g_assert (!this_ins);
3304
3305                 vtable_loc = mono_get_vtable_var (cfg);
3306                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3307
3308                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3309                         MonoInst *mrgctx_var = vtable_var;
3310                         int vtable_reg;
3311
3312                         vtable_reg = alloc_preg (cfg);
3313                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3314                         vtable_var->type = STACK_PTR;
3315                 }
3316
3317                 return vtable_var;
3318         } else {
3319                 MonoInst *ins;
3320                 int vtable_reg;
3321         
3322                 vtable_reg = alloc_preg (cfg);
3323                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3324                 return ins;
3325         }
3326 }
3327
3328 static MonoJumpInfoRgctxEntry *
3329 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3330 {
3331         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3332         res->method = method;
3333         res->in_mrgctx = in_mrgctx;
3334         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3335         res->data->type = patch_type;
3336         res->data->data.target = patch_data;
3337         res->info_type = info_type;
3338
3339         return res;
3340 }
3341
3342 static inline MonoInst*
3343 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3344 {
3345         MonoInst *args [16];
3346         MonoInst *call;
3347
3348         // FIXME: No fastpath since the slot is not a compile time constant
3349         args [0] = rgctx;
3350         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3351         if (entry->in_mrgctx)
3352                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3353         else
3354                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3355         return call;
3356 #if 0
3357         /*
3358          * FIXME: This can be called during decompose, which is a problem since it creates
3359          * new bblocks.
3360          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3361          */
3362         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3363         gboolean mrgctx;
3364         MonoBasicBlock *is_null_bb, *end_bb;
3365         MonoInst *res, *ins, *call;
3366         MonoInst *args[16];
3367
3368         slot = mini_get_rgctx_entry_slot (entry);
3369
3370         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3371         index = MONO_RGCTX_SLOT_INDEX (slot);
3372         if (mrgctx)
3373                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3374         for (depth = 0; ; ++depth) {
3375                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3376
3377                 if (index < size - 1)
3378                         break;
3379                 index -= size - 1;
3380         }
3381
3382         NEW_BBLOCK (cfg, end_bb);
3383         NEW_BBLOCK (cfg, is_null_bb);
3384
3385         if (mrgctx) {
3386                 rgctx_reg = rgctx->dreg;
3387         } else {
3388                 rgctx_reg = alloc_preg (cfg);
3389
3390                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3391                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3392                 NEW_BBLOCK (cfg, is_null_bb);
3393
3394                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3395                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3396         }
3397
3398         for (i = 0; i < depth; ++i) {
3399                 int array_reg = alloc_preg (cfg);
3400
3401                 /* load ptr to next array */
3402                 if (mrgctx && i == 0)
3403                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3404                 else
3405                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3406                 rgctx_reg = array_reg;
3407                 /* is the ptr null? */
3408                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3409                 /* if yes, jump to actual trampoline */
3410                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3411         }
3412
3413         /* fetch slot */
3414         val_reg = alloc_preg (cfg);
3415         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3416         /* is the slot null? */
3417         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3418         /* if yes, jump to actual trampoline */
3419         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3420
3421         /* Fastpath */
3422         res_reg = alloc_preg (cfg);
3423         MONO_INST_NEW (cfg, ins, OP_MOVE);
3424         ins->dreg = res_reg;
3425         ins->sreg1 = val_reg;
3426         MONO_ADD_INS (cfg->cbb, ins);
3427         res = ins;
3428         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3429
3430         /* Slowpath */
3431         MONO_START_BB (cfg, is_null_bb);
3432         args [0] = rgctx;
3433         EMIT_NEW_ICONST (cfg, args [1], index);
3434         if (mrgctx)
3435                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3436         else
3437                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3438         MONO_INST_NEW (cfg, ins, OP_MOVE);
3439         ins->dreg = res_reg;
3440         ins->sreg1 = call->dreg;
3441         MONO_ADD_INS (cfg->cbb, ins);
3442         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3443
3444         MONO_START_BB (cfg, end_bb);
3445
3446         return res;
3447 #endif
3448 }
3449
3450 /*
3451  * emit_rgctx_fetch:
3452  *
3453  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3454  * given by RGCTX.
3455  */
3456 static inline MonoInst*
3457 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3458 {
3459         if (cfg->llvm_only)
3460                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3461         else
3462                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3463 }
3464
3465 MonoInst*
3466 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3467                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3468 {
3469         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3470         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3471
3472         return emit_rgctx_fetch (cfg, rgctx, entry);
3473 }
3474
3475 static MonoInst*
3476 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3477                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3478 {
3479         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3480         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3481
3482         return emit_rgctx_fetch (cfg, rgctx, entry);
3483 }
3484
3485 static MonoInst*
3486 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3487                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3488 {
3489         MonoJumpInfoGSharedVtCall *call_info;
3490         MonoJumpInfoRgctxEntry *entry;
3491         MonoInst *rgctx;
3492
3493         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3494         call_info->sig = sig;
3495         call_info->method = cmethod;
3496
3497         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3498         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3499
3500         return emit_rgctx_fetch (cfg, rgctx, entry);
3501 }
3502
3503 /*
3504  * emit_get_rgctx_virt_method:
3505  *
3506  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3507  */
3508 static MonoInst*
3509 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3510                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3511 {
3512         MonoJumpInfoVirtMethod *info;
3513         MonoJumpInfoRgctxEntry *entry;
3514         MonoInst *rgctx;
3515
3516         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3517         info->klass = klass;
3518         info->method = virt_method;
3519
3520         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3521         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3522
3523         return emit_rgctx_fetch (cfg, rgctx, entry);
3524 }
3525
3526 static MonoInst*
3527 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3528                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3529 {
3530         MonoJumpInfoRgctxEntry *entry;
3531         MonoInst *rgctx;
3532
3533         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3534         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3535
3536         return emit_rgctx_fetch (cfg, rgctx, entry);
3537 }
3538
3539 /*
3540  * emit_get_rgctx_method:
3541  *
3542  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3543  * normal constants, else emit a load from the rgctx.
3544  */
3545 static MonoInst*
3546 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3547                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3548 {
3549         if (!context_used) {
3550                 MonoInst *ins;
3551
3552                 switch (rgctx_type) {
3553                 case MONO_RGCTX_INFO_METHOD:
3554                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3555                         return ins;
3556                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3557                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3558                         return ins;
3559                 default:
3560                         g_assert_not_reached ();
3561                 }
3562         } else {
3563                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3564                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3565
3566                 return emit_rgctx_fetch (cfg, rgctx, entry);
3567         }
3568 }
3569
3570 static MonoInst*
3571 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3572                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3573 {
3574         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3575         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3576
3577         return emit_rgctx_fetch (cfg, rgctx, entry);
3578 }
3579
3580 static int
3581 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3582 {
3583         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3584         MonoRuntimeGenericContextInfoTemplate *template_;
3585         int i, idx;
3586
3587         g_assert (info);
3588
3589         for (i = 0; i < info->num_entries; ++i) {
3590                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3591
3592                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3593                         return i;
3594         }
3595
3596         if (info->num_entries == info->count_entries) {
3597                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3598                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3599
3600                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3601
3602                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3603                 info->entries = new_entries;
3604                 info->count_entries = new_count_entries;
3605         }
3606
3607         idx = info->num_entries;
3608         template_ = &info->entries [idx];
3609         template_->info_type = rgctx_type;
3610         template_->data = data;
3611
3612         info->num_entries ++;
3613
3614         return idx;
3615 }
3616
3617 /*
3618  * emit_get_gsharedvt_info:
3619  *
3620  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3621  */
3622 static MonoInst*
3623 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3624 {
3625         MonoInst *ins;
3626         int idx, dreg;
3627
3628         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3629         /* Load info->entries [idx] */
3630         dreg = alloc_preg (cfg);
3631         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3632
3633         return ins;
3634 }
3635
3636 static MonoInst*
3637 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3638 {
3639         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3640 }
3641
3642 /*
3643  * On return the caller must check @klass for load errors.
3644  */
3645 static void
3646 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3647 {
3648         MonoInst *vtable_arg;
3649         int context_used;
3650
3651         context_used = mini_class_check_context_used (cfg, klass);
3652
3653         if (context_used) {
3654                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3655                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3656         } else {
3657                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3658
3659                 if (!vtable)
3660                         return;
3661                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3662         }
3663
3664         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3665                 MonoInst *ins;
3666
3667                 /*
3668                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3669                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3670                  */
3671                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3672                 ins->sreg1 = vtable_arg->dreg;
3673                 MONO_ADD_INS (cfg->cbb, ins);
3674         } else {
3675                 int inited_reg;
3676                 MonoBasicBlock *inited_bb;
3677                 MonoInst *args [16];
3678
3679                 inited_reg = alloc_ireg (cfg);
3680
3681                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3682
3683                 NEW_BBLOCK (cfg, inited_bb);
3684
3685                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3686                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3687
3688                 args [0] = vtable_arg;
3689                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3690
3691                 MONO_START_BB (cfg, inited_bb);
3692         }
3693 }
3694
3695 static void
3696 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3697 {
3698         MonoInst *ins;
3699
3700         if (cfg->gen_seq_points && cfg->method == method) {
3701                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3702                 if (nonempty_stack)
3703                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3704                 MONO_ADD_INS (cfg->cbb, ins);
3705         }
3706 }
3707
3708 void
3709 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3710 {
3711         if (mini_get_debug_options ()->better_cast_details) {
3712                 int vtable_reg = alloc_preg (cfg);
3713                 int klass_reg = alloc_preg (cfg);
3714                 MonoBasicBlock *is_null_bb = NULL;
3715                 MonoInst *tls_get;
3716                 int to_klass_reg, context_used;
3717
3718                 if (null_check) {
3719                         NEW_BBLOCK (cfg, is_null_bb);
3720
3721                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3722                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3723                 }
3724
3725                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3726                 if (!tls_get) {
3727                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3728                         exit (1);
3729                 }
3730
3731                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3732                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3733
3734                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3735
3736                 context_used = mini_class_check_context_used (cfg, klass);
3737                 if (context_used) {
3738                         MonoInst *class_ins;
3739
3740                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3741                         to_klass_reg = class_ins->dreg;
3742                 } else {
3743                         to_klass_reg = alloc_preg (cfg);
3744                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3745                 }
3746                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3747
3748                 if (null_check)
3749                         MONO_START_BB (cfg, is_null_bb);
3750         }
3751 }
3752
3753 void
3754 mini_reset_cast_details (MonoCompile *cfg)
3755 {
3756         /* Reset the variables holding the cast details */
3757         if (mini_get_debug_options ()->better_cast_details) {
3758                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3759                 /* It is enough to reset the from field */
3760                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3761         }
3762 }
3763
3764 /*
3765  * On return the caller must check @array_class for load errors
3766  */
3767 static void
3768 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3769 {
3770         int vtable_reg = alloc_preg (cfg);
3771         int context_used;
3772
3773         context_used = mini_class_check_context_used (cfg, array_class);
3774
3775         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3776
3777         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3778
3779         if (cfg->opt & MONO_OPT_SHARED) {
3780                 int class_reg = alloc_preg (cfg);
3781                 MonoInst *ins;
3782
3783                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3784                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3785                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3786         } else if (context_used) {
3787                 MonoInst *vtable_ins;
3788
3789                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3790                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3791         } else {
3792                 if (cfg->compile_aot) {
3793                         int vt_reg;
3794                         MonoVTable *vtable;
3795
3796                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3797                                 return;
3798                         vt_reg = alloc_preg (cfg);
3799                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3800                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3801                 } else {
3802                         MonoVTable *vtable;
3803                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3804                                 return;
3805                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3806                 }
3807         }
3808         
3809         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3810
3811         mini_reset_cast_details (cfg);
3812 }
3813
3814 /**
3815  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3816  * generic code is generated.
3817  */
3818 static MonoInst*
3819 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3820 {
3821         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3822
3823         if (context_used) {
3824                 MonoInst *rgctx, *addr;
3825
3826                 /* FIXME: What if the class is shared?  We might not
3827                    have to get the address of the method from the
3828                    RGCTX. */
3829                 addr = emit_get_rgctx_method (cfg, context_used, method,
3830                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3831                 if (cfg->llvm_only) {
3832                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3833                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3834                 } else {
3835                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3836
3837                         return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3838                 }
3839         } else {
3840                 gboolean pass_vtable, pass_mrgctx;
3841                 MonoInst *rgctx_arg = NULL;
3842
3843                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3844                 g_assert (!pass_mrgctx);
3845
3846                 if (pass_vtable) {
3847                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3848
3849                         g_assert (vtable);
3850                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3851                 }
3852
3853                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3854         }
3855 }
3856
3857 static MonoInst*
3858 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3859 {
3860         MonoInst *add;
3861         int obj_reg;
3862         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3863         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3864         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3865         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3866
3867         obj_reg = sp [0]->dreg;
3868         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3869         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3870
3871         /* FIXME: generics */
3872         g_assert (klass->rank == 0);
3873                         
3874         // Check rank == 0
3875         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3876         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3877
3878         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3879         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3880
3881         if (context_used) {
3882                 MonoInst *element_class;
3883
3884                 /* This assertion is from the unboxcast insn */
3885                 g_assert (klass->rank == 0);
3886
3887                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3888                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3889
3890                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3891                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3892         } else {
3893                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3894                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3895                 mini_reset_cast_details (cfg);
3896         }
3897
3898         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3899         MONO_ADD_INS (cfg->cbb, add);
3900         add->type = STACK_MP;
3901         add->klass = klass;
3902
3903         return add;
3904 }
3905
3906 static MonoInst*
3907 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3908 {
3909         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3910         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3911         MonoInst *ins;
3912         int dreg, addr_reg;
3913
3914         klass_inst = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3915
3916         /* obj */
3917         args [0] = obj;
3918
3919         /* klass */
3920         args [1] = klass_inst;
3921
3922         /* CASTCLASS */
3923         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3924
3925         NEW_BBLOCK (cfg, is_ref_bb);
3926         NEW_BBLOCK (cfg, is_nullable_bb);
3927         NEW_BBLOCK (cfg, end_bb);
3928         is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3929         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3930         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3931
3932         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3933         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3934
3935         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3936         addr_reg = alloc_dreg (cfg, STACK_MP);
3937
3938         /* Non-ref case */
3939         /* UNBOX */
3940         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3941         MONO_ADD_INS (cfg->cbb, addr);
3942
3943         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3944
3945         /* Ref case */
3946         MONO_START_BB (cfg, is_ref_bb);
3947
3948         /* Save the ref to a temporary */
3949         dreg = alloc_ireg (cfg);
3950         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3951         addr->dreg = addr_reg;
3952         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3953         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3954
3955         /* Nullable case */
3956         MONO_START_BB (cfg, is_nullable_bb);
3957
3958         {
3959                 MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3960                 MonoInst *unbox_call;
3961                 MonoMethodSignature *unbox_sig;
3962
3963                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3964                 unbox_sig->ret = &klass->byval_arg;
3965                 unbox_sig->param_count = 1;
3966                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3967
3968                 if (cfg->llvm_only)
3969                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3970                 else
3971                         unbox_call = mono_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3972
3973                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3974                 addr->dreg = addr_reg;
3975         }
3976
3977         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3978
3979         /* End */
3980         MONO_START_BB (cfg, end_bb);
3981
3982         /* LDOBJ */
3983         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3984
3985         return ins;
3986 }
3987
3988 /*
3989  * Returns NULL and set the cfg exception on error.
3990  */
3991 static MonoInst*
3992 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3993 {
3994         MonoInst *iargs [2];
3995         void *alloc_ftn;
3996
3997         if (context_used) {
3998                 MonoInst *data;
3999                 MonoRgctxInfoType rgctx_info;
4000                 MonoInst *iargs [2];
4001                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
4002
4003                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
4004
4005                 if (cfg->opt & MONO_OPT_SHARED)
4006                         rgctx_info = MONO_RGCTX_INFO_KLASS;
4007                 else
4008                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
4009                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
4010
4011                 if (cfg->opt & MONO_OPT_SHARED) {
4012                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4013                         iargs [1] = data;
4014                         alloc_ftn = ves_icall_object_new;
4015                 } else {
4016                         iargs [0] = data;
4017                         alloc_ftn = ves_icall_object_new_specific;
4018                 }
4019
4020                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
4021                         if (known_instance_size) {
4022                                 int size = mono_class_instance_size (klass);
4023                                 if (size < sizeof (MonoObject))
4024                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4025
4026                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
4027                         }
4028                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4029                 }
4030
4031                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4032         }
4033
4034         if (cfg->opt & MONO_OPT_SHARED) {
4035                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4036                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
4037
4038                 alloc_ftn = ves_icall_object_new;
4039         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
4040                 /* This happens often in argument checking code, eg. throw new FooException... */
4041                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
4042                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
4043                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
4044         } else {
4045                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4046                 MonoMethod *managed_alloc = NULL;
4047                 gboolean pass_lw;
4048
4049                 if (!vtable) {
4050                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4051                         cfg->exception_ptr = klass;
4052                         return NULL;
4053                 }
4054
4055                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
4056
4057                 if (managed_alloc) {
4058                         int size = mono_class_instance_size (klass);
4059                         if (size < sizeof (MonoObject))
4060                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4061
4062                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4063                         EMIT_NEW_ICONST (cfg, iargs [1], size);
4064                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4065                 }
4066                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
4067                 if (pass_lw) {
4068                         guint32 lw = vtable->klass->instance_size;
4069                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
4070                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
4071                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
4072                 }
4073                 else {
4074                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4075                 }
4076         }
4077
4078         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4079 }
4080         
4081 /*
4082  * Returns NULL and set the cfg exception on error.
4083  */     
4084 static MonoInst*
4085 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
4086 {
4087         MonoInst *alloc, *ins;
4088
4089         if (mono_class_is_nullable (klass)) {
4090                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4091
4092                 if (context_used) {
4093                         if (cfg->llvm_only && cfg->gsharedvt) {
4094                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4095                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4096                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4097                         } else {
4098                                 /* FIXME: What if the class is shared?  We might not
4099                                    have to get the method address from the RGCTX. */
4100                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4101                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4102                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
4103
4104                                 return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4105                         }
4106                 } else {
4107                         gboolean pass_vtable, pass_mrgctx;
4108                         MonoInst *rgctx_arg = NULL;
4109
4110                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4111                         g_assert (!pass_mrgctx);
4112
4113                         if (pass_vtable) {
4114                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4115
4116                                 g_assert (vtable);
4117                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4118                         }
4119
4120                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4121                 }
4122         }
4123
4124         if (mini_is_gsharedvt_klass (klass)) {
4125                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4126                 MonoInst *res, *is_ref, *src_var, *addr;
4127                 int dreg;
4128
4129                 dreg = alloc_ireg (cfg);
4130
4131                 NEW_BBLOCK (cfg, is_ref_bb);
4132                 NEW_BBLOCK (cfg, is_nullable_bb);
4133                 NEW_BBLOCK (cfg, end_bb);
4134                 is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4135                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4136                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4137
4138                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4139                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4140
4141                 /* Non-ref case */
4142                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4143                 if (!alloc)
4144                         return NULL;
4145                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4146                 ins->opcode = OP_STOREV_MEMBASE;
4147
4148                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4149                 res->type = STACK_OBJ;
4150                 res->klass = klass;
4151                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4152                 
4153                 /* Ref case */
4154                 MONO_START_BB (cfg, is_ref_bb);
4155
4156                 /* val is a vtype, so has to load the value manually */
4157                 src_var = get_vreg_to_inst (cfg, val->dreg);
4158                 if (!src_var)
4159                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4160                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4161                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4162                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4163
4164                 /* Nullable case */
4165                 MONO_START_BB (cfg, is_nullable_bb);
4166
4167                 {
4168                         MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass,
4169                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4170                         MonoInst *box_call;
4171                         MonoMethodSignature *box_sig;
4172
4173                         /*
4174                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4175                          * construct that method at JIT time, so have to do things by hand.
4176                          */
4177                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4178                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4179                         box_sig->param_count = 1;
4180                         box_sig->params [0] = &klass->byval_arg;
4181
4182                         if (cfg->llvm_only)
4183                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4184                         else
4185                                 box_call = mono_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4186                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4187                         res->type = STACK_OBJ;
4188                         res->klass = klass;
4189                 }
4190
4191                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4192
4193                 MONO_START_BB (cfg, end_bb);
4194
4195                 return res;
4196         } else {
4197                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4198                 if (!alloc)
4199                         return NULL;
4200
4201                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4202                 return alloc;
4203         }
4204 }
4205
4206 static GHashTable* direct_icall_type_hash;
4207
4208 static gboolean
4209 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4210 {
4211         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4212         if (!direct_icalls_enabled (cfg))
4213                 return FALSE;
4214
4215         /*
4216          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4217          * Whitelist a few icalls for now.
4218          */
4219         if (!direct_icall_type_hash) {
4220                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4221
4222                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4223                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4224                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4225                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4226                 mono_memory_barrier ();
4227                 direct_icall_type_hash = h;
4228         }
4229
4230         if (cmethod->klass == mono_defaults.math_class)
4231                 return TRUE;
4232         /* No locking needed */
4233         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4234                 return TRUE;
4235         return FALSE;
4236 }
4237
4238 static gboolean
4239 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
4240 {
4241         if (cmethod->klass == mono_defaults.systemtype_class) {
4242                 if (!strcmp (cmethod->name, "GetType"))
4243                         return TRUE;
4244         }
4245         return FALSE;
4246 }
4247
4248 static G_GNUC_UNUSED MonoInst*
4249 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4250 {
4251         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4252         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4253         gboolean is_i4;
4254
4255         switch (enum_type->type) {
4256         case MONO_TYPE_I8:
4257         case MONO_TYPE_U8:
4258 #if SIZEOF_REGISTER == 8
4259         case MONO_TYPE_I:
4260         case MONO_TYPE_U:
4261 #endif
4262                 is_i4 = FALSE;
4263                 break;
4264         default:
4265                 is_i4 = TRUE;
4266                 break;
4267         }
4268
4269         {
4270                 MonoInst *load, *and_, *cmp, *ceq;
4271                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4272                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4273                 int dest_reg = alloc_ireg (cfg);
4274
4275                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
4276                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
4277                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
4278                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
4279
4280                 ceq->type = STACK_I4;
4281
4282                 if (!is_i4) {
4283                         load = mono_decompose_opcode (cfg, load);
4284                         and_ = mono_decompose_opcode (cfg, and_);
4285                         cmp = mono_decompose_opcode (cfg, cmp);
4286                         ceq = mono_decompose_opcode (cfg, ceq);
4287                 }
4288
4289                 return ceq;
4290         }
4291 }
4292
4293 /*
4294  * Returns NULL and set the cfg exception on error.
4295  */
4296 static G_GNUC_UNUSED MonoInst*
4297 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
4298 {
4299         MonoInst *ptr;
4300         int dreg;
4301         gpointer trampoline;
4302         MonoInst *obj, *method_ins, *tramp_ins;
4303         MonoDomain *domain;
4304         guint8 **code_slot;
4305
4306         if (virtual_ && !cfg->llvm_only) {
4307                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
4308                 g_assert (invoke);
4309
4310                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
4311                         return NULL;
4312         }
4313
4314         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
4315         if (!obj)
4316                 return NULL;
4317
4318         /* Inline the contents of mono_delegate_ctor */
4319
4320         /* Set target field */
4321         /* Optimize away setting of NULL target */
4322         if (!MONO_INS_IS_PCONST_NULL (target)) {
4323                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4324                 if (cfg->gen_write_barriers) {
4325                         dreg = alloc_preg (cfg);
4326                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4327                         emit_write_barrier (cfg, ptr, target);
4328                 }
4329         }
4330
4331         /* Set method field */
4332         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4333         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4334
4335         /* 
4336          * To avoid looking up the compiled code belonging to the target method
4337          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4338          * store it, and we fill it after the method has been compiled.
4339          */
4340         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4341                 MonoInst *code_slot_ins;
4342
4343                 if (context_used) {
4344                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4345                 } else {
4346                         domain = mono_domain_get ();
4347                         mono_domain_lock (domain);
4348                         if (!domain_jit_info (domain)->method_code_hash)
4349                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4350                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4351                         if (!code_slot) {
4352                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4353                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4354                         }
4355                         mono_domain_unlock (domain);
4356
4357                         code_slot_ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4358                 }
4359                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4360         }
4361
4362         if (cfg->llvm_only) {
4363                 MonoInst *args [16];
4364
4365                 if (virtual_) {
4366                         args [0] = obj;
4367                         args [1] = target;
4368                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4369                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4370                 } else {
4371                         args [0] = obj;
4372                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4373                 }
4374
4375                 return obj;
4376         }
4377
4378         if (cfg->compile_aot) {
4379                 MonoDelegateClassMethodPair *del_tramp;
4380
4381                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4382                 del_tramp->klass = klass;
4383                 del_tramp->method = context_used ? NULL : method;
4384                 del_tramp->is_virtual = virtual_;
4385                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4386         } else {
4387                 if (virtual_)
4388                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4389                 else
4390                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4391                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4392         }
4393
4394         /* Set invoke_impl field */
4395         if (virtual_) {
4396                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4397         } else {
4398                 dreg = alloc_preg (cfg);
4399                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4400                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4401
4402                 dreg = alloc_preg (cfg);
4403                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4404                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4405         }
4406
4407         dreg = alloc_preg (cfg);
4408         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4409         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4410
4411         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4412
4413         return obj;
4414 }
4415
4416 static MonoInst*
4417 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4418 {
4419         MonoJitICallInfo *info;
4420
4421         /* Need to register the icall so it gets an icall wrapper */
4422         info = mono_get_array_new_va_icall (rank);
4423
4424         cfg->flags |= MONO_CFG_HAS_VARARGS;
4425
4426         /* mono_array_new_va () needs a vararg calling convention */
4427         cfg->exception_message = g_strdup ("array-new");
4428         cfg->disable_llvm = TRUE;
4429
4430         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4431         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4432 }
4433
4434 /*
4435  * handle_constrained_gsharedvt_call:
4436  *
4437  *   Handle constrained calls where the receiver is a gsharedvt type.
4438  * Return the instruction representing the call. Set the cfg exception on failure.
4439  */
4440 static MonoInst*
4441 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4442                                                                    gboolean *ref_emit_widen)
4443 {
4444         MonoInst *ins = NULL;
4445         gboolean emit_widen = *ref_emit_widen;
4446
4447         /*
4448          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4449          * 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
4450          * pack the arguments into an array, and do the rest of the work in in an icall.
4451          */
4452         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4453                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret)) || mini_is_gsharedvt_type (fsig->ret)) &&
4454                 (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]))))) {
4455                 MonoInst *args [16];
4456
4457                 /*
4458                  * This case handles calls to
4459                  * - object:ToString()/Equals()/GetHashCode(),
4460                  * - System.IComparable<T>:CompareTo()
4461                  * - System.IEquatable<T>:Equals ()
4462                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4463                  */
4464
4465                 args [0] = sp [0];
4466                 if (mono_method_check_context_used (cmethod))
4467                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4468                 else
4469                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4470                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4471
4472                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4473                 if (fsig->hasthis && fsig->param_count) {
4474                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4475                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4476                         ins->dreg = alloc_preg (cfg);
4477                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4478                         MONO_ADD_INS (cfg->cbb, ins);
4479                         args [4] = ins;
4480
4481                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4482                                 int addr_reg, deref_arg_reg;
4483
4484                                 ins = emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4485                                 deref_arg_reg = alloc_preg (cfg);
4486                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4487                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4488
4489                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4490                                 addr_reg = ins->dreg;
4491                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4492                         } else {
4493                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4494                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4495                         }
4496                 } else {
4497                         EMIT_NEW_ICONST (cfg, args [3], 0);
4498                         EMIT_NEW_ICONST (cfg, args [4], 0);
4499                 }
4500                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4501                 emit_widen = FALSE;
4502
4503                 if (mini_is_gsharedvt_type (fsig->ret)) {
4504                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4505                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4506                         MonoInst *add;
4507
4508                         /* Unbox */
4509                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4510                         MONO_ADD_INS (cfg->cbb, add);
4511                         /* Load value */
4512                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4513                         MONO_ADD_INS (cfg->cbb, ins);
4514                         /* ins represents the call result */
4515                 }
4516         } else {
4517                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4518         }
4519
4520         *ref_emit_widen = emit_widen;
4521
4522         return ins;
4523
4524  exception_exit:
4525         return NULL;
4526 }
4527
4528 static void
4529 mono_emit_load_got_addr (MonoCompile *cfg)
4530 {
4531         MonoInst *getaddr, *dummy_use;
4532
4533         if (!cfg->got_var || cfg->got_var_allocated)
4534                 return;
4535
4536         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4537         getaddr->cil_code = cfg->header->code;
4538         getaddr->dreg = cfg->got_var->dreg;
4539
4540         /* Add it to the start of the first bblock */
4541         if (cfg->bb_entry->code) {
4542                 getaddr->next = cfg->bb_entry->code;
4543                 cfg->bb_entry->code = getaddr;
4544         }
4545         else
4546                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4547
4548         cfg->got_var_allocated = TRUE;
4549
4550         /* 
4551          * Add a dummy use to keep the got_var alive, since real uses might
4552          * only be generated by the back ends.
4553          * Add it to end_bblock, so the variable's lifetime covers the whole
4554          * method.
4555          * It would be better to make the usage of the got var explicit in all
4556          * cases when the backend needs it (i.e. calls, throw etc.), so this
4557          * wouldn't be needed.
4558          */
4559         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4560         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4561 }
4562
4563 static int inline_limit;
4564 static gboolean inline_limit_inited;
4565
4566 static gboolean
4567 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4568 {
4569         MonoMethodHeaderSummary header;
4570         MonoVTable *vtable;
4571 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4572         MonoMethodSignature *sig = mono_method_signature (method);
4573         int i;
4574 #endif
4575
4576         if (cfg->disable_inline)
4577                 return FALSE;
4578         if (cfg->gsharedvt)
4579                 return FALSE;
4580
4581         if (cfg->inline_depth > 10)
4582                 return FALSE;
4583
4584         if (!mono_method_get_header_summary (method, &header))
4585                 return FALSE;
4586
4587         /*runtime, icall and pinvoke are checked by summary call*/
4588         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4589             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4590             (mono_class_is_marshalbyref (method->klass)) ||
4591             header.has_clauses)
4592                 return FALSE;
4593
4594         /* also consider num_locals? */
4595         /* Do the size check early to avoid creating vtables */
4596         if (!inline_limit_inited) {
4597                 if (g_getenv ("MONO_INLINELIMIT"))
4598                         inline_limit = atoi (g_getenv ("MONO_INLINELIMIT"));
4599                 else
4600                         inline_limit = INLINE_LENGTH_LIMIT;
4601                 inline_limit_inited = TRUE;
4602         }
4603         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4604                 return FALSE;
4605
4606         /*
4607          * if we can initialize the class of the method right away, we do,
4608          * otherwise we don't allow inlining if the class needs initialization,
4609          * since it would mean inserting a call to mono_runtime_class_init()
4610          * inside the inlined code
4611          */
4612         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4613                 return FALSE;
4614
4615         if (!(cfg->opt & MONO_OPT_SHARED)) {
4616                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4617                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4618                         if (method->klass->has_cctor) {
4619                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4620                                 if (!vtable)
4621                                         return FALSE;
4622                                 if (!cfg->compile_aot) {
4623                                         MonoError error;
4624                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4625                                                 mono_error_cleanup (&error);
4626                                                 return FALSE;
4627                                         }
4628                                 }
4629                         }
4630                 } else if (mono_class_is_before_field_init (method->klass)) {
4631                         if (cfg->run_cctors && method->klass->has_cctor) {
4632                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4633                                 if (!method->klass->runtime_info)
4634                                         /* No vtable created yet */
4635                                         return FALSE;
4636                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4637                                 if (!vtable)
4638                                         return FALSE;
4639                                 /* This makes so that inline cannot trigger */
4640                                 /* .cctors: too many apps depend on them */
4641                                 /* running with a specific order... */
4642                                 if (! vtable->initialized)
4643                                         return FALSE;
4644                                 MonoError error;
4645                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4646                                         mono_error_cleanup (&error);
4647                                         return FALSE;
4648                                 }
4649                         }
4650                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4651                         if (!method->klass->runtime_info)
4652                                 /* No vtable created yet */
4653                                 return FALSE;
4654                         vtable = mono_class_vtable (cfg->domain, method->klass);
4655                         if (!vtable)
4656                                 return FALSE;
4657                         if (!vtable->initialized)
4658                                 return FALSE;
4659                 }
4660         } else {
4661                 /* 
4662                  * If we're compiling for shared code
4663                  * the cctor will need to be run at aot method load time, for example,
4664                  * or at the end of the compilation of the inlining method.
4665                  */
4666                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4667                         return FALSE;
4668         }
4669
4670 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4671         if (mono_arch_is_soft_float ()) {
4672                 /* FIXME: */
4673                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4674                         return FALSE;
4675                 for (i = 0; i < sig->param_count; ++i)
4676                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4677                                 return FALSE;
4678         }
4679 #endif
4680
4681         if (g_list_find (cfg->dont_inline, method))
4682                 return FALSE;
4683
4684         return TRUE;
4685 }
4686
4687 static gboolean
4688 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4689 {
4690         if (!cfg->compile_aot) {
4691                 g_assert (vtable);
4692                 if (vtable->initialized)
4693                         return FALSE;
4694         }
4695
4696         if (mono_class_is_before_field_init (klass)) {
4697                 if (cfg->method == method)
4698                         return FALSE;
4699         }
4700
4701         if (!mono_class_needs_cctor_run (klass, method))
4702                 return FALSE;
4703
4704         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4705                 /* The initialization is already done before the method is called */
4706                 return FALSE;
4707
4708         return TRUE;
4709 }
4710
4711 MonoInst*
4712 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4713 {
4714         MonoInst *ins;
4715         guint32 size;
4716         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4717         int context_used;
4718
4719         if (mini_is_gsharedvt_variable_klass (klass)) {
4720                 size = -1;
4721         } else {
4722                 mono_class_init (klass);
4723                 size = mono_class_array_element_size (klass);
4724         }
4725
4726         mult_reg = alloc_preg (cfg);
4727         array_reg = arr->dreg;
4728         index_reg = index->dreg;
4729
4730 #if SIZEOF_REGISTER == 8
4731         /* The array reg is 64 bits but the index reg is only 32 */
4732         if (COMPILE_LLVM (cfg)) {
4733                 /* Not needed */
4734                 index2_reg = index_reg;
4735         } else {
4736                 index2_reg = alloc_preg (cfg);
4737                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4738         }
4739 #else
4740         if (index->type == STACK_I8) {
4741                 index2_reg = alloc_preg (cfg);
4742                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4743         } else {
4744                 index2_reg = index_reg;
4745         }
4746 #endif
4747
4748         if (bcheck)
4749                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4750
4751 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4752         if (size == 1 || size == 2 || size == 4 || size == 8) {
4753                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4754
4755                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4756                 ins->klass = mono_class_get_element_class (klass);
4757                 ins->type = STACK_MP;
4758
4759                 return ins;
4760         }
4761 #endif          
4762
4763         add_reg = alloc_ireg_mp (cfg);
4764
4765         if (size == -1) {
4766                 MonoInst *rgctx_ins;
4767
4768                 /* gsharedvt */
4769                 g_assert (cfg->gshared);
4770                 context_used = mini_class_check_context_used (cfg, klass);
4771                 g_assert (context_used);
4772                 rgctx_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4773                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4774         } else {
4775                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4776         }
4777         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4778         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4779         ins->klass = mono_class_get_element_class (klass);
4780         ins->type = STACK_MP;
4781         MONO_ADD_INS (cfg->cbb, ins);
4782
4783         return ins;
4784 }
4785
4786 static MonoInst*
4787 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4788 {
4789         int bounds_reg = alloc_preg (cfg);
4790         int add_reg = alloc_ireg_mp (cfg);
4791         int mult_reg = alloc_preg (cfg);
4792         int mult2_reg = alloc_preg (cfg);
4793         int low1_reg = alloc_preg (cfg);
4794         int low2_reg = alloc_preg (cfg);
4795         int high1_reg = alloc_preg (cfg);
4796         int high2_reg = alloc_preg (cfg);
4797         int realidx1_reg = alloc_preg (cfg);
4798         int realidx2_reg = alloc_preg (cfg);
4799         int sum_reg = alloc_preg (cfg);
4800         int index1, index2, tmpreg;
4801         MonoInst *ins;
4802         guint32 size;
4803
4804         mono_class_init (klass);
4805         size = mono_class_array_element_size (klass);
4806
4807         index1 = index_ins1->dreg;
4808         index2 = index_ins2->dreg;
4809
4810 #if SIZEOF_REGISTER == 8
4811         /* The array reg is 64 bits but the index reg is only 32 */
4812         if (COMPILE_LLVM (cfg)) {
4813                 /* Not needed */
4814         } else {
4815                 tmpreg = alloc_preg (cfg);
4816                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4817                 index1 = tmpreg;
4818                 tmpreg = alloc_preg (cfg);
4819                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4820                 index2 = tmpreg;
4821         }
4822 #else
4823         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4824         tmpreg = -1;
4825 #endif
4826
4827         /* range checking */
4828         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4829                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4830
4831         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4832                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4833         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4834         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4835                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4836         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4837         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4838
4839         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4840                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4841         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4842         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4843                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4844         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4845         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4846
4847         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4848         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4849         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4850         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4851         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4852
4853         ins->type = STACK_MP;
4854         ins->klass = klass;
4855         MONO_ADD_INS (cfg->cbb, ins);
4856
4857         return ins;
4858 }
4859
4860 static MonoInst*
4861 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4862 {
4863         int rank;
4864         MonoInst *addr;
4865         MonoMethod *addr_method;
4866         int element_size;
4867         MonoClass *eclass = cmethod->klass->element_class;
4868
4869         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4870
4871         if (rank == 1)
4872                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4873
4874         /* emit_ldelema_2 depends on OP_LMUL */
4875         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4876                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4877         }
4878
4879         if (mini_is_gsharedvt_variable_klass (eclass))
4880                 element_size = 0;
4881         else
4882                 element_size = mono_class_array_element_size (eclass);
4883         addr_method = mono_marshal_get_array_address (rank, element_size);
4884         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4885
4886         return addr;
4887 }
4888
4889 static MonoBreakPolicy
4890 always_insert_breakpoint (MonoMethod *method)
4891 {
4892         return MONO_BREAK_POLICY_ALWAYS;
4893 }
4894
4895 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
4896
4897 /**
4898  * mono_set_break_policy:
4899  * policy_callback: the new callback function
4900  *
4901  * Allow embedders to decide wherther to actually obey breakpoint instructions
4902  * (both break IL instructions and Debugger.Break () method calls), for example
4903  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
4904  * untrusted or semi-trusted code.
4905  *
4906  * @policy_callback will be called every time a break point instruction needs to
4907  * be inserted with the method argument being the method that calls Debugger.Break()
4908  * or has the IL break instruction. The callback should return #MONO_BREAK_POLICY_NEVER
4909  * if it wants the breakpoint to not be effective in the given method.
4910  * #MONO_BREAK_POLICY_ALWAYS is the default.
4911  */
4912 void
4913 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
4914 {
4915         if (policy_callback)
4916                 break_policy_func = policy_callback;
4917         else
4918                 break_policy_func = always_insert_breakpoint;
4919 }
4920
4921 static gboolean
4922 should_insert_brekpoint (MonoMethod *method) {
4923         switch (break_policy_func (method)) {
4924         case MONO_BREAK_POLICY_ALWAYS:
4925                 return TRUE;
4926         case MONO_BREAK_POLICY_NEVER:
4927                 return FALSE;
4928         case MONO_BREAK_POLICY_ON_DBG:
4929                 g_warning ("mdb no longer supported");
4930                 return FALSE;
4931         default:
4932                 g_warning ("Incorrect value returned from break policy callback");
4933                 return FALSE;
4934         }
4935 }
4936
4937 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4938 static MonoInst*
4939 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4940 {
4941         MonoInst *addr, *store, *load;
4942         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4943
4944         /* the bounds check is already done by the callers */
4945         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4946         if (is_set) {
4947                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4948                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4949                 if (mini_type_is_reference (&eklass->byval_arg))
4950                         emit_write_barrier (cfg, addr, load);
4951         } else {
4952                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4953                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4954         }
4955         return store;
4956 }
4957
4958
4959 static gboolean
4960 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4961 {
4962         return mini_type_is_reference (&klass->byval_arg);
4963 }
4964
4965 static MonoInst*
4966 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4967 {
4968         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4969                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4970                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4971                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4972                 MonoInst *iargs [3];
4973
4974                 if (!helper->slot)
4975                         mono_class_setup_vtable (obj_array);
4976                 g_assert (helper->slot);
4977
4978                 if (sp [0]->type != STACK_OBJ)
4979                         return NULL;
4980                 if (sp [2]->type != STACK_OBJ)
4981                         return NULL;
4982
4983                 iargs [2] = sp [2];
4984                 iargs [1] = sp [1];
4985                 iargs [0] = sp [0];
4986
4987                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4988         } else {
4989                 MonoInst *ins;
4990
4991                 if (mini_is_gsharedvt_variable_klass (klass)) {
4992                         MonoInst *addr;
4993
4994                         // FIXME-VT: OP_ICONST optimization
4995                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4996                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4997                         ins->opcode = OP_STOREV_MEMBASE;
4998                 } else if (sp [1]->opcode == OP_ICONST) {
4999                         int array_reg = sp [0]->dreg;
5000                         int index_reg = sp [1]->dreg;
5001                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
5002
5003                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
5004                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
5005
5006                         if (safety_checks)
5007                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
5008                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
5009                 } else {
5010                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
5011                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5012                         if (generic_class_is_reference_type (cfg, klass))
5013                                 emit_write_barrier (cfg, addr, sp [2]);
5014                 }
5015                 return ins;
5016         }
5017 }
5018
5019 static MonoInst*
5020 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5021 {
5022         MonoClass *eklass;
5023         
5024         if (is_set)
5025                 eklass = mono_class_from_mono_type (fsig->params [2]);
5026         else
5027                 eklass = mono_class_from_mono_type (fsig->ret);
5028
5029         if (is_set) {
5030                 return emit_array_store (cfg, eklass, args, FALSE);
5031         } else {
5032                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5033                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
5034                 return ins;
5035         }
5036 }
5037
5038 static gboolean
5039 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
5040 {
5041         uint32_t align;
5042         int param_size, return_size;
5043
5044         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
5045         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
5046
5047         if (cfg->verbose_level > 3)
5048                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
5049
5050         //Don't allow mixing reference types with value types
5051         if (param_klass->valuetype != return_klass->valuetype) {
5052                 if (cfg->verbose_level > 3)
5053                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
5054                 return FALSE;
5055         }
5056
5057         if (!param_klass->valuetype) {
5058                 if (cfg->verbose_level > 3)
5059                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
5060                 return TRUE;
5061         }
5062
5063         //That are blitable
5064         if (param_klass->has_references || return_klass->has_references)
5065                 return FALSE;
5066
5067         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
5068         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
5069                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
5070                         if (cfg->verbose_level > 3)
5071                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
5072                 return FALSE;
5073         }
5074
5075         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
5076                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
5077                 if (cfg->verbose_level > 3)
5078                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
5079                 return FALSE;
5080         }
5081
5082         param_size = mono_class_value_size (param_klass, &align);
5083         return_size = mono_class_value_size (return_klass, &align);
5084
5085         //We can do it if sizes match
5086         if (param_size == return_size) {
5087                 if (cfg->verbose_level > 3)
5088                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
5089                 return TRUE;
5090         }
5091
5092         //No simple way to handle struct if sizes don't match
5093         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
5094                 if (cfg->verbose_level > 3)
5095                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
5096                 return FALSE;
5097         }
5098
5099         /*
5100          * Same reg size category.
5101          * A quick note on why we don't require widening here.
5102          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
5103          *
5104          * Since the source value comes from a function argument, the JIT will already have
5105          * the value in a VREG and performed any widening needed before (say, when loading from a field).
5106          */
5107         if (param_size <= 4 && return_size <= 4) {
5108                 if (cfg->verbose_level > 3)
5109                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
5110                 return TRUE;
5111         }
5112
5113         return FALSE;
5114 }
5115
5116 static MonoInst*
5117 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
5118 {
5119         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
5120         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
5121
5122         if (mini_is_gsharedvt_variable_type (fsig->ret))
5123                 return NULL;
5124
5125         //Valuetypes that are semantically equivalent or numbers than can be widened to
5126         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5127                 return args [0];
5128
5129         //Arrays of valuetypes that are semantically equivalent
5130         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5131                 return args [0];
5132
5133         return NULL;
5134 }
5135
5136 static MonoInst*
5137 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5138 {
5139 #ifdef MONO_ARCH_SIMD_INTRINSICS
5140         MonoInst *ins = NULL;
5141
5142         if (cfg->opt & MONO_OPT_SIMD) {
5143                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5144                 if (ins)
5145                         return ins;
5146         }
5147 #endif
5148
5149         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5150 }
5151
5152 static MonoInst*
5153 emit_memory_barrier (MonoCompile *cfg, int kind)
5154 {
5155         MonoInst *ins = NULL;
5156         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5157         MONO_ADD_INS (cfg->cbb, ins);
5158         ins->backend.memory_barrier_kind = kind;
5159
5160         return ins;
5161 }
5162
5163 static MonoInst*
5164 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5165 {
5166         MonoInst *ins = NULL;
5167         int opcode = 0;
5168
5169         /* The LLVM backend supports these intrinsics */
5170         if (cmethod->klass == mono_defaults.math_class) {
5171                 if (strcmp (cmethod->name, "Sin") == 0) {
5172                         opcode = OP_SIN;
5173                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5174                         opcode = OP_COS;
5175                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5176                         opcode = OP_SQRT;
5177                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5178                         opcode = OP_ABS;
5179                 }
5180
5181                 if (opcode && fsig->param_count == 1) {
5182                         MONO_INST_NEW (cfg, ins, opcode);
5183                         ins->type = STACK_R8;
5184                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5185                         ins->sreg1 = args [0]->dreg;
5186                         MONO_ADD_INS (cfg->cbb, ins);
5187                 }
5188
5189                 opcode = 0;
5190                 if (cfg->opt & MONO_OPT_CMOV) {
5191                         if (strcmp (cmethod->name, "Min") == 0) {
5192                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5193                                         opcode = OP_IMIN;
5194                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5195                                         opcode = OP_IMIN_UN;
5196                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5197                                         opcode = OP_LMIN;
5198                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5199                                         opcode = OP_LMIN_UN;
5200                         } else if (strcmp (cmethod->name, "Max") == 0) {
5201                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5202                                         opcode = OP_IMAX;
5203                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5204                                         opcode = OP_IMAX_UN;
5205                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5206                                         opcode = OP_LMAX;
5207                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5208                                         opcode = OP_LMAX_UN;
5209                         }
5210                 }
5211
5212                 if (opcode && fsig->param_count == 2) {
5213                         MONO_INST_NEW (cfg, ins, opcode);
5214                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5215                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5216                         ins->sreg1 = args [0]->dreg;
5217                         ins->sreg2 = args [1]->dreg;
5218                         MONO_ADD_INS (cfg->cbb, ins);
5219                 }
5220         }
5221
5222         return ins;
5223 }
5224
5225 static MonoInst*
5226 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5227 {
5228         if (cmethod->klass == mono_defaults.array_class) {
5229                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5230                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5231                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5232                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5233                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5234                         return emit_array_unsafe_mov (cfg, fsig, args);
5235         }
5236
5237         return NULL;
5238 }
5239
5240 static MonoInst*
5241 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5242 {
5243         MonoInst *ins = NULL;
5244
5245          MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5246
5247         if (cmethod->klass == mono_defaults.string_class) {
5248                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5249                         int dreg = alloc_ireg (cfg);
5250                         int index_reg = alloc_preg (cfg);
5251                         int add_reg = alloc_preg (cfg);
5252
5253 #if SIZEOF_REGISTER == 8
5254                         if (COMPILE_LLVM (cfg)) {
5255                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5256                         } else {
5257                                 /* The array reg is 64 bits but the index reg is only 32 */
5258                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5259                         }
5260 #else
5261                         index_reg = args [1]->dreg;
5262 #endif  
5263                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5264
5265 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5266                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5267                         add_reg = ins->dreg;
5268                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5269                                                                    add_reg, 0);
5270 #else
5271                         int mult_reg = alloc_preg (cfg);
5272                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5273                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5274                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5275                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
5276 #endif
5277                         type_from_op (cfg, ins, NULL, NULL);
5278                         return ins;
5279                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5280                         int dreg = alloc_ireg (cfg);
5281                         /* Decompose later to allow more optimizations */
5282                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
5283                         ins->type = STACK_I4;
5284                         ins->flags |= MONO_INST_FAULT;
5285                         cfg->cbb->has_array_access = TRUE;
5286                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
5287
5288                         return ins;
5289                 } else 
5290                         return NULL;
5291         } else if (cmethod->klass == mono_defaults.object_class) {
5292                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
5293                         int dreg = alloc_ireg_ref (cfg);
5294                         int vt_reg = alloc_preg (cfg);
5295                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5296                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
5297                         type_from_op (cfg, ins, NULL, NULL);
5298
5299                         return ins;
5300                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
5301                         int dreg = alloc_ireg (cfg);
5302                         int t1 = alloc_ireg (cfg);
5303         
5304                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
5305                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
5306                         ins->type = STACK_I4;
5307
5308                         return ins;
5309                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
5310                         MONO_INST_NEW (cfg, ins, OP_NOP);
5311                         MONO_ADD_INS (cfg->cbb, ins);
5312                         return ins;
5313                 } else
5314                         return NULL;
5315         } else if (cmethod->klass == mono_defaults.array_class) {
5316                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5317                         return emit_array_generic_access (cfg, fsig, args, FALSE);
5318                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5319                         return emit_array_generic_access (cfg, fsig, args, TRUE);
5320
5321 #ifndef MONO_BIG_ARRAYS
5322                 /*
5323                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
5324                  * Array methods.
5325                  */
5326                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
5327                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
5328                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
5329                         int dreg = alloc_ireg (cfg);
5330                         int bounds_reg = alloc_ireg_mp (cfg);
5331                         MonoBasicBlock *end_bb, *szarray_bb;
5332                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
5333
5334                         NEW_BBLOCK (cfg, end_bb);
5335                         NEW_BBLOCK (cfg, szarray_bb);
5336
5337                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
5338                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5339                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5340                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5341                         /* Non-szarray case */
5342                         if (get_length)
5343                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5344                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5345                         else
5346                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5347                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5348                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5349                         MONO_START_BB (cfg, szarray_bb);
5350                         /* Szarray case */
5351                         if (get_length)
5352                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5353                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5354                         else
5355                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5356                         MONO_START_BB (cfg, end_bb);
5357
5358                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5359                         ins->type = STACK_I4;
5360                         
5361                         return ins;
5362                 }
5363 #endif
5364
5365                 if (cmethod->name [0] != 'g')
5366                         return NULL;
5367
5368                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5369                         int dreg = alloc_ireg (cfg);
5370                         int vtable_reg = alloc_preg (cfg);
5371                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5372                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5373                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5374                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5375                         type_from_op (cfg, ins, NULL, NULL);
5376
5377                         return ins;
5378                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5379                         int dreg = alloc_ireg (cfg);
5380
5381                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5382                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5383                         type_from_op (cfg, ins, NULL, NULL);
5384
5385                         return ins;
5386                 } else
5387                         return NULL;
5388         } else if (cmethod->klass == runtime_helpers_class) {
5389                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5390                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5391                         return ins;
5392                 } else
5393                         return NULL;
5394         } else if (cmethod->klass == mono_defaults.monitor_class) {
5395                 gboolean is_enter = FALSE;
5396                 gboolean is_v4 = FALSE;
5397
5398                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5399                         is_enter = TRUE;
5400                         is_v4 = TRUE;
5401                 }
5402                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5403                         is_enter = TRUE;
5404
5405                 if (is_enter) {
5406                         /*
5407                          * To make async stack traces work, icalls which can block should have a wrapper.
5408                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5409                          */
5410                         MonoBasicBlock *end_bb;
5411
5412                         NEW_BBLOCK (cfg, end_bb);
5413
5414                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5415                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5416                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5417                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5418                         MONO_START_BB (cfg, end_bb);
5419                         return ins;
5420                 }
5421         } else if (cmethod->klass == mono_defaults.thread_class) {
5422                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5423                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5424                         MONO_ADD_INS (cfg->cbb, ins);
5425                         return ins;
5426                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5427                         return emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5428                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5429                         guint32 opcode = 0;
5430                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5431
5432                         if (fsig->params [0]->type == MONO_TYPE_I1)
5433                                 opcode = OP_LOADI1_MEMBASE;
5434                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5435                                 opcode = OP_LOADU1_MEMBASE;
5436                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5437                                 opcode = OP_LOADI2_MEMBASE;
5438                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5439                                 opcode = OP_LOADU2_MEMBASE;
5440                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5441                                 opcode = OP_LOADI4_MEMBASE;
5442                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5443                                 opcode = OP_LOADU4_MEMBASE;
5444                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5445                                 opcode = OP_LOADI8_MEMBASE;
5446                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5447                                 opcode = OP_LOADR4_MEMBASE;
5448                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5449                                 opcode = OP_LOADR8_MEMBASE;
5450                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5451                                 opcode = OP_LOAD_MEMBASE;
5452
5453                         if (opcode) {
5454                                 MONO_INST_NEW (cfg, ins, opcode);
5455                                 ins->inst_basereg = args [0]->dreg;
5456                                 ins->inst_offset = 0;
5457                                 MONO_ADD_INS (cfg->cbb, ins);
5458
5459                                 switch (fsig->params [0]->type) {
5460                                 case MONO_TYPE_I1:
5461                                 case MONO_TYPE_U1:
5462                                 case MONO_TYPE_I2:
5463                                 case MONO_TYPE_U2:
5464                                 case MONO_TYPE_I4:
5465                                 case MONO_TYPE_U4:
5466                                         ins->dreg = mono_alloc_ireg (cfg);
5467                                         ins->type = STACK_I4;
5468                                         break;
5469                                 case MONO_TYPE_I8:
5470                                 case MONO_TYPE_U8:
5471                                         ins->dreg = mono_alloc_lreg (cfg);
5472                                         ins->type = STACK_I8;
5473                                         break;
5474                                 case MONO_TYPE_I:
5475                                 case MONO_TYPE_U:
5476                                         ins->dreg = mono_alloc_ireg (cfg);
5477 #if SIZEOF_REGISTER == 8
5478                                         ins->type = STACK_I8;
5479 #else
5480                                         ins->type = STACK_I4;
5481 #endif
5482                                         break;
5483                                 case MONO_TYPE_R4:
5484                                 case MONO_TYPE_R8:
5485                                         ins->dreg = mono_alloc_freg (cfg);
5486                                         ins->type = STACK_R8;
5487                                         break;
5488                                 default:
5489                                         g_assert (mini_type_is_reference (fsig->params [0]));
5490                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5491                                         ins->type = STACK_OBJ;
5492                                         break;
5493                                 }
5494
5495                                 if (opcode == OP_LOADI8_MEMBASE)
5496                                         ins = mono_decompose_opcode (cfg, ins);
5497
5498                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5499
5500                                 return ins;
5501                         }
5502                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5503                         guint32 opcode = 0;
5504                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5505
5506                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5507                                 opcode = OP_STOREI1_MEMBASE_REG;
5508                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5509                                 opcode = OP_STOREI2_MEMBASE_REG;
5510                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5511                                 opcode = OP_STOREI4_MEMBASE_REG;
5512                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5513                                 opcode = OP_STOREI8_MEMBASE_REG;
5514                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5515                                 opcode = OP_STORER4_MEMBASE_REG;
5516                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5517                                 opcode = OP_STORER8_MEMBASE_REG;
5518                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5519                                 opcode = OP_STORE_MEMBASE_REG;
5520
5521                         if (opcode) {
5522                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5523
5524                                 MONO_INST_NEW (cfg, ins, opcode);
5525                                 ins->sreg1 = args [1]->dreg;
5526                                 ins->inst_destbasereg = args [0]->dreg;
5527                                 ins->inst_offset = 0;
5528                                 MONO_ADD_INS (cfg->cbb, ins);
5529
5530                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5531                                         ins = mono_decompose_opcode (cfg, ins);
5532
5533                                 return ins;
5534                         }
5535                 }
5536         } else if (cmethod->klass->image == mono_defaults.corlib &&
5537                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5538                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5539                 ins = NULL;
5540
5541 #if SIZEOF_REGISTER == 8
5542                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5543                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5544                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5545                                 ins->dreg = mono_alloc_preg (cfg);
5546                                 ins->sreg1 = args [0]->dreg;
5547                                 ins->type = STACK_I8;
5548                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5549                                 MONO_ADD_INS (cfg->cbb, ins);
5550                         } else {
5551                                 MonoInst *load_ins;
5552
5553                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5554
5555                                 /* 64 bit reads are already atomic */
5556                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5557                                 load_ins->dreg = mono_alloc_preg (cfg);
5558                                 load_ins->inst_basereg = args [0]->dreg;
5559                                 load_ins->inst_offset = 0;
5560                                 load_ins->type = STACK_I8;
5561                                 MONO_ADD_INS (cfg->cbb, load_ins);
5562
5563                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5564
5565                                 ins = load_ins;
5566                         }
5567                 }
5568 #endif
5569
5570                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5571                         MonoInst *ins_iconst;
5572                         guint32 opcode = 0;
5573
5574                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5575                                 opcode = OP_ATOMIC_ADD_I4;
5576                                 cfg->has_atomic_add_i4 = TRUE;
5577                         }
5578 #if SIZEOF_REGISTER == 8
5579                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5580                                 opcode = OP_ATOMIC_ADD_I8;
5581 #endif
5582                         if (opcode) {
5583                                 if (!mono_arch_opcode_supported (opcode))
5584                                         return NULL;
5585                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5586                                 ins_iconst->inst_c0 = 1;
5587                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5588                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5589
5590                                 MONO_INST_NEW (cfg, ins, opcode);
5591                                 ins->dreg = mono_alloc_ireg (cfg);
5592                                 ins->inst_basereg = args [0]->dreg;
5593                                 ins->inst_offset = 0;
5594                                 ins->sreg2 = ins_iconst->dreg;
5595                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5596                                 MONO_ADD_INS (cfg->cbb, ins);
5597                         }
5598                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5599                         MonoInst *ins_iconst;
5600                         guint32 opcode = 0;
5601
5602                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5603                                 opcode = OP_ATOMIC_ADD_I4;
5604                                 cfg->has_atomic_add_i4 = TRUE;
5605                         }
5606 #if SIZEOF_REGISTER == 8
5607                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5608                                 opcode = OP_ATOMIC_ADD_I8;
5609 #endif
5610                         if (opcode) {
5611                                 if (!mono_arch_opcode_supported (opcode))
5612                                         return NULL;
5613                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5614                                 ins_iconst->inst_c0 = -1;
5615                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5616                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5617
5618                                 MONO_INST_NEW (cfg, ins, opcode);
5619                                 ins->dreg = mono_alloc_ireg (cfg);
5620                                 ins->inst_basereg = args [0]->dreg;
5621                                 ins->inst_offset = 0;
5622                                 ins->sreg2 = ins_iconst->dreg;
5623                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5624                                 MONO_ADD_INS (cfg->cbb, ins);
5625                         }
5626                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5627                         guint32 opcode = 0;
5628
5629                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5630                                 opcode = OP_ATOMIC_ADD_I4;
5631                                 cfg->has_atomic_add_i4 = TRUE;
5632                         }
5633 #if SIZEOF_REGISTER == 8
5634                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5635                                 opcode = OP_ATOMIC_ADD_I8;
5636 #endif
5637                         if (opcode) {
5638                                 if (!mono_arch_opcode_supported (opcode))
5639                                         return NULL;
5640                                 MONO_INST_NEW (cfg, ins, opcode);
5641                                 ins->dreg = mono_alloc_ireg (cfg);
5642                                 ins->inst_basereg = args [0]->dreg;
5643                                 ins->inst_offset = 0;
5644                                 ins->sreg2 = args [1]->dreg;
5645                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5646                                 MONO_ADD_INS (cfg->cbb, ins);
5647                         }
5648                 }
5649                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5650                         MonoInst *f2i = NULL, *i2f;
5651                         guint32 opcode, f2i_opcode, i2f_opcode;
5652                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5653                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5654
5655                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5656                             fsig->params [0]->type == MONO_TYPE_R4) {
5657                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5658                                 f2i_opcode = OP_MOVE_F_TO_I4;
5659                                 i2f_opcode = OP_MOVE_I4_TO_F;
5660                                 cfg->has_atomic_exchange_i4 = TRUE;
5661                         }
5662 #if SIZEOF_REGISTER == 8
5663                         else if (is_ref ||
5664                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5665                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5666                                  fsig->params [0]->type == MONO_TYPE_I) {
5667                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5668                                 f2i_opcode = OP_MOVE_F_TO_I8;
5669                                 i2f_opcode = OP_MOVE_I8_TO_F;
5670                         }
5671 #else
5672                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5673                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5674                                 cfg->has_atomic_exchange_i4 = TRUE;
5675                         }
5676 #endif
5677                         else
5678                                 return NULL;
5679
5680                         if (!mono_arch_opcode_supported (opcode))
5681                                 return NULL;
5682
5683                         if (is_float) {
5684                                 /* TODO: Decompose these opcodes instead of bailing here. */
5685                                 if (COMPILE_SOFT_FLOAT (cfg))
5686                                         return NULL;
5687
5688                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5689                                 f2i->dreg = mono_alloc_ireg (cfg);
5690                                 f2i->sreg1 = args [1]->dreg;
5691                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5692                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5693                                 MONO_ADD_INS (cfg->cbb, f2i);
5694                         }
5695
5696                         MONO_INST_NEW (cfg, ins, opcode);
5697                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5698                         ins->inst_basereg = args [0]->dreg;
5699                         ins->inst_offset = 0;
5700                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5701                         MONO_ADD_INS (cfg->cbb, ins);
5702
5703                         switch (fsig->params [0]->type) {
5704                         case MONO_TYPE_I4:
5705                                 ins->type = STACK_I4;
5706                                 break;
5707                         case MONO_TYPE_I8:
5708                                 ins->type = STACK_I8;
5709                                 break;
5710                         case MONO_TYPE_I:
5711 #if SIZEOF_REGISTER == 8
5712                                 ins->type = STACK_I8;
5713 #else
5714                                 ins->type = STACK_I4;
5715 #endif
5716                                 break;
5717                         case MONO_TYPE_R4:
5718                         case MONO_TYPE_R8:
5719                                 ins->type = STACK_R8;
5720                                 break;
5721                         default:
5722                                 g_assert (mini_type_is_reference (fsig->params [0]));
5723                                 ins->type = STACK_OBJ;
5724                                 break;
5725                         }
5726
5727                         if (is_float) {
5728                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5729                                 i2f->dreg = mono_alloc_freg (cfg);
5730                                 i2f->sreg1 = ins->dreg;
5731                                 i2f->type = STACK_R8;
5732                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5733                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5734                                 MONO_ADD_INS (cfg->cbb, i2f);
5735
5736                                 ins = i2f;
5737                         }
5738
5739                         if (cfg->gen_write_barriers && is_ref)
5740                                 emit_write_barrier (cfg, args [0], args [1]);
5741                 }
5742                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5743                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5744                         guint32 opcode, f2i_opcode, i2f_opcode;
5745                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5746                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5747
5748                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5749                             fsig->params [1]->type == MONO_TYPE_R4) {
5750                                 opcode = OP_ATOMIC_CAS_I4;
5751                                 f2i_opcode = OP_MOVE_F_TO_I4;
5752                                 i2f_opcode = OP_MOVE_I4_TO_F;
5753                                 cfg->has_atomic_cas_i4 = TRUE;
5754                         }
5755 #if SIZEOF_REGISTER == 8
5756                         else if (is_ref ||
5757                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5758                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5759                                  fsig->params [1]->type == MONO_TYPE_I) {
5760                                 opcode = OP_ATOMIC_CAS_I8;
5761                                 f2i_opcode = OP_MOVE_F_TO_I8;
5762                                 i2f_opcode = OP_MOVE_I8_TO_F;
5763                         }
5764 #else
5765                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5766                                 opcode = OP_ATOMIC_CAS_I4;
5767                                 cfg->has_atomic_cas_i4 = TRUE;
5768                         }
5769 #endif
5770                         else
5771                                 return NULL;
5772
5773                         if (!mono_arch_opcode_supported (opcode))
5774                                 return NULL;
5775
5776                         if (is_float) {
5777                                 /* TODO: Decompose these opcodes instead of bailing here. */
5778                                 if (COMPILE_SOFT_FLOAT (cfg))
5779                                         return NULL;
5780
5781                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5782                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5783                                 f2i_new->sreg1 = args [1]->dreg;
5784                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5785                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5786                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5787
5788                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5789                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5790                                 f2i_cmp->sreg1 = args [2]->dreg;
5791                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5792                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5793                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5794                         }
5795
5796                         MONO_INST_NEW (cfg, ins, opcode);
5797                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5798                         ins->sreg1 = args [0]->dreg;
5799                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5800                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5801                         MONO_ADD_INS (cfg->cbb, ins);
5802
5803                         switch (fsig->params [1]->type) {
5804                         case MONO_TYPE_I4:
5805                                 ins->type = STACK_I4;
5806                                 break;
5807                         case MONO_TYPE_I8:
5808                                 ins->type = STACK_I8;
5809                                 break;
5810                         case MONO_TYPE_I:
5811 #if SIZEOF_REGISTER == 8
5812                                 ins->type = STACK_I8;
5813 #else
5814                                 ins->type = STACK_I4;
5815 #endif
5816                                 break;
5817                         case MONO_TYPE_R4:
5818                                 ins->type = cfg->r4_stack_type;
5819                                 break;
5820                         case MONO_TYPE_R8:
5821                                 ins->type = STACK_R8;
5822                                 break;
5823                         default:
5824                                 g_assert (mini_type_is_reference (fsig->params [1]));
5825                                 ins->type = STACK_OBJ;
5826                                 break;
5827                         }
5828
5829                         if (is_float) {
5830                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5831                                 i2f->dreg = mono_alloc_freg (cfg);
5832                                 i2f->sreg1 = ins->dreg;
5833                                 i2f->type = STACK_R8;
5834                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5835                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5836                                 MONO_ADD_INS (cfg->cbb, i2f);
5837
5838                                 ins = i2f;
5839                         }
5840
5841                         if (cfg->gen_write_barriers && is_ref)
5842                                 emit_write_barrier (cfg, args [0], args [1]);
5843                 }
5844                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5845                          fsig->params [1]->type == MONO_TYPE_I4) {
5846                         MonoInst *cmp, *ceq;
5847
5848                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5849                                 return NULL;
5850
5851                         /* int32 r = CAS (location, value, comparand); */
5852                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5853                         ins->dreg = alloc_ireg (cfg);
5854                         ins->sreg1 = args [0]->dreg;
5855                         ins->sreg2 = args [1]->dreg;
5856                         ins->sreg3 = args [2]->dreg;
5857                         ins->type = STACK_I4;
5858                         MONO_ADD_INS (cfg->cbb, ins);
5859
5860                         /* bool result = r == comparand; */
5861                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5862                         cmp->sreg1 = ins->dreg;
5863                         cmp->sreg2 = args [2]->dreg;
5864                         cmp->type = STACK_I4;
5865                         MONO_ADD_INS (cfg->cbb, cmp);
5866
5867                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5868                         ceq->dreg = alloc_ireg (cfg);
5869                         ceq->type = STACK_I4;
5870                         MONO_ADD_INS (cfg->cbb, ceq);
5871
5872                         /* *success = result; */
5873                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5874
5875                         cfg->has_atomic_cas_i4 = TRUE;
5876                 }
5877                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5878                         ins = emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5879
5880                 if (ins)
5881                         return ins;
5882         } else if (cmethod->klass->image == mono_defaults.corlib &&
5883                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5884                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5885                 ins = NULL;
5886
5887                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5888                         guint32 opcode = 0;
5889                         MonoType *t = fsig->params [0];
5890                         gboolean is_ref;
5891                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5892
5893                         g_assert (t->byref);
5894                         /* t is a byref type, so the reference check is more complicated */
5895                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5896                         if (t->type == MONO_TYPE_I1)
5897                                 opcode = OP_ATOMIC_LOAD_I1;
5898                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5899                                 opcode = OP_ATOMIC_LOAD_U1;
5900                         else if (t->type == MONO_TYPE_I2)
5901                                 opcode = OP_ATOMIC_LOAD_I2;
5902                         else if (t->type == MONO_TYPE_U2)
5903                                 opcode = OP_ATOMIC_LOAD_U2;
5904                         else if (t->type == MONO_TYPE_I4)
5905                                 opcode = OP_ATOMIC_LOAD_I4;
5906                         else if (t->type == MONO_TYPE_U4)
5907                                 opcode = OP_ATOMIC_LOAD_U4;
5908                         else if (t->type == MONO_TYPE_R4)
5909                                 opcode = OP_ATOMIC_LOAD_R4;
5910                         else if (t->type == MONO_TYPE_R8)
5911                                 opcode = OP_ATOMIC_LOAD_R8;
5912 #if SIZEOF_REGISTER == 8
5913                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5914                                 opcode = OP_ATOMIC_LOAD_I8;
5915                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5916                                 opcode = OP_ATOMIC_LOAD_U8;
5917 #else
5918                         else if (t->type == MONO_TYPE_I)
5919                                 opcode = OP_ATOMIC_LOAD_I4;
5920                         else if (is_ref || t->type == MONO_TYPE_U)
5921                                 opcode = OP_ATOMIC_LOAD_U4;
5922 #endif
5923
5924                         if (opcode) {
5925                                 if (!mono_arch_opcode_supported (opcode))
5926                                         return NULL;
5927
5928                                 MONO_INST_NEW (cfg, ins, opcode);
5929                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5930                                 ins->sreg1 = args [0]->dreg;
5931                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5932                                 MONO_ADD_INS (cfg->cbb, ins);
5933
5934                                 switch (t->type) {
5935                                 case MONO_TYPE_BOOLEAN:
5936                                 case MONO_TYPE_I1:
5937                                 case MONO_TYPE_U1:
5938                                 case MONO_TYPE_I2:
5939                                 case MONO_TYPE_U2:
5940                                 case MONO_TYPE_I4:
5941                                 case MONO_TYPE_U4:
5942                                         ins->type = STACK_I4;
5943                                         break;
5944                                 case MONO_TYPE_I8:
5945                                 case MONO_TYPE_U8:
5946                                         ins->type = STACK_I8;
5947                                         break;
5948                                 case MONO_TYPE_I:
5949                                 case MONO_TYPE_U:
5950 #if SIZEOF_REGISTER == 8
5951                                         ins->type = STACK_I8;
5952 #else
5953                                         ins->type = STACK_I4;
5954 #endif
5955                                         break;
5956                                 case MONO_TYPE_R4:
5957                                         ins->type = cfg->r4_stack_type;
5958                                         break;
5959                                 case MONO_TYPE_R8:
5960                                         ins->type = STACK_R8;
5961                                         break;
5962                                 default:
5963                                         g_assert (is_ref);
5964                                         ins->type = STACK_OBJ;
5965                                         break;
5966                                 }
5967                         }
5968                 }
5969
5970                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5971                         guint32 opcode = 0;
5972                         MonoType *t = fsig->params [0];
5973                         gboolean is_ref;
5974
5975                         g_assert (t->byref);
5976                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5977                         if (t->type == MONO_TYPE_I1)
5978                                 opcode = OP_ATOMIC_STORE_I1;
5979                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5980                                 opcode = OP_ATOMIC_STORE_U1;
5981                         else if (t->type == MONO_TYPE_I2)
5982                                 opcode = OP_ATOMIC_STORE_I2;
5983                         else if (t->type == MONO_TYPE_U2)
5984                                 opcode = OP_ATOMIC_STORE_U2;
5985                         else if (t->type == MONO_TYPE_I4)
5986                                 opcode = OP_ATOMIC_STORE_I4;
5987                         else if (t->type == MONO_TYPE_U4)
5988                                 opcode = OP_ATOMIC_STORE_U4;
5989                         else if (t->type == MONO_TYPE_R4)
5990                                 opcode = OP_ATOMIC_STORE_R4;
5991                         else if (t->type == MONO_TYPE_R8)
5992                                 opcode = OP_ATOMIC_STORE_R8;
5993 #if SIZEOF_REGISTER == 8
5994                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5995                                 opcode = OP_ATOMIC_STORE_I8;
5996                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5997                                 opcode = OP_ATOMIC_STORE_U8;
5998 #else
5999                         else if (t->type == MONO_TYPE_I)
6000                                 opcode = OP_ATOMIC_STORE_I4;
6001                         else if (is_ref || t->type == MONO_TYPE_U)
6002                                 opcode = OP_ATOMIC_STORE_U4;
6003 #endif
6004
6005                         if (opcode) {
6006                                 if (!mono_arch_opcode_supported (opcode))
6007                                         return NULL;
6008
6009                                 MONO_INST_NEW (cfg, ins, opcode);
6010                                 ins->dreg = args [0]->dreg;
6011                                 ins->sreg1 = args [1]->dreg;
6012                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
6013                                 MONO_ADD_INS (cfg->cbb, ins);
6014
6015                                 if (cfg->gen_write_barriers && is_ref)
6016                                         emit_write_barrier (cfg, args [0], args [1]);
6017                         }
6018                 }
6019
6020                 if (ins)
6021                         return ins;
6022         } else if (cmethod->klass->image == mono_defaults.corlib &&
6023                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
6024                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
6025                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
6026                         if (should_insert_brekpoint (cfg->method)) {
6027                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
6028                         } else {
6029                                 MONO_INST_NEW (cfg, ins, OP_NOP);
6030                                 MONO_ADD_INS (cfg->cbb, ins);
6031                         }
6032                         return ins;
6033                 }
6034         } else if (cmethod->klass->image == mono_defaults.corlib &&
6035                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
6036                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
6037                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
6038 #ifdef TARGET_WIN32
6039                         EMIT_NEW_ICONST (cfg, ins, 1);
6040 #else
6041                         EMIT_NEW_ICONST (cfg, ins, 0);
6042 #endif
6043                 }
6044         } else if (cmethod->klass->image == mono_defaults.corlib &&
6045                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6046                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
6047                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
6048                         /* No stack walks are currently available, so implement this as an intrinsic */
6049                         MonoInst *assembly_ins;
6050
6051                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
6052                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
6053                         return ins;
6054                 }
6055         } else if (cmethod->klass->image == mono_defaults.corlib &&
6056                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6057                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
6058                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
6059                         /* No stack walks are currently available, so implement this as an intrinsic */
6060                         MonoInst *method_ins;
6061                         MonoMethod *declaring = cfg->method;
6062
6063                         /* This returns the declaring generic method */
6064                         if (declaring->is_inflated)
6065                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
6066                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
6067                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
6068                         cfg->no_inline = TRUE;
6069                         if (cfg->method != cfg->current_method)
6070                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
6071                         return ins;
6072                 }
6073         } else if (cmethod->klass == mono_defaults.math_class) {
6074                 /* 
6075                  * There is general branchless code for Min/Max, but it does not work for 
6076                  * all inputs:
6077                  * http://everything2.com/?node_id=1051618
6078                  */
6079         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
6080                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
6081                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
6082                 ins->dreg = alloc_preg (cfg);
6083                 ins->type = STACK_I4;
6084                 MONO_ADD_INS (cfg->cbb, ins);
6085                 return ins;
6086         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
6087                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
6088                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
6089                                 !strcmp (cmethod->klass->name, "Selector")) ||
6090                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
6091                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
6092                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6093                                 !strcmp (cmethod->klass->name, "Selector"))
6094                            ) {
6095                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
6096                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6097                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6098                     cfg->compile_aot) {
6099                         MonoInst *pi;
6100                         MonoJumpInfoToken *ji;
6101                         char *s;
6102
6103                         if (args [0]->opcode == OP_GOT_ENTRY) {
6104                                 pi = (MonoInst *)args [0]->inst_p1;
6105                                 g_assert (pi->opcode == OP_PATCH_INFO);
6106                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6107                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6108                         } else {
6109                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6110                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6111                         }
6112
6113                         NULLIFY_INS (args [0]);
6114
6115                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6116                         return_val_if_nok (&cfg->error, NULL);
6117
6118                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6119                         ins->dreg = mono_alloc_ireg (cfg);
6120                         // FIXME: Leaks
6121                         ins->inst_p0 = s;
6122                         MONO_ADD_INS (cfg->cbb, ins);
6123                         return ins;
6124                 }
6125         }
6126
6127 #ifdef MONO_ARCH_SIMD_INTRINSICS
6128         if (cfg->opt & MONO_OPT_SIMD) {
6129                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6130                 if (ins)
6131                         return ins;
6132         }
6133 #endif
6134
6135         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6136         if (ins)
6137                 return ins;
6138
6139         if (COMPILE_LLVM (cfg)) {
6140                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6141                 if (ins)
6142                         return ins;
6143         }
6144
6145         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6146 }
6147
6148 /*
6149  * This entry point could be used later for arbitrary method
6150  * redirection.
6151  */
6152 inline static MonoInst*
6153 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6154                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6155 {
6156         if (method->klass == mono_defaults.string_class) {
6157                 /* managed string allocation support */
6158                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6159                         MonoInst *iargs [2];
6160                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6161                         MonoMethod *managed_alloc = NULL;
6162
6163                         g_assert (vtable); /*Should not fail since it System.String*/
6164 #ifndef MONO_CROSS_COMPILE
6165                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6166 #endif
6167                         if (!managed_alloc)
6168                                 return NULL;
6169                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6170                         iargs [1] = args [0];
6171                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6172                 }
6173         }
6174         return NULL;
6175 }
6176
6177 static void
6178 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6179 {
6180         MonoInst *store, *temp;
6181         int i;
6182
6183         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6184                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6185
6186                 /*
6187                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6188                  * would be different than the MonoInst's used to represent arguments, and
6189                  * the ldelema implementation can't deal with that.
6190                  * Solution: When ldelema is used on an inline argument, create a var for 
6191                  * it, emit ldelema on that var, and emit the saving code below in
6192                  * inline_method () if needed.
6193                  */
6194                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6195                 cfg->args [i] = temp;
6196                 /* This uses cfg->args [i] which is set by the preceeding line */
6197                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6198                 store->cil_code = sp [0]->cil_code;
6199                 sp++;
6200         }
6201 }
6202
6203 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6204 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6205
6206 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6207 static gboolean
6208 check_inline_called_method_name_limit (MonoMethod *called_method)
6209 {
6210         int strncmp_result;
6211         static const char *limit = NULL;
6212         
6213         if (limit == NULL) {
6214                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6215
6216                 if (limit_string != NULL)
6217                         limit = limit_string;
6218                 else
6219                         limit = "";
6220         }
6221
6222         if (limit [0] != '\0') {
6223                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6224
6225                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6226                 g_free (called_method_name);
6227         
6228                 //return (strncmp_result <= 0);
6229                 return (strncmp_result == 0);
6230         } else {
6231                 return TRUE;
6232         }
6233 }
6234 #endif
6235
6236 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6237 static gboolean
6238 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6239 {
6240         int strncmp_result;
6241         static const char *limit = NULL;
6242         
6243         if (limit == NULL) {
6244                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6245                 if (limit_string != NULL) {
6246                         limit = limit_string;
6247                 } else {
6248                         limit = "";
6249                 }
6250         }
6251
6252         if (limit [0] != '\0') {
6253                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6254
6255                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6256                 g_free (caller_method_name);
6257         
6258                 //return (strncmp_result <= 0);
6259                 return (strncmp_result == 0);
6260         } else {
6261                 return TRUE;
6262         }
6263 }
6264 #endif
6265
6266 static void
6267 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6268 {
6269         static double r8_0 = 0.0;
6270         static float r4_0 = 0.0;
6271         MonoInst *ins;
6272         int t;
6273
6274         rtype = mini_get_underlying_type (rtype);
6275         t = rtype->type;
6276
6277         if (rtype->byref) {
6278                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6279         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6280                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6281         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6282                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6283         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6284                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
6285                 ins->type = STACK_R4;
6286                 ins->inst_p0 = (void*)&r4_0;
6287                 ins->dreg = dreg;
6288                 MONO_ADD_INS (cfg->cbb, ins);
6289         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6290                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6291                 ins->type = STACK_R8;
6292                 ins->inst_p0 = (void*)&r8_0;
6293                 ins->dreg = dreg;
6294                 MONO_ADD_INS (cfg->cbb, ins);
6295         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6296                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6297                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6298         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6299                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6300         } else {
6301                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6302         }
6303 }
6304
6305 static void
6306 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6307 {
6308         int t;
6309
6310         rtype = mini_get_underlying_type (rtype);
6311         t = rtype->type;
6312
6313         if (rtype->byref) {
6314                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6315         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6316                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6317         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6318                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6319         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6320                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6321         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6322                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6323         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6324                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6325                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6326         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6327                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6328         } else {
6329                 emit_init_rvar (cfg, dreg, rtype);
6330         }
6331 }
6332
6333 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6334 static void
6335 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6336 {
6337         MonoInst *var = cfg->locals [local];
6338         if (COMPILE_SOFT_FLOAT (cfg)) {
6339                 MonoInst *store;
6340                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6341                 emit_init_rvar (cfg, reg, type);
6342                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6343         } else {
6344                 if (init)
6345                         emit_init_rvar (cfg, var->dreg, type);
6346                 else
6347                         emit_dummy_init_rvar (cfg, var->dreg, type);
6348         }
6349 }
6350
6351 int
6352 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6353 {
6354         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6355 }
6356
6357 /*
6358  * inline_method:
6359  *
6360  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6361  */
6362 static int
6363 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6364                guchar *ip, guint real_offset, gboolean inline_always)
6365 {
6366         MonoError error;
6367         MonoInst *ins, *rvar = NULL;
6368         MonoMethodHeader *cheader;
6369         MonoBasicBlock *ebblock, *sbblock;
6370         int i, costs;
6371         MonoMethod *prev_inlined_method;
6372         MonoInst **prev_locals, **prev_args;
6373         MonoType **prev_arg_types;
6374         guint prev_real_offset;
6375         GHashTable *prev_cbb_hash;
6376         MonoBasicBlock **prev_cil_offset_to_bb;
6377         MonoBasicBlock *prev_cbb;
6378         const unsigned char *prev_ip;
6379         unsigned char *prev_cil_start;
6380         guint32 prev_cil_offset_to_bb_len;
6381         MonoMethod *prev_current_method;
6382         MonoGenericContext *prev_generic_context;
6383         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6384
6385         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6386
6387 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6388         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6389                 return 0;
6390 #endif
6391 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6392         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6393                 return 0;
6394 #endif
6395
6396         if (!fsig)
6397                 fsig = mono_method_signature (cmethod);
6398
6399         if (cfg->verbose_level > 2)
6400                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6401
6402         if (!cmethod->inline_info) {
6403                 cfg->stat_inlineable_methods++;
6404                 cmethod->inline_info = 1;
6405         }
6406
6407         /* allocate local variables */
6408         cheader = mono_method_get_header_checked (cmethod, &error);
6409         if (!cheader) {
6410                 if (inline_always) {
6411                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6412                         mono_error_move (&cfg->error, &error);
6413                 } else {
6414                         mono_error_cleanup (&error);
6415                 }
6416                 return 0;
6417         }
6418
6419         /*Must verify before creating locals as it can cause the JIT to assert.*/
6420         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6421                 mono_metadata_free_mh (cheader);
6422                 return 0;
6423         }
6424
6425         /* allocate space to store the return value */
6426         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6427                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6428         }
6429
6430         prev_locals = cfg->locals;
6431         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6432         for (i = 0; i < cheader->num_locals; ++i)
6433                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6434
6435         /* allocate start and end blocks */
6436         /* This is needed so if the inline is aborted, we can clean up */
6437         NEW_BBLOCK (cfg, sbblock);
6438         sbblock->real_offset = real_offset;
6439
6440         NEW_BBLOCK (cfg, ebblock);
6441         ebblock->block_num = cfg->num_bblocks++;
6442         ebblock->real_offset = real_offset;
6443
6444         prev_args = cfg->args;
6445         prev_arg_types = cfg->arg_types;
6446         prev_inlined_method = cfg->inlined_method;
6447         cfg->inlined_method = cmethod;
6448         cfg->ret_var_set = FALSE;
6449         cfg->inline_depth ++;
6450         prev_real_offset = cfg->real_offset;
6451         prev_cbb_hash = cfg->cbb_hash;
6452         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6453         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6454         prev_cil_start = cfg->cil_start;
6455         prev_ip = cfg->ip;
6456         prev_cbb = cfg->cbb;
6457         prev_current_method = cfg->current_method;
6458         prev_generic_context = cfg->generic_context;
6459         prev_ret_var_set = cfg->ret_var_set;
6460         prev_disable_inline = cfg->disable_inline;
6461
6462         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6463                 virtual_ = TRUE;
6464
6465         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6466
6467         ret_var_set = cfg->ret_var_set;
6468
6469         cfg->inlined_method = prev_inlined_method;
6470         cfg->real_offset = prev_real_offset;
6471         cfg->cbb_hash = prev_cbb_hash;
6472         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6473         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6474         cfg->cil_start = prev_cil_start;
6475         cfg->ip = prev_ip;
6476         cfg->locals = prev_locals;
6477         cfg->args = prev_args;
6478         cfg->arg_types = prev_arg_types;
6479         cfg->current_method = prev_current_method;
6480         cfg->generic_context = prev_generic_context;
6481         cfg->ret_var_set = prev_ret_var_set;
6482         cfg->disable_inline = prev_disable_inline;
6483         cfg->inline_depth --;
6484
6485         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6486                 if (cfg->verbose_level > 2)
6487                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6488
6489                 cfg->stat_inlined_methods++;
6490
6491                 /* always add some code to avoid block split failures */
6492                 MONO_INST_NEW (cfg, ins, OP_NOP);
6493                 MONO_ADD_INS (prev_cbb, ins);
6494
6495                 prev_cbb->next_bb = sbblock;
6496                 link_bblock (cfg, prev_cbb, sbblock);
6497
6498                 /* 
6499                  * Get rid of the begin and end bblocks if possible to aid local
6500                  * optimizations.
6501                  */
6502                 if (prev_cbb->out_count == 1)
6503                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6504
6505                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6506                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6507
6508                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6509                         MonoBasicBlock *prev = ebblock->in_bb [0];
6510
6511                         if (prev->next_bb == ebblock) {
6512                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6513                                 cfg->cbb = prev;
6514                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6515                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6516                                         cfg->cbb = prev_cbb;
6517                                 }
6518                         } else {
6519                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6520                                 cfg->cbb = ebblock;
6521                         }
6522                 } else {
6523                         /* 
6524                          * Its possible that the rvar is set in some prev bblock, but not in others.
6525                          * (#1835).
6526                          */
6527                         if (rvar) {
6528                                 MonoBasicBlock *bb;
6529
6530                                 for (i = 0; i < ebblock->in_count; ++i) {
6531                                         bb = ebblock->in_bb [i];
6532
6533                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6534                                                 cfg->cbb = bb;
6535
6536                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6537                                         }
6538                                 }
6539                         }
6540
6541                         cfg->cbb = ebblock;
6542                 }
6543
6544                 if (rvar) {
6545                         /*
6546                          * If the inlined method contains only a throw, then the ret var is not 
6547                          * set, so set it to a dummy value.
6548                          */
6549                         if (!ret_var_set)
6550                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6551
6552                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6553                         *sp++ = ins;
6554                 }
6555                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6556                 return costs + 1;
6557         } else {
6558                 if (cfg->verbose_level > 2)
6559                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6560                 cfg->exception_type = MONO_EXCEPTION_NONE;
6561
6562                 /* This gets rid of the newly added bblocks */
6563                 cfg->cbb = prev_cbb;
6564         }
6565         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6566         return 0;
6567 }
6568
6569 /*
6570  * Some of these comments may well be out-of-date.
6571  * Design decisions: we do a single pass over the IL code (and we do bblock 
6572  * splitting/merging in the few cases when it's required: a back jump to an IL
6573  * address that was not already seen as bblock starting point).
6574  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6575  * Complex operations are decomposed in simpler ones right away. We need to let the 
6576  * arch-specific code peek and poke inside this process somehow (except when the 
6577  * optimizations can take advantage of the full semantic info of coarse opcodes).
6578  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6579  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6580  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6581  * opcode with value bigger than OP_LAST.
6582  * At this point the IR can be handed over to an interpreter, a dumb code generator
6583  * or to the optimizing code generator that will translate it to SSA form.
6584  *
6585  * Profiling directed optimizations.
6586  * We may compile by default with few or no optimizations and instrument the code
6587  * or the user may indicate what methods to optimize the most either in a config file
6588  * or through repeated runs where the compiler applies offline the optimizations to 
6589  * each method and then decides if it was worth it.
6590  */
6591
6592 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6593 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6594 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6595 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6596 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6597 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6598 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6599 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6600
6601 /* offset from br.s -> br like opcodes */
6602 #define BIG_BRANCH_OFFSET 13
6603
6604 static gboolean
6605 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6606 {
6607         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6608
6609         return b == NULL || b == bb;
6610 }
6611
6612 static int
6613 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6614 {
6615         unsigned char *ip = start;
6616         unsigned char *target;
6617         int i;
6618         guint cli_addr;
6619         MonoBasicBlock *bblock;
6620         const MonoOpcode *opcode;
6621
6622         while (ip < end) {
6623                 cli_addr = ip - start;
6624                 i = mono_opcode_value ((const guint8 **)&ip, end);
6625                 if (i < 0)
6626                         UNVERIFIED;
6627                 opcode = &mono_opcodes [i];
6628                 switch (opcode->argument) {
6629                 case MonoInlineNone:
6630                         ip++; 
6631                         break;
6632                 case MonoInlineString:
6633                 case MonoInlineType:
6634                 case MonoInlineField:
6635                 case MonoInlineMethod:
6636                 case MonoInlineTok:
6637                 case MonoInlineSig:
6638                 case MonoShortInlineR:
6639                 case MonoInlineI:
6640                         ip += 5;
6641                         break;
6642                 case MonoInlineVar:
6643                         ip += 3;
6644                         break;
6645                 case MonoShortInlineVar:
6646                 case MonoShortInlineI:
6647                         ip += 2;
6648                         break;
6649                 case MonoShortInlineBrTarget:
6650                         target = start + cli_addr + 2 + (signed char)ip [1];
6651                         GET_BBLOCK (cfg, bblock, target);
6652                         ip += 2;
6653                         if (ip < end)
6654                                 GET_BBLOCK (cfg, bblock, ip);
6655                         break;
6656                 case MonoInlineBrTarget:
6657                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6658                         GET_BBLOCK (cfg, bblock, target);
6659                         ip += 5;
6660                         if (ip < end)
6661                                 GET_BBLOCK (cfg, bblock, ip);
6662                         break;
6663                 case MonoInlineSwitch: {
6664                         guint32 n = read32 (ip + 1);
6665                         guint32 j;
6666                         ip += 5;
6667                         cli_addr += 5 + 4 * n;
6668                         target = start + cli_addr;
6669                         GET_BBLOCK (cfg, bblock, target);
6670                         
6671                         for (j = 0; j < n; ++j) {
6672                                 target = start + cli_addr + (gint32)read32 (ip);
6673                                 GET_BBLOCK (cfg, bblock, target);
6674                                 ip += 4;
6675                         }
6676                         break;
6677                 }
6678                 case MonoInlineR:
6679                 case MonoInlineI8:
6680                         ip += 9;
6681                         break;
6682                 default:
6683                         g_assert_not_reached ();
6684                 }
6685
6686                 if (i == CEE_THROW) {
6687                         unsigned char *bb_start = ip - 1;
6688                         
6689                         /* Find the start of the bblock containing the throw */
6690                         bblock = NULL;
6691                         while ((bb_start >= start) && !bblock) {
6692                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6693                                 bb_start --;
6694                         }
6695                         if (bblock)
6696                                 bblock->out_of_line = 1;
6697                 }
6698         }
6699         return 0;
6700 unverified:
6701 exception_exit:
6702         *pos = ip;
6703         return 1;
6704 }
6705
6706 static inline MonoMethod *
6707 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6708 {
6709         MonoMethod *method;
6710
6711         mono_error_init (error);
6712
6713         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6714                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6715                 if (context) {
6716                         method = mono_class_inflate_generic_method_checked (method, context, error);
6717                 }
6718         } else {
6719                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6720         }
6721
6722         return method;
6723 }
6724
6725 static inline MonoMethod *
6726 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6727 {
6728         MonoError error;
6729         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6730
6731         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6732                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6733                 method = NULL;
6734         }
6735
6736         if (!method && !cfg)
6737                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6738
6739         return method;
6740 }
6741
6742 static inline MonoClass*
6743 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6744 {
6745         MonoError error;
6746         MonoClass *klass;
6747
6748         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6749                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6750                 if (context) {
6751                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6752                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6753                 }
6754         } else {
6755                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6756                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6757         }
6758         if (klass)
6759                 mono_class_init (klass);
6760         return klass;
6761 }
6762
6763 static inline MonoMethodSignature*
6764 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6765 {
6766         MonoMethodSignature *fsig;
6767
6768         mono_error_init (error);
6769         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6770                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6771         } else {
6772                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6773                 return_val_if_nok (error, NULL);
6774         }
6775         if (context) {
6776                 fsig = mono_inflate_generic_signature(fsig, context, error);
6777         }
6778         return fsig;
6779 }
6780
6781 static MonoMethod*
6782 throw_exception (void)
6783 {
6784         static MonoMethod *method = NULL;
6785
6786         if (!method) {
6787                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6788                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6789         }
6790         g_assert (method);
6791         return method;
6792 }
6793
6794 static void
6795 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6796 {
6797         MonoMethod *thrower = throw_exception ();
6798         MonoInst *args [1];
6799
6800         EMIT_NEW_PCONST (cfg, args [0], ex);
6801         mono_emit_method_call (cfg, thrower, args, NULL);
6802 }
6803
6804 /*
6805  * Return the original method is a wrapper is specified. We can only access 
6806  * the custom attributes from the original method.
6807  */
6808 static MonoMethod*
6809 get_original_method (MonoMethod *method)
6810 {
6811         if (method->wrapper_type == MONO_WRAPPER_NONE)
6812                 return method;
6813
6814         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6815         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6816                 return NULL;
6817
6818         /* in other cases we need to find the original method */
6819         return mono_marshal_method_from_wrapper (method);
6820 }
6821
6822 static void
6823 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6824 {
6825         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6826         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6827         if (ex)
6828                 emit_throw_exception (cfg, ex);
6829 }
6830
6831 static void
6832 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6833 {
6834         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6835         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6836         if (ex)
6837                 emit_throw_exception (cfg, ex);
6838 }
6839
6840 /*
6841  * Check that the IL instructions at ip are the array initialization
6842  * sequence and return the pointer to the data and the size.
6843  */
6844 static const char*
6845 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6846 {
6847         /*
6848          * newarr[System.Int32]
6849          * dup
6850          * ldtoken field valuetype ...
6851          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6852          */
6853         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6854                 MonoError error;
6855                 guint32 token = read32 (ip + 7);
6856                 guint32 field_token = read32 (ip + 2);
6857                 guint32 field_index = field_token & 0xffffff;
6858                 guint32 rva;
6859                 const char *data_ptr;
6860                 int size = 0;
6861                 MonoMethod *cmethod;
6862                 MonoClass *dummy_class;
6863                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6864                 int dummy_align;
6865
6866                 if (!field) {
6867                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6868                         return NULL;
6869                 }
6870
6871                 *out_field_token = field_token;
6872
6873                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6874                 if (!cmethod)
6875                         return NULL;
6876                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6877                         return NULL;
6878                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
6879                 case MONO_TYPE_BOOLEAN:
6880                 case MONO_TYPE_I1:
6881                 case MONO_TYPE_U1:
6882                         size = 1; break;
6883                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6884 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6885                 case MONO_TYPE_CHAR:
6886                 case MONO_TYPE_I2:
6887                 case MONO_TYPE_U2:
6888                         size = 2; break;
6889                 case MONO_TYPE_I4:
6890                 case MONO_TYPE_U4:
6891                 case MONO_TYPE_R4:
6892                         size = 4; break;
6893                 case MONO_TYPE_R8:
6894                 case MONO_TYPE_I8:
6895                 case MONO_TYPE_U8:
6896                         size = 8; break;
6897 #endif
6898                 default:
6899                         return NULL;
6900                 }
6901                 size *= len;
6902                 if (size > mono_type_size (field->type, &dummy_align))
6903                     return NULL;
6904                 *out_size = size;
6905                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6906                 if (!image_is_dynamic (method->klass->image)) {
6907                         field_index = read32 (ip + 2) & 0xffffff;
6908                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6909                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6910                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6911                         /* for aot code we do the lookup on load */
6912                         if (aot && data_ptr)
6913                                 return (const char *)GUINT_TO_POINTER (rva);
6914                 } else {
6915                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6916                         g_assert (!aot);
6917                         data_ptr = mono_field_get_data (field);
6918                 }
6919                 return data_ptr;
6920         }
6921         return NULL;
6922 }
6923
6924 static void
6925 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6926 {
6927         MonoError error;
6928         char *method_fname = mono_method_full_name (method, TRUE);
6929         char *method_code;
6930         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6931
6932         if (!header) {
6933                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6934                 mono_error_cleanup (&error);
6935         } else if (header->code_size == 0)
6936                 method_code = g_strdup ("method body is empty.");
6937         else
6938                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6939         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6940         g_free (method_fname);
6941         g_free (method_code);
6942         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6943 }
6944
6945 static void
6946 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6947 {
6948         MonoInst *ins;
6949         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6950         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6951                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6952                 /* Optimize reg-reg moves away */
6953                 /* 
6954                  * Can't optimize other opcodes, since sp[0] might point to
6955                  * the last ins of a decomposed opcode.
6956                  */
6957                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6958         } else {
6959                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6960         }
6961 }
6962
6963 /*
6964  * ldloca inhibits many optimizations so try to get rid of it in common
6965  * cases.
6966  */
6967 static inline unsigned char *
6968 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6969 {
6970         int local, token;
6971         MonoClass *klass;
6972         MonoType *type;
6973
6974         if (size == 1) {
6975                 local = ip [1];
6976                 ip += 2;
6977         } else {
6978                 local = read16 (ip + 2);
6979                 ip += 4;
6980         }
6981         
6982         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6983                 /* From the INITOBJ case */
6984                 token = read32 (ip + 2);
6985                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6986                 CHECK_TYPELOAD (klass);
6987                 type = mini_get_underlying_type (&klass->byval_arg);
6988                 emit_init_local (cfg, local, type, TRUE);
6989                 return ip + 6;
6990         }
6991  exception_exit:
6992         return NULL;
6993 }
6994
6995 static MonoInst*
6996 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6997 {
6998         MonoInst *icall_args [16];
6999         MonoInst *call_target, *ins, *vtable_ins;
7000         int arg_reg, this_reg, vtable_reg;
7001         gboolean is_iface = mono_class_is_interface (cmethod->klass);
7002         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
7003         gboolean variant_iface = FALSE;
7004         guint32 slot;
7005         int offset;
7006         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
7007
7008         /*
7009          * In llvm-only mode, vtables contain function descriptors instead of
7010          * method addresses/trampolines.
7011          */
7012         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
7013
7014         if (is_iface)
7015                 slot = mono_method_get_imt_slot (cmethod);
7016         else
7017                 slot = mono_method_get_vtable_index (cmethod);
7018
7019         this_reg = sp [0]->dreg;
7020
7021         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
7022                 variant_iface = TRUE;
7023
7024         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
7025                 /*
7026                  * The simplest case, a normal virtual call.
7027                  */
7028                 int slot_reg = alloc_preg (cfg);
7029                 int addr_reg = alloc_preg (cfg);
7030                 int arg_reg = alloc_preg (cfg);
7031                 MonoBasicBlock *non_null_bb;
7032
7033                 vtable_reg = alloc_preg (cfg);
7034                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7035                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7036
7037                 /* Load the vtable slot, which contains a function descriptor. */
7038                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7039
7040                 NEW_BBLOCK (cfg, non_null_bb);
7041
7042                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7043                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
7044                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
7045
7046                 /* Slow path */
7047                 // FIXME: Make the wrapper use the preserveall cconv
7048                 // FIXME: Use one icall per slot for small slot numbers ?
7049                 icall_args [0] = vtable_ins;
7050                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7051                 /* Make the icall return the vtable slot value to save some code space */
7052                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
7053                 ins->dreg = slot_reg;
7054                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
7055
7056                 /* Fastpath */
7057                 MONO_START_BB (cfg, non_null_bb);
7058                 /* Load the address + arg from the vtable slot */
7059                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7060                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
7061
7062                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7063         }
7064
7065         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
7066                 /*
7067                  * A simple interface call
7068                  *
7069                  * We make a call through an imt slot to obtain the function descriptor we need to call.
7070                  * The imt slot contains a function descriptor for a runtime function + arg.
7071                  */
7072                 int slot_reg = alloc_preg (cfg);
7073                 int addr_reg = alloc_preg (cfg);
7074                 int arg_reg = alloc_preg (cfg);
7075                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7076
7077                 vtable_reg = alloc_preg (cfg);
7078                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7079                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7080
7081                 /*
7082                  * The slot is already initialized when the vtable is created so there is no need
7083                  * to check it here.
7084                  */
7085
7086                 /* Load the imt slot, which contains a function descriptor. */
7087                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7088
7089                 /* Load the address + arg of the imt thunk from the imt slot */
7090                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7091                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7092                 /*
7093                  * IMT thunks in llvm-only mode are C functions which take an info argument
7094                  * plus the imt method and return the ftndesc to call.
7095                  */
7096                 icall_args [0] = thunk_arg_ins;
7097                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7098                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7099                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7100
7101                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7102         }
7103
7104         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
7105                 /*
7106                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7107                  * dynamically extended as more instantiations are discovered.
7108                  * This handles generic virtual methods both on classes and interfaces.
7109                  */
7110                 int slot_reg = alloc_preg (cfg);
7111                 int addr_reg = alloc_preg (cfg);
7112                 int arg_reg = alloc_preg (cfg);
7113                 int ftndesc_reg = alloc_preg (cfg);
7114                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7115                 MonoBasicBlock *slowpath_bb, *end_bb;
7116
7117                 NEW_BBLOCK (cfg, slowpath_bb);
7118                 NEW_BBLOCK (cfg, end_bb);
7119
7120                 vtable_reg = alloc_preg (cfg);
7121                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7122                 if (is_iface)
7123                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7124                 else
7125                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7126
7127                 /* Load the slot, which contains a function descriptor. */
7128                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7129
7130                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7131                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7132                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7133                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7134
7135                 /* Fastpath */
7136                 /* Same as with iface calls */
7137                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7138                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7139                 icall_args [0] = thunk_arg_ins;
7140                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7141                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7142                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7143                 ftndesc_ins->dreg = ftndesc_reg;
7144                 /*
7145                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7146                  * they don't know about yet. Fall back to the slowpath in that case.
7147                  */
7148                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7149                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7150
7151                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7152
7153                 /* Slowpath */
7154                 MONO_START_BB (cfg, slowpath_bb);
7155                 icall_args [0] = vtable_ins;
7156                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7157                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7158                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7159                 if (is_iface)
7160                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7161                 else
7162                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7163                 ftndesc_ins->dreg = ftndesc_reg;
7164                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7165
7166                 /* Common case */
7167                 MONO_START_BB (cfg, end_bb);
7168                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7169         }
7170
7171         /*
7172          * Non-optimized cases
7173          */
7174         icall_args [0] = sp [0];
7175         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7176
7177         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7178                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7179
7180         arg_reg = alloc_preg (cfg);
7181         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7182         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7183
7184         g_assert (is_gsharedvt);
7185         if (is_iface)
7186                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7187         else
7188                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7189
7190         /*
7191          * Pass the extra argument even if the callee doesn't receive it, most
7192          * calling conventions allow this.
7193          */
7194         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7195 }
7196
7197 static gboolean
7198 is_exception_class (MonoClass *klass)
7199 {
7200         while (klass) {
7201                 if (klass == mono_defaults.exception_class)
7202                         return TRUE;
7203                 klass = klass->parent;
7204         }
7205         return FALSE;
7206 }
7207
7208 /*
7209  * is_jit_optimizer_disabled:
7210  *
7211  *   Determine whenever M's assembly has a DebuggableAttribute with the
7212  * IsJITOptimizerDisabled flag set.
7213  */
7214 static gboolean
7215 is_jit_optimizer_disabled (MonoMethod *m)
7216 {
7217         MonoError error;
7218         MonoAssembly *ass = m->klass->image->assembly;
7219         MonoCustomAttrInfo* attrs;
7220         MonoClass *klass;
7221         int i;
7222         gboolean val = FALSE;
7223
7224         g_assert (ass);
7225         if (ass->jit_optimizer_disabled_inited)
7226                 return ass->jit_optimizer_disabled;
7227
7228         klass = mono_class_try_get_debuggable_attribute_class ();
7229
7230         if (!klass) {
7231                 /* Linked away */
7232                 ass->jit_optimizer_disabled = FALSE;
7233                 mono_memory_barrier ();
7234                 ass->jit_optimizer_disabled_inited = TRUE;
7235                 return FALSE;
7236         }
7237
7238         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
7239         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7240         if (attrs) {
7241                 for (i = 0; i < attrs->num_attrs; ++i) {
7242                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7243                         const gchar *p;
7244                         MonoMethodSignature *sig;
7245
7246                         if (!attr->ctor || attr->ctor->klass != klass)
7247                                 continue;
7248                         /* Decode the attribute. See reflection.c */
7249                         p = (const char*)attr->data;
7250                         g_assert (read16 (p) == 0x0001);
7251                         p += 2;
7252
7253                         // FIXME: Support named parameters
7254                         sig = mono_method_signature (attr->ctor);
7255                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7256                                 continue;
7257                         /* Two boolean arguments */
7258                         p ++;
7259                         val = *p;
7260                 }
7261                 mono_custom_attrs_free (attrs);
7262         }
7263
7264         ass->jit_optimizer_disabled = val;
7265         mono_memory_barrier ();
7266         ass->jit_optimizer_disabled_inited = TRUE;
7267
7268         return val;
7269 }
7270
7271 static gboolean
7272 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7273 {
7274         gboolean supported_tail_call;
7275         int i;
7276
7277         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7278
7279         for (i = 0; i < fsig->param_count; ++i) {
7280                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7281                         /* These can point to the current method's stack */
7282                         supported_tail_call = FALSE;
7283         }
7284         if (fsig->hasthis && cmethod->klass->valuetype)
7285                 /* this might point to the current method's stack */
7286                 supported_tail_call = FALSE;
7287         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7288                 supported_tail_call = FALSE;
7289         if (cfg->method->save_lmf)
7290                 supported_tail_call = FALSE;
7291         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7292                 supported_tail_call = FALSE;
7293         if (call_opcode != CEE_CALL)
7294                 supported_tail_call = FALSE;
7295
7296         /* Debugging support */
7297 #if 0
7298         if (supported_tail_call) {
7299                 if (!mono_debug_count ())
7300                         supported_tail_call = FALSE;
7301         }
7302 #endif
7303
7304         return supported_tail_call;
7305 }
7306
7307 /*
7308  * handle_ctor_call:
7309  *
7310  *   Handle calls made to ctors from NEWOBJ opcodes.
7311  */
7312 static void
7313 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7314                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7315 {
7316         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7317
7318         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7319                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7320                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7321                         mono_class_vtable (cfg->domain, cmethod->klass);
7322                         CHECK_TYPELOAD (cmethod->klass);
7323
7324                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7325                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7326                 } else {
7327                         if (context_used) {
7328                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7329                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7330                         } else {
7331                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7332
7333                                 CHECK_TYPELOAD (cmethod->klass);
7334                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7335                         }
7336                 }
7337         }
7338
7339         /* Avoid virtual calls to ctors if possible */
7340         if (mono_class_is_marshalbyref (cmethod->klass))
7341                 callvirt_this_arg = sp [0];
7342
7343         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7344                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7345                 CHECK_CFG_EXCEPTION;
7346         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7347                            mono_method_check_inlining (cfg, cmethod) &&
7348                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7349                 int costs;
7350
7351                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7352                         cfg->real_offset += 5;
7353
7354                         *inline_costs += costs - 5;
7355                 } else {
7356                         INLINE_FAILURE ("inline failure");
7357                         // FIXME-VT: Clean this up
7358                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7359                                 GSHAREDVT_FAILURE(*ip);
7360                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7361                 }
7362         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7363                 MonoInst *addr;
7364
7365                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7366
7367                 if (cfg->llvm_only) {
7368                         // FIXME: Avoid initializing vtable_arg
7369                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7370                 } else {
7371                         mono_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7372                 }
7373         } else if (context_used &&
7374                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7375                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7376                 MonoInst *cmethod_addr;
7377
7378                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7379
7380                 if (cfg->llvm_only) {
7381                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7382                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7383                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7384                 } else {
7385                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7386                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7387
7388                         mono_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7389                 }
7390         } else {
7391                 INLINE_FAILURE ("ctor call");
7392                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7393                                                                                   callvirt_this_arg, NULL, vtable_arg);
7394         }
7395  exception_exit:
7396         return;
7397 }
7398
7399 static void
7400 emit_setret (MonoCompile *cfg, MonoInst *val)
7401 {
7402         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7403         MonoInst *ins;
7404
7405         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7406                 MonoInst *ret_addr;
7407
7408                 if (!cfg->vret_addr) {
7409                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7410                 } else {
7411                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7412
7413                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7414                         ins->klass = mono_class_from_mono_type (ret_type);
7415                 }
7416         } else {
7417 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7418                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7419                         MonoInst *iargs [1];
7420                         MonoInst *conv;
7421
7422                         iargs [0] = val;
7423                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7424                         mono_arch_emit_setret (cfg, cfg->method, conv);
7425                 } else {
7426                         mono_arch_emit_setret (cfg, cfg->method, val);
7427                 }
7428 #else
7429                 mono_arch_emit_setret (cfg, cfg->method, val);
7430 #endif
7431         }
7432 }
7433
7434 /*
7435  * mono_method_to_ir:
7436  *
7437  * Translate the .net IL into linear IR.
7438  *
7439  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7440  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7441  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7442  * @inline_args: if not NULL, contains the arguments to the inline call
7443  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7444  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7445  *
7446  * This method is used to turn ECMA IL into Mono's internal Linear IR
7447  * reprensetation.  It is used both for entire methods, as well as
7448  * inlining existing methods.  In the former case, the @start_bblock,
7449  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7450  * inline_offset is set to zero.
7451  * 
7452  * Returns: the inline cost, or -1 if there was an error processing this method.
7453  */
7454 int
7455 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7456                    MonoInst *return_var, MonoInst **inline_args, 
7457                    guint inline_offset, gboolean is_virtual_call)
7458 {
7459         MonoError error;
7460         MonoInst *ins, **sp, **stack_start;
7461         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7462         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7463         MonoMethod *cmethod, *method_definition;
7464         MonoInst **arg_array;
7465         MonoMethodHeader *header;
7466         MonoImage *image;
7467         guint32 token, ins_flag;
7468         MonoClass *klass;
7469         MonoClass *constrained_class = NULL;
7470         unsigned char *ip, *end, *target, *err_pos;
7471         MonoMethodSignature *sig;
7472         MonoGenericContext *generic_context = NULL;
7473         MonoGenericContainer *generic_container = NULL;
7474         MonoType **param_types;
7475         int i, n, start_new_bblock, dreg;
7476         int num_calls = 0, inline_costs = 0;
7477         int breakpoint_id = 0;
7478         guint num_args;
7479         GSList *class_inits = NULL;
7480         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7481         int context_used;
7482         gboolean init_locals, seq_points, skip_dead_blocks;
7483         gboolean sym_seq_points = FALSE;
7484         MonoDebugMethodInfo *minfo;
7485         MonoBitSet *seq_point_locs = NULL;
7486         MonoBitSet *seq_point_set_locs = NULL;
7487
7488         cfg->disable_inline = is_jit_optimizer_disabled (method);
7489
7490         /* serialization and xdomain stuff may need access to private fields and methods */
7491         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7492         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7493         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7494         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7495         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7496         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7497
7498         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7499         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7500         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7501         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7502         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7503
7504         image = method->klass->image;
7505         header = mono_method_get_header_checked (method, &cfg->error);
7506         if (!header) {
7507                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7508                 goto exception_exit;
7509         } else {
7510                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7511         }
7512
7513         generic_container = mono_method_get_generic_container (method);
7514         sig = mono_method_signature (method);
7515         num_args = sig->hasthis + sig->param_count;
7516         ip = (unsigned char*)header->code;
7517         cfg->cil_start = ip;
7518         end = ip + header->code_size;
7519         cfg->stat_cil_code_size += header->code_size;
7520
7521         seq_points = cfg->gen_seq_points && cfg->method == method;
7522
7523         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7524                 /* We could hit a seq point before attaching to the JIT (#8338) */
7525                 seq_points = FALSE;
7526         }
7527
7528         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7529                 minfo = mono_debug_lookup_method (method);
7530                 if (minfo) {
7531                         MonoSymSeqPoint *sps;
7532                         int i, n_il_offsets;
7533
7534                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7535                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7536                         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);
7537                         sym_seq_points = TRUE;
7538                         for (i = 0; i < n_il_offsets; ++i) {
7539                                 if (sps [i].il_offset < header->code_size)
7540                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7541                         }
7542                         g_free (sps);
7543
7544                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7545                         if (asyncMethod) {
7546                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7547                                 {
7548                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7549                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7550                                 }
7551                                 mono_debug_free_method_async_debug_info (asyncMethod);
7552                         }
7553                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7554                         /* Methods without line number info like auto-generated property accessors */
7555                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7556                         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);
7557                         sym_seq_points = TRUE;
7558                 }
7559         }
7560
7561         /* 
7562          * Methods without init_locals set could cause asserts in various passes
7563          * (#497220). To work around this, we emit dummy initialization opcodes
7564          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7565          * on some platforms.
7566          */
7567         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7568                 init_locals = header->init_locals;
7569         else
7570                 init_locals = TRUE;
7571
7572         method_definition = method;
7573         while (method_definition->is_inflated) {
7574                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7575                 method_definition = imethod->declaring;
7576         }
7577
7578         /* SkipVerification is not allowed if core-clr is enabled */
7579         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7580                 dont_verify = TRUE;
7581                 dont_verify_stloc = TRUE;
7582         }
7583
7584         if (sig->is_inflated)
7585                 generic_context = mono_method_get_context (method);
7586         else if (generic_container)
7587                 generic_context = &generic_container->context;
7588         cfg->generic_context = generic_context;
7589
7590         if (!cfg->gshared)
7591                 g_assert (!sig->has_type_parameters);
7592
7593         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7594                 g_assert (method->is_inflated);
7595                 g_assert (mono_method_get_context (method)->method_inst);
7596         }
7597         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7598                 g_assert (sig->generic_param_count);
7599
7600         if (cfg->method == method) {
7601                 cfg->real_offset = 0;
7602         } else {
7603                 cfg->real_offset = inline_offset;
7604         }
7605
7606         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7607         cfg->cil_offset_to_bb_len = header->code_size;
7608
7609         cfg->current_method = method;
7610
7611         if (cfg->verbose_level > 2)
7612                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7613
7614         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7615         if (sig->hasthis)
7616                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7617         for (n = 0; n < sig->param_count; ++n)
7618                 param_types [n + sig->hasthis] = sig->params [n];
7619         cfg->arg_types = param_types;
7620
7621         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7622         if (cfg->method == method) {
7623
7624                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7625                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7626
7627                 /* ENTRY BLOCK */
7628                 NEW_BBLOCK (cfg, start_bblock);
7629                 cfg->bb_entry = start_bblock;
7630                 start_bblock->cil_code = NULL;
7631                 start_bblock->cil_length = 0;
7632
7633                 /* EXIT BLOCK */
7634                 NEW_BBLOCK (cfg, end_bblock);
7635                 cfg->bb_exit = end_bblock;
7636                 end_bblock->cil_code = NULL;
7637                 end_bblock->cil_length = 0;
7638                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7639                 g_assert (cfg->num_bblocks == 2);
7640
7641                 arg_array = cfg->args;
7642
7643                 if (header->num_clauses) {
7644                         cfg->spvars = g_hash_table_new (NULL, NULL);
7645                         cfg->exvars = g_hash_table_new (NULL, NULL);
7646                 }
7647                 /* handle exception clauses */
7648                 for (i = 0; i < header->num_clauses; ++i) {
7649                         MonoBasicBlock *try_bb;
7650                         MonoExceptionClause *clause = &header->clauses [i];
7651                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7652
7653                         try_bb->real_offset = clause->try_offset;
7654                         try_bb->try_start = TRUE;
7655                         try_bb->region = ((i + 1) << 8) | clause->flags;
7656                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7657                         tblock->real_offset = clause->handler_offset;
7658                         tblock->flags |= BB_EXCEPTION_HANDLER;
7659
7660                         /*
7661                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7662                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7663                          */
7664                         if (COMPILE_LLVM (cfg))
7665                                 link_bblock (cfg, try_bb, tblock);
7666
7667                         if (*(ip + clause->handler_offset) == CEE_POP)
7668                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7669
7670                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7671                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7672                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7673                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7674                                 MONO_ADD_INS (tblock, ins);
7675
7676                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7677                                         /* finally clauses already have a seq point */
7678                                         /* seq points for filter clauses are emitted below */
7679                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7680                                         MONO_ADD_INS (tblock, ins);
7681                                 }
7682
7683                                 /* todo: is a fault block unsafe to optimize? */
7684                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7685                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7686                         }
7687
7688                         /*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);
7689                           while (p < end) {
7690                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7691                           }*/
7692                         /* catch and filter blocks get the exception object on the stack */
7693                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7694                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7695
7696                                 /* mostly like handle_stack_args (), but just sets the input args */
7697                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7698                                 tblock->in_scount = 1;
7699                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7700                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7701
7702                                 cfg->cbb = tblock;
7703
7704 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7705                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7706                                 if (!cfg->compile_llvm) {
7707                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7708                                         ins->dreg = tblock->in_stack [0]->dreg;
7709                                         MONO_ADD_INS (tblock, ins);
7710                                 }
7711 #else
7712                                 MonoInst *dummy_use;
7713
7714                                 /* 
7715                                  * Add a dummy use for the exvar so its liveness info will be
7716                                  * correct.
7717                                  */
7718                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7719 #endif
7720
7721                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7722                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7723                                         MONO_ADD_INS (tblock, ins);
7724                                 }
7725                                 
7726                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7727                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7728                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7729                                         tblock->real_offset = clause->data.filter_offset;
7730                                         tblock->in_scount = 1;
7731                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7732                                         /* The filter block shares the exvar with the handler block */
7733                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7734                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7735                                         MONO_ADD_INS (tblock, ins);
7736                                 }
7737                         }
7738
7739                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7740                                         clause->data.catch_class &&
7741                                         cfg->gshared &&
7742                                         mono_class_check_context_used (clause->data.catch_class)) {
7743                                 /*
7744                                  * In shared generic code with catch
7745                                  * clauses containing type variables
7746                                  * the exception handling code has to
7747                                  * be able to get to the rgctx.
7748                                  * Therefore we have to make sure that
7749                                  * the vtable/mrgctx argument (for
7750                                  * static or generic methods) or the
7751                                  * "this" argument (for non-static
7752                                  * methods) are live.
7753                                  */
7754                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7755                                                 mini_method_get_context (method)->method_inst ||
7756                                                 method->klass->valuetype) {
7757                                         mono_get_vtable_var (cfg);
7758                                 } else {
7759                                         MonoInst *dummy_use;
7760
7761                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7762                                 }
7763                         }
7764                 }
7765         } else {
7766                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7767                 cfg->cbb = start_bblock;
7768                 cfg->args = arg_array;
7769                 mono_save_args (cfg, sig, inline_args);
7770         }
7771
7772         /* FIRST CODE BLOCK */
7773         NEW_BBLOCK (cfg, tblock);
7774         tblock->cil_code = ip;
7775         cfg->cbb = tblock;
7776         cfg->ip = ip;
7777
7778         ADD_BBLOCK (cfg, tblock);
7779
7780         if (cfg->method == method) {
7781                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7782                 if (breakpoint_id) {
7783                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7784                         MONO_ADD_INS (cfg->cbb, ins);
7785                 }
7786         }
7787
7788         /* we use a separate basic block for the initialization code */
7789         NEW_BBLOCK (cfg, init_localsbb);
7790         if (cfg->method == method)
7791                 cfg->bb_init = init_localsbb;
7792         init_localsbb->real_offset = cfg->real_offset;
7793         start_bblock->next_bb = init_localsbb;
7794         init_localsbb->next_bb = cfg->cbb;
7795         link_bblock (cfg, start_bblock, init_localsbb);
7796         link_bblock (cfg, init_localsbb, cfg->cbb);
7797                 
7798         cfg->cbb = init_localsbb;
7799
7800         if (cfg->gsharedvt && cfg->method == method) {
7801                 MonoGSharedVtMethodInfo *info;
7802                 MonoInst *var, *locals_var;
7803                 int dreg;
7804
7805                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7806                 info->method = cfg->method;
7807                 info->count_entries = 16;
7808                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7809                 cfg->gsharedvt_info = info;
7810
7811                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7812                 /* prevent it from being register allocated */
7813                 //var->flags |= MONO_INST_VOLATILE;
7814                 cfg->gsharedvt_info_var = var;
7815
7816                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7817                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7818
7819                 /* Allocate locals */
7820                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7821                 /* prevent it from being register allocated */
7822                 //locals_var->flags |= MONO_INST_VOLATILE;
7823                 cfg->gsharedvt_locals_var = locals_var;
7824
7825                 dreg = alloc_ireg (cfg);
7826                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7827
7828                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7829                 ins->dreg = locals_var->dreg;
7830                 ins->sreg1 = dreg;
7831                 MONO_ADD_INS (cfg->cbb, ins);
7832                 cfg->gsharedvt_locals_var_ins = ins;
7833                 
7834                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7835                 /*
7836                 if (init_locals)
7837                         ins->flags |= MONO_INST_INIT;
7838                 */
7839         }
7840
7841         if (mono_security_core_clr_enabled ()) {
7842                 /* check if this is native code, e.g. an icall or a p/invoke */
7843                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7844                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7845                         if (wrapped) {
7846                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7847                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7848
7849                                 /* if this ia a native call then it can only be JITted from platform code */
7850                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7851                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7852                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7853                                                         mono_get_exception_method_access ();
7854                                                 emit_throw_exception (cfg, ex);
7855                                         }
7856                                 }
7857                         }
7858                 }
7859         }
7860
7861         CHECK_CFG_EXCEPTION;
7862
7863         if (header->code_size == 0)
7864                 UNVERIFIED;
7865
7866         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7867                 ip = err_pos;
7868                 UNVERIFIED;
7869         }
7870
7871         if (cfg->method == method)
7872                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7873
7874         for (n = 0; n < header->num_locals; ++n) {
7875                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7876                         UNVERIFIED;
7877         }
7878         class_inits = NULL;
7879
7880         /* We force the vtable variable here for all shared methods
7881            for the possibility that they might show up in a stack
7882            trace where their exact instantiation is needed. */
7883         if (cfg->gshared && method == cfg->method) {
7884                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7885                                 mini_method_get_context (method)->method_inst ||
7886                                 method->klass->valuetype) {
7887                         mono_get_vtable_var (cfg);
7888                 } else {
7889                         /* FIXME: Is there a better way to do this?
7890                            We need the variable live for the duration
7891                            of the whole method. */
7892                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7893                 }
7894         }
7895
7896         /* add a check for this != NULL to inlined methods */
7897         if (is_virtual_call) {
7898                 MonoInst *arg_ins;
7899
7900                 NEW_ARGLOAD (cfg, arg_ins, 0);
7901                 MONO_ADD_INS (cfg->cbb, arg_ins);
7902                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7903         }
7904
7905         skip_dead_blocks = !dont_verify;
7906         if (skip_dead_blocks) {
7907                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7908                 CHECK_CFG_ERROR;
7909                 g_assert (bb);
7910         }
7911
7912         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7913         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7914
7915         ins_flag = 0;
7916         start_new_bblock = 0;
7917         while (ip < end) {
7918                 if (cfg->method == method)
7919                         cfg->real_offset = ip - header->code;
7920                 else
7921                         cfg->real_offset = inline_offset;
7922                 cfg->ip = ip;
7923
7924                 context_used = 0;
7925
7926                 if (start_new_bblock) {
7927                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7928                         if (start_new_bblock == 2) {
7929                                 g_assert (ip == tblock->cil_code);
7930                         } else {
7931                                 GET_BBLOCK (cfg, tblock, ip);
7932                         }
7933                         cfg->cbb->next_bb = tblock;
7934                         cfg->cbb = tblock;
7935                         start_new_bblock = 0;
7936                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7937                                 if (cfg->verbose_level > 3)
7938                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7939                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7940                                 *sp++ = ins;
7941                         }
7942                         if (class_inits)
7943                                 g_slist_free (class_inits);
7944                         class_inits = NULL;
7945                 } else {
7946                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7947                                 link_bblock (cfg, cfg->cbb, tblock);
7948                                 if (sp != stack_start) {
7949                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7950                                         sp = stack_start;
7951                                         CHECK_UNVERIFIABLE (cfg);
7952                                 }
7953                                 cfg->cbb->next_bb = tblock;
7954                                 cfg->cbb = tblock;
7955                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7956                                         if (cfg->verbose_level > 3)
7957                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7958                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7959                                         *sp++ = ins;
7960                                 }
7961                                 g_slist_free (class_inits);
7962                                 class_inits = NULL;
7963                         }
7964                 }
7965
7966                 if (skip_dead_blocks) {
7967                         int ip_offset = ip - header->code;
7968
7969                         if (ip_offset == bb->end)
7970                                 bb = bb->next;
7971
7972                         if (bb->dead) {
7973                                 int op_size = mono_opcode_size (ip, end);
7974                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7975
7976                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7977
7978                                 if (ip_offset + op_size == bb->end) {
7979                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7980                                         MONO_ADD_INS (cfg->cbb, ins);
7981                                         start_new_bblock = 1;
7982                                 }
7983
7984                                 ip += op_size;
7985                                 continue;
7986                         }
7987                 }
7988                 /*
7989                  * Sequence points are points where the debugger can place a breakpoint.
7990                  * Currently, we generate these automatically at points where the IL
7991                  * stack is empty.
7992                  */
7993                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7994                         /*
7995                          * Make methods interruptable at the beginning, and at the targets of
7996                          * backward branches.
7997                          * Also, do this at the start of every bblock in methods with clauses too,
7998                          * to be able to handle instructions with inprecise control flow like
7999                          * throw/endfinally.
8000                          * Backward branches are handled at the end of method-to-ir ().
8001                          */
8002                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
8003                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
8004
8005                         /* Avoid sequence points on empty IL like .volatile */
8006                         // FIXME: Enable this
8007                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
8008                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
8009                         if ((sp != stack_start) && !sym_seq_point)
8010                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
8011                         MONO_ADD_INS (cfg->cbb, ins);
8012
8013                         if (sym_seq_points)
8014                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
8015                 }
8016
8017                 cfg->cbb->real_offset = cfg->real_offset;
8018
8019                 if ((cfg->method == method) && cfg->coverage_info) {
8020                         guint32 cil_offset = ip - header->code;
8021                         cfg->coverage_info->data [cil_offset].cil_code = ip;
8022
8023                         /* TODO: Use an increment here */
8024 #if defined(TARGET_X86)
8025                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
8026                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
8027                         ins->inst_imm = 1;
8028                         MONO_ADD_INS (cfg->cbb, ins);
8029 #else
8030                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
8031                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
8032 #endif
8033                 }
8034
8035                 if (cfg->verbose_level > 3)
8036                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8037
8038                 switch (*ip) {
8039                 case CEE_NOP:
8040                         if (seq_points && !sym_seq_points && sp != stack_start) {
8041                                 /*
8042                                  * The C# compiler uses these nops to notify the JIT that it should
8043                                  * insert seq points.
8044                                  */
8045                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
8046                                 MONO_ADD_INS (cfg->cbb, ins);
8047                         }
8048                         if (cfg->keep_cil_nops)
8049                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
8050                         else
8051                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8052                         ip++;
8053                         MONO_ADD_INS (cfg->cbb, ins);
8054                         break;
8055                 case CEE_BREAK:
8056                         if (should_insert_brekpoint (cfg->method)) {
8057                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
8058                         } else {
8059                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8060                         }
8061                         ip++;
8062                         MONO_ADD_INS (cfg->cbb, ins);
8063                         break;
8064                 case CEE_LDARG_0:
8065                 case CEE_LDARG_1:
8066                 case CEE_LDARG_2:
8067                 case CEE_LDARG_3:
8068                         CHECK_STACK_OVF (1);
8069                         n = (*ip)-CEE_LDARG_0;
8070                         CHECK_ARG (n);
8071                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8072                         ip++;
8073                         *sp++ = ins;
8074                         break;
8075                 case CEE_LDLOC_0:
8076                 case CEE_LDLOC_1:
8077                 case CEE_LDLOC_2:
8078                 case CEE_LDLOC_3:
8079                         CHECK_STACK_OVF (1);
8080                         n = (*ip)-CEE_LDLOC_0;
8081                         CHECK_LOCAL (n);
8082                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8083                         ip++;
8084                         *sp++ = ins;
8085                         break;
8086                 case CEE_STLOC_0:
8087                 case CEE_STLOC_1:
8088                 case CEE_STLOC_2:
8089                 case CEE_STLOC_3: {
8090                         CHECK_STACK (1);
8091                         n = (*ip)-CEE_STLOC_0;
8092                         CHECK_LOCAL (n);
8093                         --sp;
8094                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8095                                 UNVERIFIED;
8096                         emit_stloc_ir (cfg, sp, header, n);
8097                         ++ip;
8098                         inline_costs += 1;
8099                         break;
8100                         }
8101                 case CEE_LDARG_S:
8102                         CHECK_OPSIZE (2);
8103                         CHECK_STACK_OVF (1);
8104                         n = ip [1];
8105                         CHECK_ARG (n);
8106                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8107                         *sp++ = ins;
8108                         ip += 2;
8109                         break;
8110                 case CEE_LDARGA_S:
8111                         CHECK_OPSIZE (2);
8112                         CHECK_STACK_OVF (1);
8113                         n = ip [1];
8114                         CHECK_ARG (n);
8115                         NEW_ARGLOADA (cfg, ins, n);
8116                         MONO_ADD_INS (cfg->cbb, ins);
8117                         *sp++ = ins;
8118                         ip += 2;
8119                         break;
8120                 case CEE_STARG_S:
8121                         CHECK_OPSIZE (2);
8122                         CHECK_STACK (1);
8123                         --sp;
8124                         n = ip [1];
8125                         CHECK_ARG (n);
8126                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8127                                 UNVERIFIED;
8128                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8129                         ip += 2;
8130                         break;
8131                 case CEE_LDLOC_S:
8132                         CHECK_OPSIZE (2);
8133                         CHECK_STACK_OVF (1);
8134                         n = ip [1];
8135                         CHECK_LOCAL (n);
8136                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8137                         *sp++ = ins;
8138                         ip += 2;
8139                         break;
8140                 case CEE_LDLOCA_S: {
8141                         unsigned char *tmp_ip;
8142                         CHECK_OPSIZE (2);
8143                         CHECK_STACK_OVF (1);
8144                         CHECK_LOCAL (ip [1]);
8145
8146                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8147                                 ip = tmp_ip;
8148                                 inline_costs += 1;
8149                                 break;
8150                         }
8151
8152                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8153                         *sp++ = ins;
8154                         ip += 2;
8155                         break;
8156                 }
8157                 case CEE_STLOC_S:
8158                         CHECK_OPSIZE (2);
8159                         CHECK_STACK (1);
8160                         --sp;
8161                         CHECK_LOCAL (ip [1]);
8162                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8163                                 UNVERIFIED;
8164                         emit_stloc_ir (cfg, sp, header, ip [1]);
8165                         ip += 2;
8166                         inline_costs += 1;
8167                         break;
8168                 case CEE_LDNULL:
8169                         CHECK_STACK_OVF (1);
8170                         EMIT_NEW_PCONST (cfg, ins, NULL);
8171                         ins->type = STACK_OBJ;
8172                         ++ip;
8173                         *sp++ = ins;
8174                         break;
8175                 case CEE_LDC_I4_M1:
8176                         CHECK_STACK_OVF (1);
8177                         EMIT_NEW_ICONST (cfg, ins, -1);
8178                         ++ip;
8179                         *sp++ = ins;
8180                         break;
8181                 case CEE_LDC_I4_0:
8182                 case CEE_LDC_I4_1:
8183                 case CEE_LDC_I4_2:
8184                 case CEE_LDC_I4_3:
8185                 case CEE_LDC_I4_4:
8186                 case CEE_LDC_I4_5:
8187                 case CEE_LDC_I4_6:
8188                 case CEE_LDC_I4_7:
8189                 case CEE_LDC_I4_8:
8190                         CHECK_STACK_OVF (1);
8191                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8192                         ++ip;
8193                         *sp++ = ins;
8194                         break;
8195                 case CEE_LDC_I4_S:
8196                         CHECK_OPSIZE (2);
8197                         CHECK_STACK_OVF (1);
8198                         ++ip;
8199                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8200                         ++ip;
8201                         *sp++ = ins;
8202                         break;
8203                 case CEE_LDC_I4:
8204                         CHECK_OPSIZE (5);
8205                         CHECK_STACK_OVF (1);
8206                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8207                         ip += 5;
8208                         *sp++ = ins;
8209                         break;
8210                 case CEE_LDC_I8:
8211                         CHECK_OPSIZE (9);
8212                         CHECK_STACK_OVF (1);
8213                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8214                         ins->type = STACK_I8;
8215                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8216                         ++ip;
8217                         ins->inst_l = (gint64)read64 (ip);
8218                         MONO_ADD_INS (cfg->cbb, ins);
8219                         ip += 8;
8220                         *sp++ = ins;
8221                         break;
8222                 case CEE_LDC_R4: {
8223                         float *f;
8224                         gboolean use_aotconst = FALSE;
8225
8226 #ifdef TARGET_POWERPC
8227                         /* FIXME: Clean this up */
8228                         if (cfg->compile_aot)
8229                                 use_aotconst = TRUE;
8230 #endif
8231
8232                         /* FIXME: we should really allocate this only late in the compilation process */
8233                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8234                         CHECK_OPSIZE (5);
8235                         CHECK_STACK_OVF (1);
8236
8237                         if (use_aotconst) {
8238                                 MonoInst *cons;
8239                                 int dreg;
8240
8241                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8242
8243                                 dreg = alloc_freg (cfg);
8244                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8245                                 ins->type = cfg->r4_stack_type;
8246                         } else {
8247                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8248                                 ins->type = cfg->r4_stack_type;
8249                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8250                                 ins->inst_p0 = f;
8251                                 MONO_ADD_INS (cfg->cbb, ins);
8252                         }
8253                         ++ip;
8254                         readr4 (ip, f);
8255                         ip += 4;
8256                         *sp++ = ins;                    
8257                         break;
8258                 }
8259                 case CEE_LDC_R8: {
8260                         double *d;
8261                         gboolean use_aotconst = FALSE;
8262
8263 #ifdef TARGET_POWERPC
8264                         /* FIXME: Clean this up */
8265                         if (cfg->compile_aot)
8266                                 use_aotconst = TRUE;
8267 #endif
8268
8269                         /* FIXME: we should really allocate this only late in the compilation process */
8270                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8271                         CHECK_OPSIZE (9);
8272                         CHECK_STACK_OVF (1);
8273
8274                         if (use_aotconst) {
8275                                 MonoInst *cons;
8276                                 int dreg;
8277
8278                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8279
8280                                 dreg = alloc_freg (cfg);
8281                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8282                                 ins->type = STACK_R8;
8283                         } else {
8284                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8285                                 ins->type = STACK_R8;
8286                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8287                                 ins->inst_p0 = d;
8288                                 MONO_ADD_INS (cfg->cbb, ins);
8289                         }
8290                         ++ip;
8291                         readr8 (ip, d);
8292                         ip += 8;
8293                         *sp++ = ins;
8294                         break;
8295                 }
8296                 case CEE_DUP: {
8297                         MonoInst *temp, *store;
8298                         CHECK_STACK (1);
8299                         CHECK_STACK_OVF (1);
8300                         sp--;
8301                         ins = *sp;
8302
8303                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8304                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8305
8306                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8307                         *sp++ = ins;
8308
8309                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8310                         *sp++ = ins;
8311
8312                         ++ip;
8313                         inline_costs += 2;
8314                         break;
8315                 }
8316                 case CEE_POP:
8317                         CHECK_STACK (1);
8318                         ip++;
8319                         --sp;
8320
8321 #ifdef TARGET_X86
8322                         if (sp [0]->type == STACK_R8)
8323                                 /* we need to pop the value from the x86 FP stack */
8324                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8325 #endif
8326                         break;
8327                 case CEE_JMP: {
8328                         MonoCallInst *call;
8329                         MonoMethodSignature *fsig;
8330                         int i, n;
8331
8332                         INLINE_FAILURE ("jmp");
8333                         GSHAREDVT_FAILURE (*ip);
8334
8335                         CHECK_OPSIZE (5);
8336                         if (stack_start != sp)
8337                                 UNVERIFIED;
8338                         token = read32 (ip + 1);
8339                         /* FIXME: check the signature matches */
8340                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8341                         CHECK_CFG_ERROR;
8342  
8343                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8344                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8345
8346                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8347
8348                         fsig = mono_method_signature (cmethod);
8349                         n = fsig->param_count + fsig->hasthis;
8350                         if (cfg->llvm_only) {
8351                                 MonoInst **args;
8352
8353                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8354                                 for (i = 0; i < n; ++i)
8355                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8356                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8357                                 /*
8358                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8359                                  * have to emit a normal return since llvm expects it.
8360                                  */
8361                                 if (cfg->ret)
8362                                         emit_setret (cfg, ins);
8363                                 MONO_INST_NEW (cfg, ins, OP_BR);
8364                                 ins->inst_target_bb = end_bblock;
8365                                 MONO_ADD_INS (cfg->cbb, ins);
8366                                 link_bblock (cfg, cfg->cbb, end_bblock);
8367                                 ip += 5;
8368                                 break;
8369                         } else if (cfg->backend->have_op_tail_call) {
8370                                 /* Handle tail calls similarly to calls */
8371                                 DISABLE_AOT (cfg);
8372
8373                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8374                                 call->method = cmethod;
8375                                 call->tail_call = TRUE;
8376                                 call->signature = mono_method_signature (cmethod);
8377                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8378                                 call->inst.inst_p0 = cmethod;
8379                                 for (i = 0; i < n; ++i)
8380                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8381
8382                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8383                                         call->vret_var = cfg->vret_addr;
8384
8385                                 mono_arch_emit_call (cfg, call);
8386                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8387                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8388                         } else {
8389                                 for (i = 0; i < num_args; ++i)
8390                                         /* Prevent arguments from being optimized away */
8391                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8392
8393                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8394                                 ins = (MonoInst*)call;
8395                                 ins->inst_p0 = cmethod;
8396                                 MONO_ADD_INS (cfg->cbb, ins);
8397                         }
8398
8399                         ip += 5;
8400                         start_new_bblock = 1;
8401                         break;
8402                 }
8403                 case CEE_CALLI: {
8404                         MonoInst *addr;
8405                         MonoMethodSignature *fsig;
8406
8407                         CHECK_OPSIZE (5);
8408                         token = read32 (ip + 1);
8409
8410                         ins = NULL;
8411
8412                         //GSHAREDVT_FAILURE (*ip);
8413                         cmethod = NULL;
8414                         CHECK_STACK (1);
8415                         --sp;
8416                         addr = *sp;
8417                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8418                         CHECK_CFG_ERROR;
8419
8420                         if (method->dynamic && fsig->pinvoke) {
8421                                 MonoInst *args [3];
8422
8423                                 /*
8424                                  * This is a call through a function pointer using a pinvoke
8425                                  * signature. Have to create a wrapper and call that instead.
8426                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8427                                  * instead based on the signature.
8428                                  */
8429                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8430                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8431                                 args [2] = addr;
8432                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8433                         }
8434
8435                         n = fsig->param_count + fsig->hasthis;
8436
8437                         CHECK_STACK (n);
8438
8439                         //g_assert (!virtual_ || fsig->hasthis);
8440
8441                         sp -= n;
8442
8443                         inline_costs += 10 * num_calls++;
8444
8445                         /*
8446                          * Making generic calls out of gsharedvt methods.
8447                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8448                          * patching gshared method addresses into a gsharedvt method.
8449                          */
8450                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8451                                 /*
8452                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8453                                  */
8454                                 MonoInst *callee = addr;
8455
8456                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8457                                         /* Not tested */
8458                                         GSHAREDVT_FAILURE (*ip);
8459
8460                                 if (cfg->llvm_only)
8461                                         // FIXME:
8462                                         GSHAREDVT_FAILURE (*ip);
8463
8464                                 addr = emit_get_rgctx_sig (cfg, context_used,
8465                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8466                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8467                                 goto calli_end;
8468                         }
8469
8470                         /* Prevent inlining of methods with indirect calls */
8471                         INLINE_FAILURE ("indirect call");
8472
8473                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8474                                 MonoJumpInfoType info_type;
8475                                 gpointer info_data;
8476
8477                                 /*
8478                                  * Instead of emitting an indirect call, emit a direct call
8479                                  * with the contents of the aotconst as the patch info.
8480                                  */
8481                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8482                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8483                                         info_data = addr->inst_p0;
8484                                 } else {
8485                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8486                                         info_data = addr->inst_right->inst_left;
8487                                 }
8488
8489                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8490                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8491                                         NULLIFY_INS (addr);
8492                                         goto calli_end;
8493                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8494                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8495                                         NULLIFY_INS (addr);
8496                                         goto calli_end;
8497                                 }
8498                         }
8499                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8500
8501                         calli_end:
8502
8503                         /* End of call, INS should contain the result of the call, if any */
8504
8505                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8506                                 g_assert (ins);
8507                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8508                         }
8509
8510                         CHECK_CFG_EXCEPTION;
8511
8512                         ip += 5;
8513                         ins_flag = 0;
8514                         constrained_class = NULL;
8515                         break;
8516                 }
8517                 case CEE_CALL:
8518                 case CEE_CALLVIRT: {
8519                         MonoInst *addr = NULL;
8520                         MonoMethodSignature *fsig = NULL;
8521                         int array_rank = 0;
8522                         int virtual_ = *ip == CEE_CALLVIRT;
8523                         gboolean pass_imt_from_rgctx = FALSE;
8524                         MonoInst *imt_arg = NULL;
8525                         MonoInst *keep_this_alive = NULL;
8526                         gboolean pass_vtable = FALSE;
8527                         gboolean pass_mrgctx = FALSE;
8528                         MonoInst *vtable_arg = NULL;
8529                         gboolean check_this = FALSE;
8530                         gboolean supported_tail_call = FALSE;
8531                         gboolean tail_call = FALSE;
8532                         gboolean need_seq_point = FALSE;
8533                         guint32 call_opcode = *ip;
8534                         gboolean emit_widen = TRUE;
8535                         gboolean push_res = TRUE;
8536                         gboolean skip_ret = FALSE;
8537                         gboolean delegate_invoke = FALSE;
8538                         gboolean direct_icall = FALSE;
8539                         gboolean constrained_partial_call = FALSE;
8540                         MonoMethod *cil_method;
8541
8542                         CHECK_OPSIZE (5);
8543                         token = read32 (ip + 1);
8544
8545                         ins = NULL;
8546
8547                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8548                         CHECK_CFG_ERROR;
8549
8550                         cil_method = cmethod;
8551                                 
8552                         if (constrained_class) {
8553                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8554                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8555                                                 g_assert (!cmethod->klass->valuetype);
8556                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8557                                                         constrained_partial_call = TRUE;
8558                                         }
8559                                 }
8560
8561                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8562                                         if (cfg->verbose_level > 2)
8563                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8564                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8565                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8566                                                   cfg->gshared)) {
8567                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8568                                                 CHECK_CFG_ERROR;
8569                                         }
8570                                 } else {
8571                                         if (cfg->verbose_level > 2)
8572                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8573
8574                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8575                                                 /* 
8576                                                  * This is needed since get_method_constrained can't find 
8577                                                  * the method in klass representing a type var.
8578                                                  * The type var is guaranteed to be a reference type in this
8579                                                  * case.
8580                                                  */
8581                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8582                                                         g_assert (!cmethod->klass->valuetype);
8583                                         } else {
8584                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8585                                                 CHECK_CFG_ERROR;
8586                                         }
8587                                 }
8588
8589                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8590                                         /* Use the corresponding method from the base type to avoid boxing */
8591                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8592                                         g_assert (base_type);
8593                                         constrained_class = mono_class_from_mono_type (base_type);
8594                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8595                                         g_assert (cmethod);
8596                                 }
8597                         }
8598                                         
8599                         if (!dont_verify && !cfg->skip_visibility) {
8600                                 MonoMethod *target_method = cil_method;
8601                                 if (method->is_inflated) {
8602                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8603                                         CHECK_CFG_ERROR;
8604                                 }
8605                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8606                                         !mono_method_can_access_method (method, cil_method))
8607                                         emit_method_access_failure (cfg, method, cil_method);
8608                         }
8609
8610                         if (mono_security_core_clr_enabled ())
8611                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8612
8613                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8614                                 /* MS.NET seems to silently convert this to a callvirt */
8615                                 virtual_ = 1;
8616
8617                         {
8618                                 /*
8619                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8620                                  * converts to a callvirt.
8621                                  *
8622                                  * tests/bug-515884.il is an example of this behavior
8623                                  */
8624                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8625                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8626                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8627                                         virtual_ = 1;
8628                         }
8629
8630                         if (!cmethod->klass->inited)
8631                                 if (!mono_class_init (cmethod->klass))
8632                                         TYPE_LOAD_ERROR (cmethod->klass);
8633
8634                         fsig = mono_method_signature (cmethod);
8635                         if (!fsig)
8636                                 LOAD_ERROR;
8637                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8638                                 mini_class_is_system_array (cmethod->klass)) {
8639                                 array_rank = cmethod->klass->rank;
8640                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8641                                 direct_icall = TRUE;
8642                         } else if (fsig->pinvoke) {
8643                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8644                                 fsig = mono_method_signature (wrapper);
8645                         } else if (constrained_class) {
8646                         } else {
8647                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8648                                 CHECK_CFG_ERROR;
8649                         }
8650
8651                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8652                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8653
8654                         /* See code below */
8655                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8656                                 MonoBasicBlock *tbb;
8657
8658                                 GET_BBLOCK (cfg, tbb, ip + 5);
8659                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8660                                         /*
8661                                          * We want to extend the try block to cover the call, but we can't do it if the
8662                                          * call is made directly since its followed by an exception check.
8663                                          */
8664                                         direct_icall = FALSE;
8665                                 }
8666                         }
8667
8668                         mono_save_token_info (cfg, image, token, cil_method);
8669
8670                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8671                                 need_seq_point = TRUE;
8672
8673                         /* Don't support calls made using type arguments for now */
8674                         /*
8675                           if (cfg->gsharedvt) {
8676                           if (mini_is_gsharedvt_signature (fsig))
8677                           GSHAREDVT_FAILURE (*ip);
8678                           }
8679                         */
8680
8681                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8682                                 g_assert_not_reached ();
8683
8684                         n = fsig->param_count + fsig->hasthis;
8685
8686                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8687                                 UNVERIFIED;
8688
8689                         if (!cfg->gshared)
8690                                 g_assert (!mono_method_check_context_used (cmethod));
8691
8692                         CHECK_STACK (n);
8693
8694                         //g_assert (!virtual_ || fsig->hasthis);
8695
8696                         sp -= n;
8697
8698                         /*
8699                          * We have the `constrained.' prefix opcode.
8700                          */
8701                         if (constrained_class) {
8702                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8703                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8704                                                 /* The 'Own method' case below */
8705                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8706                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8707                                         } else {
8708                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8709                                                 CHECK_CFG_EXCEPTION;
8710                                                 g_assert (ins);
8711                                                 goto call_end;
8712                                         }
8713                                 }
8714
8715                                 if (constrained_partial_call) {
8716                                         gboolean need_box = TRUE;
8717
8718                                         /*
8719                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8720                                          * called method is not known at compile time either. The called method could end up being
8721                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8722                                          * to box the receiver.
8723                                          * A simple solution would be to box always and make a normal virtual call, but that would
8724                                          * be bad performance wise.
8725                                          */
8726                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8727                                                 /*
8728                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8729                                                  */
8730                                                 need_box = FALSE;
8731                                         }
8732
8733                                         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)) {
8734                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8735                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8736                                                 ins->klass = constrained_class;
8737                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8738                                                 CHECK_CFG_EXCEPTION;
8739                                         } else if (need_box) {
8740                                                 MonoInst *box_type;
8741                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8742                                                 MonoInst *nonbox_call;
8743
8744                                                 /*
8745                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8746                                                  * if needed.
8747                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8748                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8749                                                  */
8750                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8751
8752                                                 NEW_BBLOCK (cfg, is_ref_bb);
8753                                                 NEW_BBLOCK (cfg, end_bb);
8754
8755                                                 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);
8756                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8757                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8758
8759                                                 /* Non-ref case */
8760                                                 nonbox_call = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8761
8762                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8763
8764                                                 /* Ref case */
8765                                                 MONO_START_BB (cfg, is_ref_bb);
8766                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8767                                                 ins->klass = constrained_class;
8768                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8769                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8770
8771                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8772
8773                                                 MONO_START_BB (cfg, end_bb);
8774                                                 cfg->cbb = end_bb;
8775
8776                                                 nonbox_call->dreg = ins->dreg;
8777                                                 goto call_end;
8778                                         } else {
8779                                                 g_assert (mono_class_is_interface (cmethod->klass));
8780                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8781                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8782                                                 goto call_end;
8783                                         }
8784                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8785                                         /*
8786                                          * The type parameter is instantiated as a valuetype,
8787                                          * but that type doesn't override the method we're
8788                                          * calling, so we need to box `this'.
8789                                          */
8790                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8791                                         ins->klass = constrained_class;
8792                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8793                                         CHECK_CFG_EXCEPTION;
8794                                 } else if (!constrained_class->valuetype) {
8795                                         int dreg = alloc_ireg_ref (cfg);
8796
8797                                         /*
8798                                          * The type parameter is instantiated as a reference
8799                                          * type.  We have a managed pointer on the stack, so
8800                                          * we need to dereference it here.
8801                                          */
8802                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8803                                         ins->type = STACK_OBJ;
8804                                         sp [0] = ins;
8805                                 } else {
8806                                         if (cmethod->klass->valuetype) {
8807                                                 /* Own method */
8808                                         } else {
8809                                                 /* Interface method */
8810                                                 int ioffset, slot;
8811
8812                                                 mono_class_setup_vtable (constrained_class);
8813                                                 CHECK_TYPELOAD (constrained_class);
8814                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8815                                                 if (ioffset == -1)
8816                                                         TYPE_LOAD_ERROR (constrained_class);
8817                                                 slot = mono_method_get_vtable_slot (cmethod);
8818                                                 if (slot == -1)
8819                                                         TYPE_LOAD_ERROR (cmethod->klass);
8820                                                 cmethod = constrained_class->vtable [ioffset + slot];
8821
8822                                                 if (cmethod->klass == mono_defaults.enum_class) {
8823                                                         /* Enum implements some interfaces, so treat this as the first case */
8824                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8825                                                         ins->klass = constrained_class;
8826                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8827                                                         CHECK_CFG_EXCEPTION;
8828                                                 }
8829                                         }
8830                                         virtual_ = 0;
8831                                 }
8832                                 constrained_class = NULL;
8833                         }
8834
8835                         if (check_call_signature (cfg, fsig, sp))
8836                                 UNVERIFIED;
8837
8838                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8839                                 delegate_invoke = TRUE;
8840
8841                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8842                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8843                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8844                                         emit_widen = FALSE;
8845                                 }
8846
8847                                 goto call_end;
8848                         }
8849
8850                         /* 
8851                          * If the callee is a shared method, then its static cctor
8852                          * might not get called after the call was patched.
8853                          */
8854                         if (cfg->gshared && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
8855                                 emit_class_init (cfg, cmethod->klass);
8856                                 CHECK_TYPELOAD (cmethod->klass);
8857                         }
8858
8859                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8860
8861                         if (cfg->gshared) {
8862                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8863
8864                                 context_used = mini_method_check_context_used (cfg, cmethod);
8865
8866                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8867                                         /* Generic method interface
8868                                            calls are resolved via a
8869                                            helper function and don't
8870                                            need an imt. */
8871                                         if (!cmethod_context || !cmethod_context->method_inst)
8872                                                 pass_imt_from_rgctx = TRUE;
8873                                 }
8874
8875                                 /*
8876                                  * If a shared method calls another
8877                                  * shared method then the caller must
8878                                  * have a generic sharing context
8879                                  * because the magic trampoline
8880                                  * requires it.  FIXME: We shouldn't
8881                                  * have to force the vtable/mrgctx
8882                                  * variable here.  Instead there
8883                                  * should be a flag in the cfg to
8884                                  * request a generic sharing context.
8885                                  */
8886                                 if (context_used &&
8887                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8888                                         mono_get_vtable_var (cfg);
8889                         }
8890
8891                         if (pass_vtable) {
8892                                 if (context_used) {
8893                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8894                                 } else {
8895                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8896
8897                                         CHECK_TYPELOAD (cmethod->klass);
8898                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8899                                 }
8900                         }
8901
8902                         if (pass_mrgctx) {
8903                                 g_assert (!vtable_arg);
8904
8905                                 if (!cfg->compile_aot) {
8906                                         /* 
8907                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8908                                          * for type load errors before.
8909                                          */
8910                                         mono_class_setup_vtable (cmethod->klass);
8911                                         CHECK_TYPELOAD (cmethod->klass);
8912                                 }
8913
8914                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8915
8916                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8917                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8918                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8919                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8920                                         if (virtual_)
8921                                                 check_this = TRUE;
8922                                         virtual_ = 0;
8923                                 }
8924                         }
8925
8926                         if (pass_imt_from_rgctx) {
8927                                 g_assert (!pass_vtable);
8928
8929                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8930                                         cmethod, MONO_RGCTX_INFO_METHOD);
8931                         }
8932
8933                         if (check_this)
8934                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8935
8936                         /* Calling virtual generic methods */
8937                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8938                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8939                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8940                             fsig->generic_param_count && 
8941                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8942                                 !cfg->llvm_only) {
8943                                 MonoInst *this_temp, *this_arg_temp, *store;
8944                                 MonoInst *iargs [4];
8945
8946                                 g_assert (fsig->is_inflated);
8947
8948                                 /* Prevent inlining of methods that contain indirect calls */
8949                                 INLINE_FAILURE ("virtual generic call");
8950
8951                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8952                                         GSHAREDVT_FAILURE (*ip);
8953
8954                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8955                                         g_assert (!imt_arg);
8956                                         if (!context_used)
8957                                                 g_assert (cmethod->is_inflated);
8958                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8959                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8960                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8961                                 } else {
8962                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8963                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8964                                         MONO_ADD_INS (cfg->cbb, store);
8965
8966                                         /* FIXME: This should be a managed pointer */
8967                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8968
8969                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8970                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8971                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8972                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8973                                         addr = mono_emit_jit_icall (cfg,
8974                                                                                                 mono_helper_compile_generic_method, iargs);
8975
8976                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8977
8978                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8979                                 }
8980
8981                                 goto call_end;
8982                         }
8983
8984                         /*
8985                          * Implement a workaround for the inherent races involved in locking:
8986                          * Monitor.Enter ()
8987                          * try {
8988                          * } finally {
8989                          *    Monitor.Exit ()
8990                          * }
8991                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8992                          * try block, the Exit () won't be executed, see:
8993                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8994                          * To work around this, we extend such try blocks to include the last x bytes
8995                          * of the Monitor.Enter () call.
8996                          */
8997                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8998                                 MonoBasicBlock *tbb;
8999
9000                                 GET_BBLOCK (cfg, tbb, ip + 5);
9001                                 /* 
9002                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
9003                                  * from Monitor.Enter like ArgumentNullException.
9004                                  */
9005                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9006                                         /* Mark this bblock as needing to be extended */
9007                                         tbb->extend_try_block = TRUE;
9008                                 }
9009                         }
9010
9011                         /* Conversion to a JIT intrinsic */
9012                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
9013                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9014                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9015                                         emit_widen = FALSE;
9016                                 }
9017                                 goto call_end;
9018                         }
9019                         CHECK_CFG_ERROR;
9020                         
9021                         /* Inlining */
9022                         if ((cfg->opt & MONO_OPT_INLINE) &&
9023                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
9024                             mono_method_check_inlining (cfg, cmethod)) {
9025                                 int costs;
9026                                 gboolean always = FALSE;
9027
9028                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9029                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9030                                         /* Prevent inlining of methods that call wrappers */
9031                                         INLINE_FAILURE ("wrapper call");
9032                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
9033                                         always = TRUE;
9034                                 }
9035
9036                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
9037                                 if (costs) {
9038                                         cfg->real_offset += 5;
9039
9040                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9041                                                 /* *sp is already set by inline_method */
9042                                                 sp++;
9043                                                 push_res = FALSE;
9044                                         }
9045
9046                                         inline_costs += costs;
9047
9048                                         goto call_end;
9049                                 }
9050                         }
9051
9052                         /* Tail recursion elimination */
9053                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
9054                                 gboolean has_vtargs = FALSE;
9055                                 int i;
9056
9057                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9058                                 INLINE_FAILURE ("tail call");
9059
9060                                 /* keep it simple */
9061                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
9062                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
9063                                                 has_vtargs = TRUE;
9064                                 }
9065
9066                                 if (!has_vtargs) {
9067                                         if (need_seq_point) {
9068                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9069                                                 need_seq_point = FALSE;
9070                                         }
9071                                         for (i = 0; i < n; ++i)
9072                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9073                                         MONO_INST_NEW (cfg, ins, OP_BR);
9074                                         MONO_ADD_INS (cfg->cbb, ins);
9075                                         tblock = start_bblock->out_bb [0];
9076                                         link_bblock (cfg, cfg->cbb, tblock);
9077                                         ins->inst_target_bb = tblock;
9078                                         start_new_bblock = 1;
9079
9080                                         /* skip the CEE_RET, too */
9081                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
9082                                                 skip_ret = TRUE;
9083                                         push_res = FALSE;
9084                                         goto call_end;
9085                                 }
9086                         }
9087
9088                         inline_costs += 10 * num_calls++;
9089
9090                         /*
9091                          * Synchronized wrappers.
9092                          * Its hard to determine where to replace a method with its synchronized
9093                          * wrapper without causing an infinite recursion. The current solution is
9094                          * to add the synchronized wrapper in the trampolines, and to
9095                          * change the called method to a dummy wrapper, and resolve that wrapper
9096                          * to the real method in mono_jit_compile_method ().
9097                          */
9098                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9099                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9100                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9101                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9102                         }
9103
9104                         /*
9105                          * Making generic calls out of gsharedvt methods.
9106                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9107                          * patching gshared method addresses into a gsharedvt method.
9108                          */
9109                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
9110                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9111                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9112                                 MonoRgctxInfoType info_type;
9113
9114                                 if (virtual_) {
9115                                         //if (mono_class_is_interface (cmethod->klass))
9116                                                 //GSHAREDVT_FAILURE (*ip);
9117                                         // disable for possible remoting calls
9118                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9119                                                 GSHAREDVT_FAILURE (*ip);
9120                                         if (fsig->generic_param_count) {
9121                                                 /* virtual generic call */
9122                                                 g_assert (!imt_arg);
9123                                                 /* Same as the virtual generic case above */
9124                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9125                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9126                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9127                                                 vtable_arg = NULL;
9128                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
9129                                                 /* This can happen when we call a fully instantiated iface method */
9130                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9131                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9132                                                 vtable_arg = NULL;
9133                                         }
9134                                 }
9135
9136                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9137                                         keep_this_alive = sp [0];
9138
9139                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9140                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9141                                 else
9142                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9143                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9144
9145                                 if (cfg->llvm_only) {
9146                                         // FIXME: Avoid initializing vtable_arg
9147                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9148                                 } else {
9149                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9150                                 }
9151                                 goto call_end;
9152                         }
9153
9154                         /* Generic sharing */
9155
9156                         /*
9157                          * Use this if the callee is gsharedvt sharable too, since
9158                          * at runtime we might find an instantiation so the call cannot
9159                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9160                          */
9161                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9162                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9163                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9164                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9165                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9166                                 INLINE_FAILURE ("gshared");
9167
9168                                 g_assert (cfg->gshared && cmethod);
9169                                 g_assert (!addr);
9170
9171                                 /*
9172                                  * We are compiling a call to a
9173                                  * generic method from shared code,
9174                                  * which means that we have to look up
9175                                  * the method in the rgctx and do an
9176                                  * indirect call.
9177                                  */
9178                                 if (fsig->hasthis)
9179                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9180
9181                                 if (cfg->llvm_only) {
9182                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9183                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9184                                         else
9185                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9186                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9187                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9188                                 } else {
9189                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9190                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9191                                 }
9192                                 goto call_end;
9193                         }
9194
9195                         /* Direct calls to icalls */
9196                         if (direct_icall) {
9197                                 MonoMethod *wrapper;
9198                                 int costs;
9199
9200                                 /* Inline the wrapper */
9201                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9202
9203                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9204                                 g_assert (costs > 0);
9205                                 cfg->real_offset += 5;
9206
9207                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9208                                         /* *sp is already set by inline_method */
9209                                         sp++;
9210                                         push_res = FALSE;
9211                                 }
9212
9213                                 inline_costs += costs;
9214
9215                                 goto call_end;
9216                         }
9217                                         
9218                         /* Array methods */
9219                         if (array_rank) {
9220                                 MonoInst *addr;
9221
9222                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9223                                         MonoInst *val = sp [fsig->param_count];
9224
9225                                         if (val->type == STACK_OBJ) {
9226                                                 MonoInst *iargs [2];
9227
9228                                                 iargs [0] = sp [0];
9229                                                 iargs [1] = val;
9230                                                 
9231                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9232                                         }
9233                                         
9234                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9235                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9236                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
9237                                                 emit_write_barrier (cfg, addr, val);
9238                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9239                                                 GSHAREDVT_FAILURE (*ip);
9240                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9241                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9242
9243                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9244                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9245                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9246                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9247                                         CHECK_TYPELOAD (cmethod->klass);
9248                                         
9249                                         readonly = FALSE;
9250                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9251                                         ins = addr;
9252                                 } else {
9253                                         g_assert_not_reached ();
9254                                 }
9255
9256                                 emit_widen = FALSE;
9257                                 goto call_end;
9258                         }
9259
9260                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9261                         if (ins)
9262                                 goto call_end;
9263
9264                         /* Tail prefix / tail call optimization */
9265
9266                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9267                         /* FIXME: runtime generic context pointer for jumps? */
9268                         /* FIXME: handle this for generic sharing eventually */
9269                         if ((ins_flag & MONO_INST_TAILCALL) &&
9270                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9271                                 supported_tail_call = TRUE;
9272
9273                         if (supported_tail_call) {
9274                                 MonoCallInst *call;
9275
9276                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9277                                 INLINE_FAILURE ("tail call");
9278
9279                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9280
9281                                 if (cfg->backend->have_op_tail_call) {
9282                                         /* Handle tail calls similarly to normal calls */
9283                                         tail_call = TRUE;
9284                                 } else {
9285                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9286
9287                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9288                                         call->tail_call = TRUE;
9289                                         call->method = cmethod;
9290                                         call->signature = mono_method_signature (cmethod);
9291
9292                                         /*
9293                                          * We implement tail calls by storing the actual arguments into the 
9294                                          * argument variables, then emitting a CEE_JMP.
9295                                          */
9296                                         for (i = 0; i < n; ++i) {
9297                                                 /* Prevent argument from being register allocated */
9298                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9299                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9300                                         }
9301                                         ins = (MonoInst*)call;
9302                                         ins->inst_p0 = cmethod;
9303                                         ins->inst_p1 = arg_array [0];
9304                                         MONO_ADD_INS (cfg->cbb, ins);
9305                                         link_bblock (cfg, cfg->cbb, end_bblock);
9306                                         start_new_bblock = 1;
9307
9308                                         // FIXME: Eliminate unreachable epilogs
9309
9310                                         /*
9311                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9312                                          * only reachable from this call.
9313                                          */
9314                                         GET_BBLOCK (cfg, tblock, ip + 5);
9315                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9316                                                 skip_ret = TRUE;
9317                                         push_res = FALSE;
9318
9319                                         goto call_end;
9320                                 }
9321                         }
9322
9323                         /*
9324                          * Virtual calls in llvm-only mode.
9325                          */
9326                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9327                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9328                                 goto call_end;
9329                         }
9330
9331                         /* Common call */
9332                         if (!(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9333                                 INLINE_FAILURE ("call");
9334                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9335                                                                                           imt_arg, vtable_arg);
9336
9337                         if (tail_call && !cfg->llvm_only) {
9338                                 link_bblock (cfg, cfg->cbb, end_bblock);
9339                                 start_new_bblock = 1;
9340
9341                                 // FIXME: Eliminate unreachable epilogs
9342
9343                                 /*
9344                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9345                                  * only reachable from this call.
9346                                  */
9347                                 GET_BBLOCK (cfg, tblock, ip + 5);
9348                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9349                                         skip_ret = TRUE;
9350                                 push_res = FALSE;
9351                         }
9352
9353                         call_end:
9354
9355                         /* End of call, INS should contain the result of the call, if any */
9356
9357                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9358                                 g_assert (ins);
9359                                 if (emit_widen)
9360                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9361                                 else
9362                                         *sp++ = ins;
9363                         }
9364
9365                         if (keep_this_alive) {
9366                                 MonoInst *dummy_use;
9367
9368                                 /* See mono_emit_method_call_full () */
9369                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9370                         }
9371
9372                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9373                                 /*
9374                                  * Clang can convert these calls to tail calls which screw up the stack
9375                                  * walk. This happens even when the -fno-optimize-sibling-calls
9376                                  * option is passed to clang.
9377                                  * Work around this by emitting a dummy call.
9378                                  */
9379                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9380                         }
9381
9382                         CHECK_CFG_EXCEPTION;
9383
9384                         ip += 5;
9385                         if (skip_ret) {
9386                                 g_assert (*ip == CEE_RET);
9387                                 ip += 1;
9388                         }
9389                         ins_flag = 0;
9390                         constrained_class = NULL;
9391                         if (need_seq_point)
9392                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9393                         break;
9394                 }
9395                 case CEE_RET:
9396                         if (cfg->method != method) {
9397                                 /* return from inlined method */
9398                                 /* 
9399                                  * If in_count == 0, that means the ret is unreachable due to
9400                                  * being preceeded by a throw. In that case, inline_method () will
9401                                  * handle setting the return value 
9402                                  * (test case: test_0_inline_throw ()).
9403                                  */
9404                                 if (return_var && cfg->cbb->in_count) {
9405                                         MonoType *ret_type = mono_method_signature (method)->ret;
9406
9407                                         MonoInst *store;
9408                                         CHECK_STACK (1);
9409                                         --sp;
9410
9411                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9412                                                 UNVERIFIED;
9413
9414                                         //g_assert (returnvar != -1);
9415                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9416                                         cfg->ret_var_set = TRUE;
9417                                 } 
9418                         } else {
9419                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9420
9421                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9422                                         emit_pop_lmf (cfg);
9423
9424                                 if (cfg->ret) {
9425                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9426
9427                                         if (seq_points && !sym_seq_points) {
9428                                                 /* 
9429                                                  * Place a seq point here too even through the IL stack is not
9430                                                  * empty, so a step over on
9431                                                  * call <FOO>
9432                                                  * ret
9433                                                  * will work correctly.
9434                                                  */
9435                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9436                                                 MONO_ADD_INS (cfg->cbb, ins);
9437                                         }
9438
9439                                         g_assert (!return_var);
9440                                         CHECK_STACK (1);
9441                                         --sp;
9442
9443                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9444                                                 UNVERIFIED;
9445
9446                                         emit_setret (cfg, *sp);
9447                                 }
9448                         }
9449                         if (sp != stack_start)
9450                                 UNVERIFIED;
9451                         MONO_INST_NEW (cfg, ins, OP_BR);
9452                         ip++;
9453                         ins->inst_target_bb = end_bblock;
9454                         MONO_ADD_INS (cfg->cbb, ins);
9455                         link_bblock (cfg, cfg->cbb, end_bblock);
9456                         start_new_bblock = 1;
9457                         break;
9458                 case CEE_BR_S:
9459                         CHECK_OPSIZE (2);
9460                         MONO_INST_NEW (cfg, ins, OP_BR);
9461                         ip++;
9462                         target = ip + 1 + (signed char)(*ip);
9463                         ++ip;
9464                         GET_BBLOCK (cfg, tblock, target);
9465                         link_bblock (cfg, cfg->cbb, tblock);
9466                         ins->inst_target_bb = tblock;
9467                         if (sp != stack_start) {
9468                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9469                                 sp = stack_start;
9470                                 CHECK_UNVERIFIABLE (cfg);
9471                         }
9472                         MONO_ADD_INS (cfg->cbb, ins);
9473                         start_new_bblock = 1;
9474                         inline_costs += BRANCH_COST;
9475                         break;
9476                 case CEE_BEQ_S:
9477                 case CEE_BGE_S:
9478                 case CEE_BGT_S:
9479                 case CEE_BLE_S:
9480                 case CEE_BLT_S:
9481                 case CEE_BNE_UN_S:
9482                 case CEE_BGE_UN_S:
9483                 case CEE_BGT_UN_S:
9484                 case CEE_BLE_UN_S:
9485                 case CEE_BLT_UN_S:
9486                         CHECK_OPSIZE (2);
9487                         CHECK_STACK (2);
9488                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9489                         ip++;
9490                         target = ip + 1 + *(signed char*)ip;
9491                         ip++;
9492
9493                         ADD_BINCOND (NULL);
9494
9495                         sp = stack_start;
9496                         inline_costs += BRANCH_COST;
9497                         break;
9498                 case CEE_BR:
9499                         CHECK_OPSIZE (5);
9500                         MONO_INST_NEW (cfg, ins, OP_BR);
9501                         ip++;
9502
9503                         target = ip + 4 + (gint32)read32(ip);
9504                         ip += 4;
9505                         GET_BBLOCK (cfg, tblock, target);
9506                         link_bblock (cfg, cfg->cbb, tblock);
9507                         ins->inst_target_bb = tblock;
9508                         if (sp != stack_start) {
9509                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9510                                 sp = stack_start;
9511                                 CHECK_UNVERIFIABLE (cfg);
9512                         }
9513
9514                         MONO_ADD_INS (cfg->cbb, ins);
9515
9516                         start_new_bblock = 1;
9517                         inline_costs += BRANCH_COST;
9518                         break;
9519                 case CEE_BRFALSE_S:
9520                 case CEE_BRTRUE_S:
9521                 case CEE_BRFALSE:
9522                 case CEE_BRTRUE: {
9523                         MonoInst *cmp;
9524                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9525                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9526                         guint32 opsize = is_short ? 1 : 4;
9527
9528                         CHECK_OPSIZE (opsize);
9529                         CHECK_STACK (1);
9530                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9531                                 UNVERIFIED;
9532                         ip ++;
9533                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9534                         ip += opsize;
9535
9536                         sp--;
9537
9538                         GET_BBLOCK (cfg, tblock, target);
9539                         link_bblock (cfg, cfg->cbb, tblock);
9540                         GET_BBLOCK (cfg, tblock, ip);
9541                         link_bblock (cfg, cfg->cbb, tblock);
9542
9543                         if (sp != stack_start) {
9544                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9545                                 CHECK_UNVERIFIABLE (cfg);
9546                         }
9547
9548                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9549                         cmp->sreg1 = sp [0]->dreg;
9550                         type_from_op (cfg, cmp, sp [0], NULL);
9551                         CHECK_TYPE (cmp);
9552
9553 #if SIZEOF_REGISTER == 4
9554                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9555                                 /* Convert it to OP_LCOMPARE */
9556                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9557                                 ins->type = STACK_I8;
9558                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9559                                 ins->inst_l = 0;
9560                                 MONO_ADD_INS (cfg->cbb, ins);
9561                                 cmp->opcode = OP_LCOMPARE;
9562                                 cmp->sreg2 = ins->dreg;
9563                         }
9564 #endif
9565                         MONO_ADD_INS (cfg->cbb, cmp);
9566
9567                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9568                         type_from_op (cfg, ins, sp [0], NULL);
9569                         MONO_ADD_INS (cfg->cbb, ins);
9570                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9571                         GET_BBLOCK (cfg, tblock, target);
9572                         ins->inst_true_bb = tblock;
9573                         GET_BBLOCK (cfg, tblock, ip);
9574                         ins->inst_false_bb = tblock;
9575                         start_new_bblock = 2;
9576
9577                         sp = stack_start;
9578                         inline_costs += BRANCH_COST;
9579                         break;
9580                 }
9581                 case CEE_BEQ:
9582                 case CEE_BGE:
9583                 case CEE_BGT:
9584                 case CEE_BLE:
9585                 case CEE_BLT:
9586                 case CEE_BNE_UN:
9587                 case CEE_BGE_UN:
9588                 case CEE_BGT_UN:
9589                 case CEE_BLE_UN:
9590                 case CEE_BLT_UN:
9591                         CHECK_OPSIZE (5);
9592                         CHECK_STACK (2);
9593                         MONO_INST_NEW (cfg, ins, *ip);
9594                         ip++;
9595                         target = ip + 4 + (gint32)read32(ip);
9596                         ip += 4;
9597
9598                         ADD_BINCOND (NULL);
9599
9600                         sp = stack_start;
9601                         inline_costs += BRANCH_COST;
9602                         break;
9603                 case CEE_SWITCH: {
9604                         MonoInst *src1;
9605                         MonoBasicBlock **targets;
9606                         MonoBasicBlock *default_bblock;
9607                         MonoJumpInfoBBTable *table;
9608                         int offset_reg = alloc_preg (cfg);
9609                         int target_reg = alloc_preg (cfg);
9610                         int table_reg = alloc_preg (cfg);
9611                         int sum_reg = alloc_preg (cfg);
9612                         gboolean use_op_switch;
9613
9614                         CHECK_OPSIZE (5);
9615                         CHECK_STACK (1);
9616                         n = read32 (ip + 1);
9617                         --sp;
9618                         src1 = sp [0];
9619                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9620                                 UNVERIFIED;
9621
9622                         ip += 5;
9623                         CHECK_OPSIZE (n * sizeof (guint32));
9624                         target = ip + n * sizeof (guint32);
9625
9626                         GET_BBLOCK (cfg, default_bblock, target);
9627                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9628
9629                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9630                         for (i = 0; i < n; ++i) {
9631                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9632                                 targets [i] = tblock;
9633                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9634                                 ip += 4;
9635                         }
9636
9637                         if (sp != stack_start) {
9638                                 /* 
9639                                  * Link the current bb with the targets as well, so handle_stack_args
9640                                  * will set their in_stack correctly.
9641                                  */
9642                                 link_bblock (cfg, cfg->cbb, default_bblock);
9643                                 for (i = 0; i < n; ++i)
9644                                         link_bblock (cfg, cfg->cbb, targets [i]);
9645
9646                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9647                                 sp = stack_start;
9648                                 CHECK_UNVERIFIABLE (cfg);
9649
9650                                 /* Undo the links */
9651                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9652                                 for (i = 0; i < n; ++i)
9653                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9654                         }
9655
9656                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9657                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9658
9659                         for (i = 0; i < n; ++i)
9660                                 link_bblock (cfg, cfg->cbb, targets [i]);
9661
9662                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9663                         table->table = targets;
9664                         table->table_size = n;
9665
9666                         use_op_switch = FALSE;
9667 #ifdef TARGET_ARM
9668                         /* ARM implements SWITCH statements differently */
9669                         /* FIXME: Make it use the generic implementation */
9670                         if (!cfg->compile_aot)
9671                                 use_op_switch = TRUE;
9672 #endif
9673
9674                         if (COMPILE_LLVM (cfg))
9675                                 use_op_switch = TRUE;
9676
9677                         cfg->cbb->has_jump_table = 1;
9678
9679                         if (use_op_switch) {
9680                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9681                                 ins->sreg1 = src1->dreg;
9682                                 ins->inst_p0 = table;
9683                                 ins->inst_many_bb = targets;
9684                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9685                                 MONO_ADD_INS (cfg->cbb, ins);
9686                         } else {
9687                                 if (sizeof (gpointer) == 8)
9688                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9689                                 else
9690                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9691
9692 #if SIZEOF_REGISTER == 8
9693                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9694                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9695 #endif
9696
9697                                 if (cfg->compile_aot) {
9698                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9699                                 } else {
9700                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9701                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9702                                         ins->inst_p0 = table;
9703                                         ins->dreg = table_reg;
9704                                         MONO_ADD_INS (cfg->cbb, ins);
9705                                 }
9706
9707                                 /* FIXME: Use load_memindex */
9708                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9709                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9710                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9711                         }
9712                         start_new_bblock = 1;
9713                         inline_costs += (BRANCH_COST * 2);
9714                         break;
9715                 }
9716                 case CEE_LDIND_I1:
9717                 case CEE_LDIND_U1:
9718                 case CEE_LDIND_I2:
9719                 case CEE_LDIND_U2:
9720                 case CEE_LDIND_I4:
9721                 case CEE_LDIND_U4:
9722                 case CEE_LDIND_I8:
9723                 case CEE_LDIND_I:
9724                 case CEE_LDIND_R4:
9725                 case CEE_LDIND_R8:
9726                 case CEE_LDIND_REF:
9727                         CHECK_STACK (1);
9728                         --sp;
9729
9730                         switch (*ip) {
9731                         case CEE_LDIND_R4:
9732                         case CEE_LDIND_R8:
9733                                 dreg = alloc_freg (cfg);
9734                                 break;
9735                         case CEE_LDIND_I8:
9736                                 dreg = alloc_lreg (cfg);
9737                                 break;
9738                         case CEE_LDIND_REF:
9739                                 dreg = alloc_ireg_ref (cfg);
9740                                 break;
9741                         default:
9742                                 dreg = alloc_preg (cfg);
9743                         }
9744
9745                         NEW_LOAD_MEMBASE (cfg, ins, ldind_to_load_membase (*ip), dreg, sp [0]->dreg, 0);
9746                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
9747                         if (*ip == CEE_LDIND_R4)
9748                                 ins->type = cfg->r4_stack_type;
9749                         ins->flags |= ins_flag;
9750                         MONO_ADD_INS (cfg->cbb, ins);
9751                         *sp++ = ins;
9752                         if (ins_flag & MONO_INST_VOLATILE) {
9753                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9754                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9755                         }
9756                         ins_flag = 0;
9757                         ++ip;
9758                         break;
9759                 case CEE_STIND_REF:
9760                 case CEE_STIND_I1:
9761                 case CEE_STIND_I2:
9762                 case CEE_STIND_I4:
9763                 case CEE_STIND_I8:
9764                 case CEE_STIND_R4:
9765                 case CEE_STIND_R8:
9766                 case CEE_STIND_I:
9767                         CHECK_STACK (2);
9768                         sp -= 2;
9769
9770                         if (ins_flag & MONO_INST_VOLATILE) {
9771                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9772                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9773                         }
9774
9775                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9776                         ins->flags |= ins_flag;
9777                         ins_flag = 0;
9778
9779                         MONO_ADD_INS (cfg->cbb, ins);
9780
9781                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9782                                 emit_write_barrier (cfg, sp [0], sp [1]);
9783
9784                         inline_costs += 1;
9785                         ++ip;
9786                         break;
9787
9788                 case CEE_MUL:
9789                         CHECK_STACK (2);
9790
9791                         MONO_INST_NEW (cfg, ins, (*ip));
9792                         sp -= 2;
9793                         ins->sreg1 = sp [0]->dreg;
9794                         ins->sreg2 = sp [1]->dreg;
9795                         type_from_op (cfg, ins, sp [0], sp [1]);
9796                         CHECK_TYPE (ins);
9797                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9798
9799                         /* Use the immediate opcodes if possible */
9800                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9801                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9802                                 if (imm_opcode != -1) {
9803                                         ins->opcode = imm_opcode;
9804                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9805                                         ins->sreg2 = -1;
9806
9807                                         NULLIFY_INS (sp [1]);
9808                                 }
9809                         }
9810
9811                         MONO_ADD_INS ((cfg)->cbb, (ins));
9812
9813                         *sp++ = mono_decompose_opcode (cfg, ins);
9814                         ip++;
9815                         break;
9816                 case CEE_ADD:
9817                 case CEE_SUB:
9818                 case CEE_DIV:
9819                 case CEE_DIV_UN:
9820                 case CEE_REM:
9821                 case CEE_REM_UN:
9822                 case CEE_AND:
9823                 case CEE_OR:
9824                 case CEE_XOR:
9825                 case CEE_SHL:
9826                 case CEE_SHR:
9827                 case CEE_SHR_UN:
9828                         CHECK_STACK (2);
9829
9830                         MONO_INST_NEW (cfg, ins, (*ip));
9831                         sp -= 2;
9832                         ins->sreg1 = sp [0]->dreg;
9833                         ins->sreg2 = sp [1]->dreg;
9834                         type_from_op (cfg, ins, sp [0], sp [1]);
9835                         CHECK_TYPE (ins);
9836                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9837                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9838
9839                         /* FIXME: Pass opcode to is_inst_imm */
9840
9841                         /* Use the immediate opcodes if possible */
9842                         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)) {
9843                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9844                                 if (imm_opcode != -1) {
9845                                         ins->opcode = imm_opcode;
9846                                         if (sp [1]->opcode == OP_I8CONST) {
9847 #if SIZEOF_REGISTER == 8
9848                                                 ins->inst_imm = sp [1]->inst_l;
9849 #else
9850                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9851                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9852 #endif
9853                                         }
9854                                         else
9855                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9856                                         ins->sreg2 = -1;
9857
9858                                         /* Might be followed by an instruction added by add_widen_op */
9859                                         if (sp [1]->next == NULL)
9860                                                 NULLIFY_INS (sp [1]);
9861                                 }
9862                         }
9863                         MONO_ADD_INS ((cfg)->cbb, (ins));
9864
9865                         *sp++ = mono_decompose_opcode (cfg, ins);
9866                         ip++;
9867                         break;
9868                 case CEE_NEG:
9869                 case CEE_NOT:
9870                 case CEE_CONV_I1:
9871                 case CEE_CONV_I2:
9872                 case CEE_CONV_I4:
9873                 case CEE_CONV_R4:
9874                 case CEE_CONV_R8:
9875                 case CEE_CONV_U4:
9876                 case CEE_CONV_I8:
9877                 case CEE_CONV_U8:
9878                 case CEE_CONV_OVF_I8:
9879                 case CEE_CONV_OVF_U8:
9880                 case CEE_CONV_R_UN:
9881                         CHECK_STACK (1);
9882
9883                         /* Special case this earlier so we have long constants in the IR */
9884                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9885                                 int data = sp [-1]->inst_c0;
9886                                 sp [-1]->opcode = OP_I8CONST;
9887                                 sp [-1]->type = STACK_I8;
9888 #if SIZEOF_REGISTER == 8
9889                                 if ((*ip) == CEE_CONV_U8)
9890                                         sp [-1]->inst_c0 = (guint32)data;
9891                                 else
9892                                         sp [-1]->inst_c0 = data;
9893 #else
9894                                 sp [-1]->inst_ls_word = data;
9895                                 if ((*ip) == CEE_CONV_U8)
9896                                         sp [-1]->inst_ms_word = 0;
9897                                 else
9898                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9899 #endif
9900                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9901                         }
9902                         else {
9903                                 ADD_UNOP (*ip);
9904                         }
9905                         ip++;
9906                         break;
9907                 case CEE_CONV_OVF_I4:
9908                 case CEE_CONV_OVF_I1:
9909                 case CEE_CONV_OVF_I2:
9910                 case CEE_CONV_OVF_I:
9911                 case CEE_CONV_OVF_U:
9912                         CHECK_STACK (1);
9913
9914                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9915                                 ADD_UNOP (CEE_CONV_OVF_I8);
9916                                 ADD_UNOP (*ip);
9917                         } else {
9918                                 ADD_UNOP (*ip);
9919                         }
9920                         ip++;
9921                         break;
9922                 case CEE_CONV_OVF_U1:
9923                 case CEE_CONV_OVF_U2:
9924                 case CEE_CONV_OVF_U4:
9925                         CHECK_STACK (1);
9926
9927                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9928                                 ADD_UNOP (CEE_CONV_OVF_U8);
9929                                 ADD_UNOP (*ip);
9930                         } else {
9931                                 ADD_UNOP (*ip);
9932                         }
9933                         ip++;
9934                         break;
9935                 case CEE_CONV_OVF_I1_UN:
9936                 case CEE_CONV_OVF_I2_UN:
9937                 case CEE_CONV_OVF_I4_UN:
9938                 case CEE_CONV_OVF_I8_UN:
9939                 case CEE_CONV_OVF_U1_UN:
9940                 case CEE_CONV_OVF_U2_UN:
9941                 case CEE_CONV_OVF_U4_UN:
9942                 case CEE_CONV_OVF_U8_UN:
9943                 case CEE_CONV_OVF_I_UN:
9944                 case CEE_CONV_OVF_U_UN:
9945                 case CEE_CONV_U2:
9946                 case CEE_CONV_U1:
9947                 case CEE_CONV_I:
9948                 case CEE_CONV_U:
9949                         CHECK_STACK (1);
9950                         ADD_UNOP (*ip);
9951                         CHECK_CFG_EXCEPTION;
9952                         ip++;
9953                         break;
9954                 case CEE_ADD_OVF:
9955                 case CEE_ADD_OVF_UN:
9956                 case CEE_MUL_OVF:
9957                 case CEE_MUL_OVF_UN:
9958                 case CEE_SUB_OVF:
9959                 case CEE_SUB_OVF_UN:
9960                         CHECK_STACK (2);
9961                         ADD_BINOP (*ip);
9962                         ip++;
9963                         break;
9964                 case CEE_CPOBJ:
9965                         GSHAREDVT_FAILURE (*ip);
9966                         CHECK_OPSIZE (5);
9967                         CHECK_STACK (2);
9968                         token = read32 (ip + 1);
9969                         klass = mini_get_class (method, token, generic_context);
9970                         CHECK_TYPELOAD (klass);
9971                         sp -= 2;
9972                         if (generic_class_is_reference_type (cfg, klass)) {
9973                                 MonoInst *store, *load;
9974                                 int dreg = alloc_ireg_ref (cfg);
9975
9976                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
9977                                 load->flags |= ins_flag;
9978                                 MONO_ADD_INS (cfg->cbb, load);
9979
9980                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
9981                                 store->flags |= ins_flag;
9982                                 MONO_ADD_INS (cfg->cbb, store);
9983
9984                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
9985                                         emit_write_barrier (cfg, sp [0], sp [1]);
9986                         } else {
9987                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
9988                         }
9989                         ins_flag = 0;
9990                         ip += 5;
9991                         break;
9992                 case CEE_LDOBJ: {
9993                         int loc_index = -1;
9994                         int stloc_len = 0;
9995
9996                         CHECK_OPSIZE (5);
9997                         CHECK_STACK (1);
9998                         --sp;
9999                         token = read32 (ip + 1);
10000                         klass = mini_get_class (method, token, generic_context);
10001                         CHECK_TYPELOAD (klass);
10002
10003                         /* Optimize the common ldobj+stloc combination */
10004                         switch (ip [5]) {
10005                         case CEE_STLOC_S:
10006                                 loc_index = ip [6];
10007                                 stloc_len = 2;
10008                                 break;
10009                         case CEE_STLOC_0:
10010                         case CEE_STLOC_1:
10011                         case CEE_STLOC_2:
10012                         case CEE_STLOC_3:
10013                                 loc_index = ip [5] - CEE_STLOC_0;
10014                                 stloc_len = 1;
10015                                 break;
10016                         default:
10017                                 break;
10018                         }
10019
10020                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
10021                                 CHECK_LOCAL (loc_index);
10022
10023                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10024                                 ins->dreg = cfg->locals [loc_index]->dreg;
10025                                 ins->flags |= ins_flag;
10026                                 ip += 5;
10027                                 ip += stloc_len;
10028                                 if (ins_flag & MONO_INST_VOLATILE) {
10029                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10030                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10031                                 }
10032                                 ins_flag = 0;
10033                                 break;
10034                         }
10035
10036                         /* Optimize the ldobj+stobj combination */
10037                         /* The reference case ends up being a load+store anyway */
10038                         /* Skip this if the operation is volatile. */
10039                         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)) {
10040                                 CHECK_STACK (1);
10041
10042                                 sp --;
10043
10044                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10045
10046                                 ip += 5 + 5;
10047                                 ins_flag = 0;
10048                                 break;
10049                         }
10050
10051                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10052                         ins->flags |= ins_flag;
10053                         *sp++ = ins;
10054
10055                         if (ins_flag & MONO_INST_VOLATILE) {
10056                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10057                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10058                         }
10059
10060                         ip += 5;
10061                         ins_flag = 0;
10062                         inline_costs += 1;
10063                         break;
10064                 }
10065                 case CEE_LDSTR:
10066                         CHECK_STACK_OVF (1);
10067                         CHECK_OPSIZE (5);
10068                         n = read32 (ip + 1);
10069
10070                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
10071                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
10072                                 ins->type = STACK_OBJ;
10073                                 *sp = ins;
10074                         }
10075                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
10076                                 MonoInst *iargs [1];
10077                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
10078
10079                                 if (cfg->compile_aot)
10080                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
10081                                 else
10082                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
10083                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
10084                         } else {
10085                                 if (cfg->opt & MONO_OPT_SHARED) {
10086                                         MonoInst *iargs [3];
10087
10088                                         if (cfg->compile_aot) {
10089                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
10090                                         }
10091                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10092                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
10093                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
10094                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
10095                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10096                                         CHECK_CFG_ERROR;
10097                                 } else {
10098                                         if (cfg->cbb->out_of_line) {
10099                                                 MonoInst *iargs [2];
10100
10101                                                 if (image == mono_defaults.corlib) {
10102                                                         /* 
10103                                                          * Avoid relocations in AOT and save some space by using a 
10104                                                          * version of helper_ldstr specialized to mscorlib.
10105                                                          */
10106                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
10107                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
10108                                                 } else {
10109                                                         /* Avoid creating the string object */
10110                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
10111                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
10112                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
10113                                                 }
10114                                         } 
10115                                         else
10116                                         if (cfg->compile_aot) {
10117                                                 NEW_LDSTRCONST (cfg, ins, image, n);
10118                                                 *sp = ins;
10119                                                 MONO_ADD_INS (cfg->cbb, ins);
10120                                         } 
10121                                         else {
10122                                                 NEW_PCONST (cfg, ins, NULL);
10123                                                 ins->type = STACK_OBJ;
10124                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10125                                                 CHECK_CFG_ERROR;
10126                                                 
10127                                                 if (!ins->inst_p0)
10128                                                         OUT_OF_MEMORY_FAILURE;
10129
10130                                                 *sp = ins;
10131                                                 MONO_ADD_INS (cfg->cbb, ins);
10132                                         }
10133                                 }
10134                         }
10135
10136                         sp++;
10137                         ip += 5;
10138                         break;
10139                 case CEE_NEWOBJ: {
10140                         MonoInst *iargs [2];
10141                         MonoMethodSignature *fsig;
10142                         MonoInst this_ins;
10143                         MonoInst *alloc;
10144                         MonoInst *vtable_arg = NULL;
10145
10146                         CHECK_OPSIZE (5);
10147                         token = read32 (ip + 1);
10148                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10149                         CHECK_CFG_ERROR;
10150
10151                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10152                         CHECK_CFG_ERROR;
10153
10154                         mono_save_token_info (cfg, image, token, cmethod);
10155
10156                         if (!mono_class_init (cmethod->klass))
10157                                 TYPE_LOAD_ERROR (cmethod->klass);
10158
10159                         context_used = mini_method_check_context_used (cfg, cmethod);
10160
10161                         if (mono_security_core_clr_enabled ())
10162                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10163
10164                         if (cfg->gshared && cmethod && cmethod->klass != method->klass && mono_class_is_ginst (cmethod->klass) && mono_method_is_generic_sharable (cmethod, TRUE) && mono_class_needs_cctor_run (cmethod->klass, method)) {
10165                                 emit_class_init (cfg, cmethod->klass);
10166                                 CHECK_TYPELOAD (cmethod->klass);
10167                         }
10168
10169                         /*
10170                         if (cfg->gsharedvt) {
10171                                 if (mini_is_gsharedvt_variable_signature (sig))
10172                                         GSHAREDVT_FAILURE (*ip);
10173                         }
10174                         */
10175
10176                         n = fsig->param_count;
10177                         CHECK_STACK (n);
10178
10179                         /* 
10180                          * Generate smaller code for the common newobj <exception> instruction in
10181                          * argument checking code.
10182                          */
10183                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10184                                 is_exception_class (cmethod->klass) && n <= 2 &&
10185                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10186                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10187                                 MonoInst *iargs [3];
10188
10189                                 sp -= n;
10190
10191                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10192                                 switch (n) {
10193                                 case 0:
10194                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10195                                         break;
10196                                 case 1:
10197                                         iargs [1] = sp [0];
10198                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10199                                         break;
10200                                 case 2:
10201                                         iargs [1] = sp [0];
10202                                         iargs [2] = sp [1];
10203                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10204                                         break;
10205                                 default:
10206                                         g_assert_not_reached ();
10207                                 }
10208
10209                                 ip += 5;
10210                                 inline_costs += 5;
10211                                 break;
10212                         }
10213
10214                         /* move the args to allow room for 'this' in the first position */
10215                         while (n--) {
10216                                 --sp;
10217                                 sp [1] = sp [0];
10218                         }
10219
10220                         /* check_call_signature () requires sp[0] to be set */
10221                         this_ins.type = STACK_OBJ;
10222                         sp [0] = &this_ins;
10223                         if (check_call_signature (cfg, fsig, sp))
10224                                 UNVERIFIED;
10225
10226                         iargs [0] = NULL;
10227
10228                         if (mini_class_is_system_array (cmethod->klass)) {
10229                                 *sp = emit_get_rgctx_method (cfg, context_used,
10230                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10231
10232                                 /* Avoid varargs in the common case */
10233                                 if (fsig->param_count == 1)
10234                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10235                                 else if (fsig->param_count == 2)
10236                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10237                                 else if (fsig->param_count == 3)
10238                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10239                                 else if (fsig->param_count == 4)
10240                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10241                                 else
10242                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10243                         } else if (cmethod->string_ctor) {
10244                                 g_assert (!context_used);
10245                                 g_assert (!vtable_arg);
10246                                 /* we simply pass a null pointer */
10247                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10248                                 /* now call the string ctor */
10249                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10250                         } else {
10251                                 if (cmethod->klass->valuetype) {
10252                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10253                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10254                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10255
10256                                         alloc = NULL;
10257
10258                                         /* 
10259                                          * The code generated by mini_emit_virtual_call () expects
10260                                          * iargs [0] to be a boxed instance, but luckily the vcall
10261                                          * will be transformed into a normal call there.
10262                                          */
10263                                 } else if (context_used) {
10264                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10265                                         *sp = alloc;
10266                                 } else {
10267                                         MonoVTable *vtable = NULL;
10268
10269                                         if (!cfg->compile_aot)
10270                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10271                                         CHECK_TYPELOAD (cmethod->klass);
10272
10273                                         /*
10274                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10275                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10276                                          * As a workaround, we call class cctors before allocating objects.
10277                                          */
10278                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10279                                                 emit_class_init (cfg, cmethod->klass);
10280                                                 if (cfg->verbose_level > 2)
10281                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10282                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10283                                         }
10284
10285                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10286                                         *sp = alloc;
10287                                 }
10288                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10289
10290                                 if (alloc)
10291                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10292
10293                                 /* Now call the actual ctor */
10294                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10295                                 CHECK_CFG_EXCEPTION;
10296                         }
10297
10298                         if (alloc == NULL) {
10299                                 /* Valuetype */
10300                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10301                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10302                                 *sp++= ins;
10303                         } else {
10304                                 *sp++ = alloc;
10305                         }
10306                         
10307                         ip += 5;
10308                         inline_costs += 5;
10309                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10310                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10311                         break;
10312                 }
10313                 case CEE_CASTCLASS:
10314                 case CEE_ISINST: {
10315                         CHECK_STACK (1);
10316                         --sp;
10317                         CHECK_OPSIZE (5);
10318                         token = read32 (ip + 1);
10319                         klass = mini_get_class (method, token, generic_context);
10320                         CHECK_TYPELOAD (klass);
10321                         if (sp [0]->type != STACK_OBJ)
10322                                 UNVERIFIED;
10323
10324                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
10325                         ins->dreg = alloc_preg (cfg);
10326                         ins->sreg1 = (*sp)->dreg;
10327                         ins->klass = klass;
10328                         ins->type = STACK_OBJ;
10329                         MONO_ADD_INS (cfg->cbb, ins);
10330
10331                         CHECK_CFG_EXCEPTION;
10332                         *sp++ = ins;
10333                         ip += 5;
10334
10335                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10336                         break;
10337                 }
10338                 case CEE_UNBOX_ANY: {
10339                         MonoInst *res, *addr;
10340
10341                         CHECK_STACK (1);
10342                         --sp;
10343                         CHECK_OPSIZE (5);
10344                         token = read32 (ip + 1);
10345                         klass = mini_get_class (method, token, generic_context);
10346                         CHECK_TYPELOAD (klass);
10347
10348                         mono_save_token_info (cfg, image, token, klass);
10349
10350                         context_used = mini_class_check_context_used (cfg, klass);
10351
10352                         if (mini_is_gsharedvt_klass (klass)) {
10353                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10354                                 inline_costs += 2;
10355                         } else if (generic_class_is_reference_type (cfg, klass)) {
10356                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10357                                         EMIT_NEW_PCONST (cfg, res, NULL);
10358                                         res->type = STACK_OBJ;
10359                                 } else {
10360                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10361                                         res->dreg = alloc_preg (cfg);
10362                                         res->sreg1 = (*sp)->dreg;
10363                                         res->klass = klass;
10364                                         res->type = STACK_OBJ;
10365                                         MONO_ADD_INS (cfg->cbb, res);
10366                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10367                                 }
10368                         } else if (mono_class_is_nullable (klass)) {
10369                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10370                         } else {
10371                                 addr = handle_unbox (cfg, klass, sp, context_used);
10372                                 /* LDOBJ */
10373                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10374                                 res = ins;
10375                                 inline_costs += 2;
10376                         }
10377
10378                         *sp ++ = res;
10379                         ip += 5;
10380                         break;
10381                 }
10382                 case CEE_BOX: {
10383                         MonoInst *val;
10384                         MonoClass *enum_class;
10385                         MonoMethod *has_flag;
10386
10387                         CHECK_STACK (1);
10388                         --sp;
10389                         val = *sp;
10390                         CHECK_OPSIZE (5);
10391                         token = read32 (ip + 1);
10392                         klass = mini_get_class (method, token, generic_context);
10393                         CHECK_TYPELOAD (klass);
10394
10395                         mono_save_token_info (cfg, image, token, klass);
10396
10397                         context_used = mini_class_check_context_used (cfg, klass);
10398
10399                         if (generic_class_is_reference_type (cfg, klass)) {
10400                                 *sp++ = val;
10401                                 ip += 5;
10402                                 break;
10403                         }
10404
10405                         if (klass == mono_defaults.void_class)
10406                                 UNVERIFIED;
10407                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10408                                 UNVERIFIED;
10409                         /* frequent check in generic code: box (struct), brtrue */
10410
10411                         /*
10412                          * Look for:
10413                          *
10414                          *   <push int/long ptr>
10415                          *   <push int/long>
10416                          *   box MyFlags
10417                          *   constrained. MyFlags
10418                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10419                          *
10420                          * If we find this sequence and the operand types on box and constrained
10421                          * are equal, we can emit a specialized instruction sequence instead of
10422                          * the very slow HasFlag () call.
10423                          */
10424                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10425                             /* Cheap checks first. */
10426                             ip + 5 + 6 + 5 < end &&
10427                             ip [5] == CEE_PREFIX1 &&
10428                             ip [6] == CEE_CONSTRAINED_ &&
10429                             ip [11] == CEE_CALLVIRT &&
10430                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10431                             mono_class_is_enum (klass) &&
10432                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10433                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10434                             has_flag->klass == mono_defaults.enum_class &&
10435                             !strcmp (has_flag->name, "HasFlag") &&
10436                             has_flag->signature->hasthis &&
10437                             has_flag->signature->param_count == 1) {
10438                                 CHECK_TYPELOAD (enum_class);
10439
10440                                 if (enum_class == klass) {
10441                                         MonoInst *enum_this, *enum_flag;
10442
10443                                         ip += 5 + 6 + 5;
10444                                         --sp;
10445
10446                                         enum_this = sp [0];
10447                                         enum_flag = sp [1];
10448
10449                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10450                                         break;
10451                                 }
10452                         }
10453
10454                         // FIXME: LLVM can't handle the inconsistent bb linking
10455                         if (!mono_class_is_nullable (klass) &&
10456                                 !mini_is_gsharedvt_klass (klass) &&
10457                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10458                                 (ip [5] == CEE_BRTRUE || 
10459                                  ip [5] == CEE_BRTRUE_S ||
10460                                  ip [5] == CEE_BRFALSE ||
10461                                  ip [5] == CEE_BRFALSE_S)) {
10462                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10463                                 int dreg;
10464                                 MonoBasicBlock *true_bb, *false_bb;
10465
10466                                 ip += 5;
10467
10468                                 if (cfg->verbose_level > 3) {
10469                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10470                                         printf ("<box+brtrue opt>\n");
10471                                 }
10472
10473                                 switch (*ip) {
10474                                 case CEE_BRTRUE_S:
10475                                 case CEE_BRFALSE_S:
10476                                         CHECK_OPSIZE (2);
10477                                         ip++;
10478                                         target = ip + 1 + (signed char)(*ip);
10479                                         ip++;
10480                                         break;
10481                                 case CEE_BRTRUE:
10482                                 case CEE_BRFALSE:
10483                                         CHECK_OPSIZE (5);
10484                                         ip++;
10485                                         target = ip + 4 + (gint)(read32 (ip));
10486                                         ip += 4;
10487                                         break;
10488                                 default:
10489                                         g_assert_not_reached ();
10490                                 }
10491
10492                                 /* 
10493                                  * We need to link both bblocks, since it is needed for handling stack
10494                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10495                                  * Branching to only one of them would lead to inconsistencies, so
10496                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10497                                  */
10498                                 GET_BBLOCK (cfg, true_bb, target);
10499                                 GET_BBLOCK (cfg, false_bb, ip);
10500
10501                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10502                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10503
10504                                 if (sp != stack_start) {
10505                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10506                                         sp = stack_start;
10507                                         CHECK_UNVERIFIABLE (cfg);
10508                                 }
10509
10510                                 if (COMPILE_LLVM (cfg)) {
10511                                         dreg = alloc_ireg (cfg);
10512                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10513                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10514
10515                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10516                                 } else {
10517                                         /* The JIT can't eliminate the iconst+compare */
10518                                         MONO_INST_NEW (cfg, ins, OP_BR);
10519                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10520                                         MONO_ADD_INS (cfg->cbb, ins);
10521                                 }
10522
10523                                 start_new_bblock = 1;
10524                                 break;
10525                         }
10526
10527                         *sp++ = handle_box (cfg, val, klass, context_used);
10528
10529                         CHECK_CFG_EXCEPTION;
10530                         ip += 5;
10531                         inline_costs += 1;
10532                         break;
10533                 }
10534                 case CEE_UNBOX: {
10535                         CHECK_STACK (1);
10536                         --sp;
10537                         CHECK_OPSIZE (5);
10538                         token = read32 (ip + 1);
10539                         klass = mini_get_class (method, token, generic_context);
10540                         CHECK_TYPELOAD (klass);
10541
10542                         mono_save_token_info (cfg, image, token, klass);
10543
10544                         context_used = mini_class_check_context_used (cfg, klass);
10545
10546                         if (mono_class_is_nullable (klass)) {
10547                                 MonoInst *val;
10548
10549                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10550                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10551
10552                                 *sp++= ins;
10553                         } else {
10554                                 ins = handle_unbox (cfg, klass, sp, context_used);
10555                                 *sp++ = ins;
10556                         }
10557                         ip += 5;
10558                         inline_costs += 2;
10559                         break;
10560                 }
10561                 case CEE_LDFLD:
10562                 case CEE_LDFLDA:
10563                 case CEE_STFLD:
10564                 case CEE_LDSFLD:
10565                 case CEE_LDSFLDA:
10566                 case CEE_STSFLD: {
10567                         MonoClassField *field;
10568 #ifndef DISABLE_REMOTING
10569                         int costs;
10570 #endif
10571                         guint foffset;
10572                         gboolean is_instance;
10573                         int op;
10574                         gpointer addr = NULL;
10575                         gboolean is_special_static;
10576                         MonoType *ftype;
10577                         MonoInst *store_val = NULL;
10578                         MonoInst *thread_ins;
10579
10580                         op = *ip;
10581                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10582                         if (is_instance) {
10583                                 if (op == CEE_STFLD) {
10584                                         CHECK_STACK (2);
10585                                         sp -= 2;
10586                                         store_val = sp [1];
10587                                 } else {
10588                                         CHECK_STACK (1);
10589                                         --sp;
10590                                 }
10591                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10592                                         UNVERIFIED;
10593                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10594                                         UNVERIFIED;
10595                         } else {
10596                                 if (op == CEE_STSFLD) {
10597                                         CHECK_STACK (1);
10598                                         sp--;
10599                                         store_val = sp [0];
10600                                 }
10601                         }
10602
10603                         CHECK_OPSIZE (5);
10604                         token = read32 (ip + 1);
10605                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10606                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10607                                 klass = field->parent;
10608                         }
10609                         else {
10610                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10611                                 CHECK_CFG_ERROR;
10612                         }
10613                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10614                                 FIELD_ACCESS_FAILURE (method, field);
10615                         mono_class_init (klass);
10616
10617                         /* if the class is Critical then transparent code cannot access it's fields */
10618                         if (!is_instance && mono_security_core_clr_enabled ())
10619                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10620
10621                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10622                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10623                         if (mono_security_core_clr_enabled ())
10624                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10625                         */
10626
10627                         ftype = mono_field_get_type (field);
10628
10629                         /*
10630                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10631                          * the static case.
10632                          */
10633                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10634                                 switch (op) {
10635                                 case CEE_LDFLD:
10636                                         op = CEE_LDSFLD;
10637                                         break;
10638                                 case CEE_STFLD:
10639                                         op = CEE_STSFLD;
10640                                         break;
10641                                 case CEE_LDFLDA:
10642                                         op = CEE_LDSFLDA;
10643                                         break;
10644                                 default:
10645                                         g_assert_not_reached ();
10646                                 }
10647                                 is_instance = FALSE;
10648                         }
10649
10650                         context_used = mini_class_check_context_used (cfg, klass);
10651
10652                         /* INSTANCE CASE */
10653
10654                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10655                         if (op == CEE_STFLD) {
10656                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10657                                         UNVERIFIED;
10658 #ifndef DISABLE_REMOTING
10659                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10660                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10661                                         MonoInst *iargs [5];
10662
10663                                         GSHAREDVT_FAILURE (op);
10664
10665                                         iargs [0] = sp [0];
10666                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10667                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10668                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10669                                                     field->offset);
10670                                         iargs [4] = sp [1];
10671
10672                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10673                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10674                                                                                            iargs, ip, cfg->real_offset, TRUE);
10675                                                 CHECK_CFG_EXCEPTION;
10676                                                 g_assert (costs > 0);
10677                                                       
10678                                                 cfg->real_offset += 5;
10679
10680                                                 inline_costs += costs;
10681                                         } else {
10682                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10683                                         }
10684                                 } else
10685 #endif
10686                                 {
10687                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10688
10689                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10690
10691                                         if (ins_flag & MONO_INST_VOLATILE) {
10692                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10693                                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10694                                         }
10695
10696                                         if (mini_is_gsharedvt_klass (klass)) {
10697                                                 MonoInst *offset_ins;
10698
10699                                                 context_used = mini_class_check_context_used (cfg, klass);
10700
10701                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10702                                                 /* The value is offset by 1 */
10703                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10704                                                 dreg = alloc_ireg_mp (cfg);
10705                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10706                                                 wbarrier_ptr_ins = ins;
10707                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
10708                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10709                                         } else {
10710                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10711                                         }
10712                                         if (sp [0]->opcode != OP_LDADDR)
10713                                                 store->flags |= MONO_INST_FAULT;
10714
10715                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10716                                                 if (mini_is_gsharedvt_klass (klass)) {
10717                                                         g_assert (wbarrier_ptr_ins);
10718                                                         emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10719                                                 } else {
10720                                                         /* insert call to write barrier */
10721                                                         MonoInst *ptr;
10722                                                         int dreg;
10723
10724                                                         dreg = alloc_ireg_mp (cfg);
10725                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10726                                                         emit_write_barrier (cfg, ptr, sp [1]);
10727                                                 }
10728                                         }
10729
10730                                         store->flags |= ins_flag;
10731                                 }
10732                                 ins_flag = 0;
10733                                 ip += 5;
10734                                 break;
10735                         }
10736
10737 #ifndef DISABLE_REMOTING
10738                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10739                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10740                                 MonoInst *iargs [4];
10741
10742                                 GSHAREDVT_FAILURE (op);
10743
10744                                 iargs [0] = sp [0];
10745                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10746                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10747                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10748                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10749                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10750                                                                                    iargs, ip, cfg->real_offset, TRUE);
10751                                         CHECK_CFG_EXCEPTION;
10752                                         g_assert (costs > 0);
10753                                                       
10754                                         cfg->real_offset += 5;
10755
10756                                         *sp++ = iargs [0];
10757
10758                                         inline_costs += costs;
10759                                 } else {
10760                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10761                                         *sp++ = ins;
10762                                 }
10763                         } else 
10764 #endif
10765                         if (is_instance) {
10766                                 if (sp [0]->type == STACK_VTYPE) {
10767                                         MonoInst *var;
10768
10769                                         /* Have to compute the address of the variable */
10770
10771                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10772                                         if (!var)
10773                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10774                                         else
10775                                                 g_assert (var->klass == klass);
10776                                         
10777                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10778                                         sp [0] = ins;
10779                                 }
10780
10781                                 if (op == CEE_LDFLDA) {
10782                                         if (sp [0]->type == STACK_OBJ) {
10783                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10784                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10785                                         }
10786
10787                                         dreg = alloc_ireg_mp (cfg);
10788
10789                                         if (mini_is_gsharedvt_klass (klass)) {
10790                                                 MonoInst *offset_ins;
10791
10792                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10793                                                 /* The value is offset by 1 */
10794                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10795                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10796                                         } else {
10797                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10798                                         }
10799                                         ins->klass = mono_class_from_mono_type (field->type);
10800                                         ins->type = STACK_MP;
10801                                         *sp++ = ins;
10802                                 } else {
10803                                         MonoInst *load;
10804
10805                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10806
10807                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10808                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10809                                                 if (ins) {
10810                                                         *sp++ = ins;
10811                                                         ins_flag = 0;
10812                                                         ip += 5;
10813                                                         break;
10814                                                 }
10815                                         }
10816
10817                                         if (mini_is_gsharedvt_klass (klass)) {
10818                                                 MonoInst *offset_ins;
10819
10820                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10821                                                 /* The value is offset by 1 */
10822                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10823                                                 dreg = alloc_ireg_mp (cfg);
10824                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10825                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, dreg, 0);
10826                                         } else {
10827                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, sp [0]->dreg, foffset);
10828                                         }
10829                                         load->flags |= ins_flag;
10830                                         if (sp [0]->opcode != OP_LDADDR)
10831                                                 load->flags |= MONO_INST_FAULT;
10832                                         *sp++ = load;
10833                                 }
10834                         }
10835
10836                         if (is_instance) {
10837                                 ins_flag = 0;
10838                                 ip += 5;
10839                                 break;
10840                         }
10841
10842                         /* STATIC CASE */
10843                         context_used = mini_class_check_context_used (cfg, klass);
10844
10845                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10846                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10847                                 CHECK_CFG_ERROR;
10848                         }
10849
10850                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10851                          * to be called here.
10852                          */
10853                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10854                                 mono_class_vtable (cfg->domain, klass);
10855                                 CHECK_TYPELOAD (klass);
10856                         }
10857                         mono_domain_lock (cfg->domain);
10858                         if (cfg->domain->special_static_fields)
10859                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10860                         mono_domain_unlock (cfg->domain);
10861
10862                         is_special_static = mono_class_field_is_special_static (field);
10863
10864                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10865                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10866                         else
10867                                 thread_ins = NULL;
10868
10869                         /* Generate IR to compute the field address */
10870                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10871                                 /*
10872                                  * Fast access to TLS data
10873                                  * Inline version of get_thread_static_data () in
10874                                  * threads.c.
10875                                  */
10876                                 guint32 offset;
10877                                 int idx, static_data_reg, array_reg, dreg;
10878
10879                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10880                                         GSHAREDVT_FAILURE (op);
10881
10882                                 static_data_reg = alloc_ireg (cfg);
10883                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10884
10885                                 if (cfg->compile_aot) {
10886                                         int offset_reg, offset2_reg, idx_reg;
10887
10888                                         /* For TLS variables, this will return the TLS offset */
10889                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10890                                         offset_reg = ins->dreg;
10891                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10892                                         idx_reg = alloc_ireg (cfg);
10893                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10894                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10895                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10896                                         array_reg = alloc_ireg (cfg);
10897                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10898                                         offset2_reg = alloc_ireg (cfg);
10899                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10900                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10901                                         dreg = alloc_ireg (cfg);
10902                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10903                                 } else {
10904                                         offset = (gsize)addr & 0x7fffffff;
10905                                         idx = offset & 0x3f;
10906
10907                                         array_reg = alloc_ireg (cfg);
10908                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10909                                         dreg = alloc_ireg (cfg);
10910                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10911                                 }
10912                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10913                                         (cfg->compile_aot && is_special_static) ||
10914                                         (context_used && is_special_static)) {
10915                                 MonoInst *iargs [2];
10916
10917                                 g_assert (field->parent);
10918                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10919                                 if (context_used) {
10920                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10921                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10922                                 } else {
10923                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10924                                 }
10925                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10926                         } else if (context_used) {
10927                                 MonoInst *static_data;
10928
10929                                 /*
10930                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10931                                         method->klass->name_space, method->klass->name, method->name,
10932                                         depth, field->offset);
10933                                 */
10934
10935                                 if (mono_class_needs_cctor_run (klass, method))
10936                                         emit_class_init (cfg, klass);
10937
10938                                 /*
10939                                  * The pointer we're computing here is
10940                                  *
10941                                  *   super_info.static_data + field->offset
10942                                  */
10943                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10944                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10945
10946                                 if (mini_is_gsharedvt_klass (klass)) {
10947                                         MonoInst *offset_ins;
10948
10949                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10950                                         /* The value is offset by 1 */
10951                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10952                                         dreg = alloc_ireg_mp (cfg);
10953                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10954                                 } else if (field->offset == 0) {
10955                                         ins = static_data;
10956                                 } else {
10957                                         int addr_reg = mono_alloc_preg (cfg);
10958                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10959                                 }
10960                                 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10961                                 MonoInst *iargs [2];
10962
10963                                 g_assert (field->parent);
10964                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10965                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10966                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10967                         } else {
10968                                 MonoVTable *vtable = NULL;
10969
10970                                 if (!cfg->compile_aot)
10971                                         vtable = mono_class_vtable (cfg->domain, klass);
10972                                 CHECK_TYPELOAD (klass);
10973
10974                                 if (!addr) {
10975                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10976                                                 if (!(g_slist_find (class_inits, klass))) {
10977                                                         emit_class_init (cfg, klass);
10978                                                         if (cfg->verbose_level > 2)
10979                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10980                                                         class_inits = g_slist_prepend (class_inits, klass);
10981                                                 }
10982                                         } else {
10983                                                 if (cfg->run_cctors) {
10984                                                         /* This makes so that inline cannot trigger */
10985                                                         /* .cctors: too many apps depend on them */
10986                                                         /* running with a specific order... */
10987                                                         g_assert (vtable);
10988                                                         if (! vtable->initialized)
10989                                                                 INLINE_FAILURE ("class init");
10990                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10991                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10992                                                                 goto exception_exit;
10993                                                         }
10994                                                 }
10995                                         }
10996                                         if (cfg->compile_aot)
10997                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10998                                         else {
10999                                                 g_assert (vtable);
11000                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11001                                                 g_assert (addr);
11002                                                 EMIT_NEW_PCONST (cfg, ins, addr);
11003                                         }
11004                                 } else {
11005                                         MonoInst *iargs [1];
11006                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
11007                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
11008                                 }
11009                         }
11010
11011                         /* Generate IR to do the actual load/store operation */
11012
11013                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11014                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11015                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11016                         }
11017
11018                         if (op == CEE_LDSFLDA) {
11019                                 ins->klass = mono_class_from_mono_type (ftype);
11020                                 ins->type = STACK_PTR;
11021                                 *sp++ = ins;
11022                         } else if (op == CEE_STSFLD) {
11023                                 MonoInst *store;
11024
11025                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
11026                                 store->flags |= ins_flag;
11027                         } else {
11028                                 gboolean is_const = FALSE;
11029                                 MonoVTable *vtable = NULL;
11030                                 gpointer addr = NULL;
11031
11032                                 if (!context_used) {
11033                                         vtable = mono_class_vtable (cfg->domain, klass);
11034                                         CHECK_TYPELOAD (klass);
11035                                 }
11036                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
11037                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
11038                                         int ro_type = ftype->type;
11039                                         if (!addr)
11040                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11041                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
11042                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
11043                                         }
11044
11045                                         GSHAREDVT_FAILURE (op);
11046
11047                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
11048                                         is_const = TRUE;
11049                                         switch (ro_type) {
11050                                         case MONO_TYPE_BOOLEAN:
11051                                         case MONO_TYPE_U1:
11052                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
11053                                                 sp++;
11054                                                 break;
11055                                         case MONO_TYPE_I1:
11056                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
11057                                                 sp++;
11058                                                 break;                                          
11059                                         case MONO_TYPE_CHAR:
11060                                         case MONO_TYPE_U2:
11061                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
11062                                                 sp++;
11063                                                 break;
11064                                         case MONO_TYPE_I2:
11065                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
11066                                                 sp++;
11067                                                 break;
11068                                                 break;
11069                                         case MONO_TYPE_I4:
11070                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
11071                                                 sp++;
11072                                                 break;                                          
11073                                         case MONO_TYPE_U4:
11074                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
11075                                                 sp++;
11076                                                 break;
11077                                         case MONO_TYPE_I:
11078                                         case MONO_TYPE_U:
11079                                         case MONO_TYPE_PTR:
11080                                         case MONO_TYPE_FNPTR:
11081                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11082                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
11083                                                 sp++;
11084                                                 break;
11085                                         case MONO_TYPE_STRING:
11086                                         case MONO_TYPE_OBJECT:
11087                                         case MONO_TYPE_CLASS:
11088                                         case MONO_TYPE_SZARRAY:
11089                                         case MONO_TYPE_ARRAY:
11090                                                 if (!mono_gc_is_moving ()) {
11091                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11092                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
11093                                                         sp++;
11094                                                 } else {
11095                                                         is_const = FALSE;
11096                                                 }
11097                                                 break;
11098                                         case MONO_TYPE_I8:
11099                                         case MONO_TYPE_U8:
11100                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
11101                                                 sp++;
11102                                                 break;
11103                                         case MONO_TYPE_R4:
11104                                         case MONO_TYPE_R8:
11105                                         case MONO_TYPE_VALUETYPE:
11106                                         default:
11107                                                 is_const = FALSE;
11108                                                 break;
11109                                         }
11110                                 }
11111
11112                                 if (!is_const) {
11113                                         MonoInst *load;
11114
11115                                         CHECK_STACK_OVF (1);
11116
11117                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
11118                                         load->flags |= ins_flag;
11119                                         ins_flag = 0;
11120                                         *sp++ = load;
11121                                 }
11122                         }
11123
11124                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11125                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11126                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11127                         }
11128
11129                         ins_flag = 0;
11130                         ip += 5;
11131                         break;
11132                 }
11133                 case CEE_STOBJ:
11134                         CHECK_STACK (2);
11135                         sp -= 2;
11136                         CHECK_OPSIZE (5);
11137                         token = read32 (ip + 1);
11138                         klass = mini_get_class (method, token, generic_context);
11139                         CHECK_TYPELOAD (klass);
11140                         if (ins_flag & MONO_INST_VOLATILE) {
11141                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11142                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11143                         }
11144                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11145                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
11146                         ins->flags |= ins_flag;
11147                         if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
11148                                 generic_class_is_reference_type (cfg, klass) && !MONO_INS_IS_PCONST_NULL (sp [1])) {
11149                                 /* insert call to write barrier */
11150                                 emit_write_barrier (cfg, sp [0], sp [1]);
11151                         }
11152                         ins_flag = 0;
11153                         ip += 5;
11154                         inline_costs += 1;
11155                         break;
11156
11157                         /*
11158                          * Array opcodes
11159                          */
11160                 case CEE_NEWARR: {
11161                         MonoInst *len_ins;
11162                         const char *data_ptr;
11163                         int data_size = 0;
11164                         guint32 field_token;
11165
11166                         CHECK_STACK (1);
11167                         --sp;
11168
11169                         CHECK_OPSIZE (5);
11170                         token = read32 (ip + 1);
11171
11172                         klass = mini_get_class (method, token, generic_context);
11173                         CHECK_TYPELOAD (klass);
11174
11175                         context_used = mini_class_check_context_used (cfg, klass);
11176
11177                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11178                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11179                                 ins->sreg1 = sp [0]->dreg;
11180                                 ins->type = STACK_I4;
11181                                 ins->dreg = alloc_ireg (cfg);
11182                                 MONO_ADD_INS (cfg->cbb, ins);
11183                                 *sp = mono_decompose_opcode (cfg, ins);
11184                         }
11185
11186                         if (context_used) {
11187                                 MonoInst *args [3];
11188                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11189                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11190
11191                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11192
11193                                 /* vtable */
11194                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
11195                                         array_class, MONO_RGCTX_INFO_VTABLE);
11196                                 /* array len */
11197                                 args [1] = sp [0];
11198
11199                                 if (managed_alloc)
11200                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11201                                 else
11202                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11203                         } else {
11204                                 if (cfg->opt & MONO_OPT_SHARED) {
11205                                         /* Decompose now to avoid problems with references to the domainvar */
11206                                         MonoInst *iargs [3];
11207
11208                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11209                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11210                                         iargs [2] = sp [0];
11211
11212                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11213                                 } else {
11214                                         /* Decompose later since it is needed by abcrem */
11215                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11216                                         mono_class_vtable (cfg->domain, array_type);
11217                                         CHECK_TYPELOAD (array_type);
11218
11219                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11220                                         ins->dreg = alloc_ireg_ref (cfg);
11221                                         ins->sreg1 = sp [0]->dreg;
11222                                         ins->inst_newa_class = klass;
11223                                         ins->type = STACK_OBJ;
11224                                         ins->klass = array_type;
11225                                         MONO_ADD_INS (cfg->cbb, ins);
11226                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11227                                         cfg->cbb->has_array_access = TRUE;
11228
11229                                         /* Needed so mono_emit_load_get_addr () gets called */
11230                                         mono_get_got_var (cfg);
11231                                 }
11232                         }
11233
11234                         len_ins = sp [0];
11235                         ip += 5;
11236                         *sp++ = ins;
11237                         inline_costs += 1;
11238
11239                         /* 
11240                          * we inline/optimize the initialization sequence if possible.
11241                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11242                          * for small sizes open code the memcpy
11243                          * ensure the rva field is big enough
11244                          */
11245                         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))) {
11246                                 MonoMethod *memcpy_method = get_memcpy_method ();
11247                                 MonoInst *iargs [3];
11248                                 int add_reg = alloc_ireg_mp (cfg);
11249
11250                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11251                                 if (cfg->compile_aot) {
11252                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11253                                 } else {
11254                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11255                                 }
11256                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11257                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11258                                 ip += 11;
11259                         }
11260
11261                         break;
11262                 }
11263                 case CEE_LDLEN:
11264                         CHECK_STACK (1);
11265                         --sp;
11266                         if (sp [0]->type != STACK_OBJ)
11267                                 UNVERIFIED;
11268
11269                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11270                         ins->dreg = alloc_preg (cfg);
11271                         ins->sreg1 = sp [0]->dreg;
11272                         ins->type = STACK_I4;
11273                         /* This flag will be inherited by the decomposition */
11274                         ins->flags |= MONO_INST_FAULT;
11275                         MONO_ADD_INS (cfg->cbb, ins);
11276                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11277                         cfg->cbb->has_array_access = TRUE;
11278                         ip ++;
11279                         *sp++ = ins;
11280                         break;
11281                 case CEE_LDELEMA:
11282                         CHECK_STACK (2);
11283                         sp -= 2;
11284                         CHECK_OPSIZE (5);
11285                         if (sp [0]->type != STACK_OBJ)
11286                                 UNVERIFIED;
11287
11288                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11289
11290                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11291                         CHECK_TYPELOAD (klass);
11292                         /* we need to make sure that this array is exactly the type it needs
11293                          * to be for correctness. the wrappers are lax with their usage
11294                          * so we need to ignore them here
11295                          */
11296                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11297                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11298                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11299                                 CHECK_TYPELOAD (array_class);
11300                         }
11301
11302                         readonly = FALSE;
11303                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11304                         *sp++ = ins;
11305                         ip += 5;
11306                         break;
11307                 case CEE_LDELEM:
11308                 case CEE_LDELEM_I1:
11309                 case CEE_LDELEM_U1:
11310                 case CEE_LDELEM_I2:
11311                 case CEE_LDELEM_U2:
11312                 case CEE_LDELEM_I4:
11313                 case CEE_LDELEM_U4:
11314                 case CEE_LDELEM_I8:
11315                 case CEE_LDELEM_I:
11316                 case CEE_LDELEM_R4:
11317                 case CEE_LDELEM_R8:
11318                 case CEE_LDELEM_REF: {
11319                         MonoInst *addr;
11320
11321                         CHECK_STACK (2);
11322                         sp -= 2;
11323
11324                         if (*ip == CEE_LDELEM) {
11325                                 CHECK_OPSIZE (5);
11326                                 token = read32 (ip + 1);
11327                                 klass = mini_get_class (method, token, generic_context);
11328                                 CHECK_TYPELOAD (klass);
11329                                 mono_class_init (klass);
11330                         }
11331                         else
11332                                 klass = array_access_to_klass (*ip);
11333
11334                         if (sp [0]->type != STACK_OBJ)
11335                                 UNVERIFIED;
11336
11337                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11338
11339                         if (mini_is_gsharedvt_variable_klass (klass)) {
11340                                 // FIXME-VT: OP_ICONST optimization
11341                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11342                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11343                                 ins->opcode = OP_LOADV_MEMBASE;
11344                         } else if (sp [1]->opcode == OP_ICONST) {
11345                                 int array_reg = sp [0]->dreg;
11346                                 int index_reg = sp [1]->dreg;
11347                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11348
11349                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11350                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11351
11352                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11353                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11354                         } else {
11355                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11356                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11357                         }
11358                         *sp++ = ins;
11359                         if (*ip == CEE_LDELEM)
11360                                 ip += 5;
11361                         else
11362                                 ++ip;
11363                         break;
11364                 }
11365                 case CEE_STELEM_I:
11366                 case CEE_STELEM_I1:
11367                 case CEE_STELEM_I2:
11368                 case CEE_STELEM_I4:
11369                 case CEE_STELEM_I8:
11370                 case CEE_STELEM_R4:
11371                 case CEE_STELEM_R8:
11372                 case CEE_STELEM_REF:
11373                 case CEE_STELEM: {
11374                         CHECK_STACK (3);
11375                         sp -= 3;
11376
11377                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11378
11379                         if (*ip == CEE_STELEM) {
11380                                 CHECK_OPSIZE (5);
11381                                 token = read32 (ip + 1);
11382                                 klass = mini_get_class (method, token, generic_context);
11383                                 CHECK_TYPELOAD (klass);
11384                                 mono_class_init (klass);
11385                         }
11386                         else
11387                                 klass = array_access_to_klass (*ip);
11388
11389                         if (sp [0]->type != STACK_OBJ)
11390                                 UNVERIFIED;
11391
11392                         emit_array_store (cfg, klass, sp, TRUE);
11393
11394                         if (*ip == CEE_STELEM)
11395                                 ip += 5;
11396                         else
11397                                 ++ip;
11398                         inline_costs += 1;
11399                         break;
11400                 }
11401                 case CEE_CKFINITE: {
11402                         CHECK_STACK (1);
11403                         --sp;
11404
11405                         if (cfg->llvm_only) {
11406                                 MonoInst *iargs [1];
11407
11408                                 iargs [0] = sp [0];
11409                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11410                         } else  {
11411                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11412                                 ins->sreg1 = sp [0]->dreg;
11413                                 ins->dreg = alloc_freg (cfg);
11414                                 ins->type = STACK_R8;
11415                                 MONO_ADD_INS (cfg->cbb, ins);
11416
11417                                 *sp++ = mono_decompose_opcode (cfg, ins);
11418                         }
11419
11420                         ++ip;
11421                         break;
11422                 }
11423                 case CEE_REFANYVAL: {
11424                         MonoInst *src_var, *src;
11425
11426                         int klass_reg = alloc_preg (cfg);
11427                         int dreg = alloc_preg (cfg);
11428
11429                         GSHAREDVT_FAILURE (*ip);
11430
11431                         CHECK_STACK (1);
11432                         MONO_INST_NEW (cfg, ins, *ip);
11433                         --sp;
11434                         CHECK_OPSIZE (5);
11435                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11436                         CHECK_TYPELOAD (klass);
11437
11438                         context_used = mini_class_check_context_used (cfg, klass);
11439
11440                         // FIXME:
11441                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11442                         if (!src_var)
11443                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11444                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11445                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11446
11447                         if (context_used) {
11448                                 MonoInst *klass_ins;
11449
11450                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11451                                                 klass, MONO_RGCTX_INFO_KLASS);
11452
11453                                 // FIXME:
11454                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11455                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11456                         } else {
11457                                 mini_emit_class_check (cfg, klass_reg, klass);
11458                         }
11459                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11460                         ins->type = STACK_MP;
11461                         ins->klass = klass;
11462                         *sp++ = ins;
11463                         ip += 5;
11464                         break;
11465                 }
11466                 case CEE_MKREFANY: {
11467                         MonoInst *loc, *addr;
11468
11469                         GSHAREDVT_FAILURE (*ip);
11470
11471                         CHECK_STACK (1);
11472                         MONO_INST_NEW (cfg, ins, *ip);
11473                         --sp;
11474                         CHECK_OPSIZE (5);
11475                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11476                         CHECK_TYPELOAD (klass);
11477
11478                         context_used = mini_class_check_context_used (cfg, klass);
11479
11480                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11481                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11482
11483                         if (context_used) {
11484                                 MonoInst *const_ins;
11485                                 int type_reg = alloc_preg (cfg);
11486
11487                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11488                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11489                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11490                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11491                         } else {
11492                                 int const_reg = alloc_preg (cfg);
11493                                 int type_reg = alloc_preg (cfg);
11494
11495                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11496                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11497                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11498                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11499                         }
11500                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11501
11502                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11503                         ins->type = STACK_VTYPE;
11504                         ins->klass = mono_defaults.typed_reference_class;
11505                         *sp++ = ins;
11506                         ip += 5;
11507                         break;
11508                 }
11509                 case CEE_LDTOKEN: {
11510                         gpointer handle;
11511                         MonoClass *handle_class;
11512
11513                         CHECK_STACK_OVF (1);
11514
11515                         CHECK_OPSIZE (5);
11516                         n = read32 (ip + 1);
11517
11518                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11519                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11520                                 handle = mono_method_get_wrapper_data (method, n);
11521                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11522                                 if (handle_class == mono_defaults.typehandle_class)
11523                                         handle = &((MonoClass*)handle)->byval_arg;
11524                         }
11525                         else {
11526                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11527                                 CHECK_CFG_ERROR;
11528                         }
11529                         if (!handle)
11530                                 LOAD_ERROR;
11531                         mono_class_init (handle_class);
11532                         if (cfg->gshared) {
11533                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11534                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11535                                         /* This case handles ldtoken
11536                                            of an open type, like for
11537                                            typeof(Gen<>). */
11538                                         context_used = 0;
11539                                 } else if (handle_class == mono_defaults.typehandle_class) {
11540                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11541                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11542                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11543                                 else if (handle_class == mono_defaults.methodhandle_class)
11544                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11545                                 else
11546                                         g_assert_not_reached ();
11547                         }
11548
11549                         if ((cfg->opt & MONO_OPT_SHARED) &&
11550                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11551                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11552                                 MonoInst *addr, *vtvar, *iargs [3];
11553                                 int method_context_used;
11554
11555                                 method_context_used = mini_method_check_context_used (cfg, method);
11556
11557                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11558
11559                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11560                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11561                                 if (method_context_used) {
11562                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11563                                                 method, MONO_RGCTX_INFO_METHOD);
11564                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11565                                 } else {
11566                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11567                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11568                                 }
11569                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11570
11571                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11572
11573                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11574                         } else {
11575                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11576                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11577                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11578                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11579                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11580                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11581
11582                                         mono_class_init (tclass);
11583                                         if (context_used) {
11584                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11585                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11586                                         } else if (cfg->compile_aot) {
11587                                                 if (method->wrapper_type) {
11588                                                         mono_error_init (&error); //got to do it since there are multiple conditionals below
11589                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11590                                                                 /* Special case for static synchronized wrappers */
11591                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11592                                                         } else {
11593                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11594                                                                 /* FIXME: n is not a normal token */
11595                                                                 DISABLE_AOT (cfg);
11596                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11597                                                         }
11598                                                 } else {
11599                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11600                                                 }
11601                                         } else {
11602                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11603                                                 CHECK_CFG_ERROR;
11604                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11605                                         }
11606                                         ins->type = STACK_OBJ;
11607                                         ins->klass = cmethod->klass;
11608                                         ip += 5;
11609                                 } else {
11610                                         MonoInst *addr, *vtvar;
11611
11612                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11613
11614                                         if (context_used) {
11615                                                 if (handle_class == mono_defaults.typehandle_class) {
11616                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11617                                                                         mono_class_from_mono_type ((MonoType *)handle),
11618                                                                         MONO_RGCTX_INFO_TYPE);
11619                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11620                                                         ins = emit_get_rgctx_method (cfg, context_used,
11621                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11622                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11623                                                         ins = emit_get_rgctx_field (cfg, context_used,
11624                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11625                                                 } else {
11626                                                         g_assert_not_reached ();
11627                                                 }
11628                                         } else if (cfg->compile_aot) {
11629                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11630                                         } else {
11631                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11632                                         }
11633                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11634                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11635                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11636                                 }
11637                         }
11638
11639                         *sp++ = ins;
11640                         ip += 5;
11641                         break;
11642                 }
11643                 case CEE_THROW:
11644                         CHECK_STACK (1);
11645                         if (sp [-1]->type != STACK_OBJ)
11646                                 UNVERIFIED;
11647
11648                         MONO_INST_NEW (cfg, ins, OP_THROW);
11649                         --sp;
11650                         ins->sreg1 = sp [0]->dreg;
11651                         ip++;
11652                         cfg->cbb->out_of_line = TRUE;
11653                         MONO_ADD_INS (cfg->cbb, ins);
11654                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11655                         MONO_ADD_INS (cfg->cbb, ins);
11656                         sp = stack_start;
11657                         
11658                         link_bblock (cfg, cfg->cbb, end_bblock);
11659                         start_new_bblock = 1;
11660                         /* This can complicate code generation for llvm since the return value might not be defined */
11661                         if (COMPILE_LLVM (cfg))
11662                                 INLINE_FAILURE ("throw");
11663                         break;
11664                 case CEE_ENDFINALLY:
11665                         if (!ip_in_finally_clause (cfg, ip - header->code))
11666                                 UNVERIFIED;
11667                         /* mono_save_seq_point_info () depends on this */
11668                         if (sp != stack_start)
11669                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11670                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11671                         MONO_ADD_INS (cfg->cbb, ins);
11672                         ip++;
11673                         start_new_bblock = 1;
11674
11675                         /*
11676                          * Control will leave the method so empty the stack, otherwise
11677                          * the next basic block will start with a nonempty stack.
11678                          */
11679                         while (sp != stack_start) {
11680                                 sp--;
11681                         }
11682                         break;
11683                 case CEE_LEAVE:
11684                 case CEE_LEAVE_S: {
11685                         GList *handlers;
11686
11687                         if (*ip == CEE_LEAVE) {
11688                                 CHECK_OPSIZE (5);
11689                                 target = ip + 5 + (gint32)read32(ip + 1);
11690                         } else {
11691                                 CHECK_OPSIZE (2);
11692                                 target = ip + 2 + (signed char)(ip [1]);
11693                         }
11694
11695                         /* empty the stack */
11696                         while (sp != stack_start) {
11697                                 sp--;
11698                         }
11699
11700                         /* 
11701                          * If this leave statement is in a catch block, check for a
11702                          * pending exception, and rethrow it if necessary.
11703                          * We avoid doing this in runtime invoke wrappers, since those are called
11704                          * by native code which excepts the wrapper to catch all exceptions.
11705                          */
11706                         for (i = 0; i < header->num_clauses; ++i) {
11707                                 MonoExceptionClause *clause = &header->clauses [i];
11708
11709                                 /* 
11710                                  * Use <= in the final comparison to handle clauses with multiple
11711                                  * leave statements, like in bug #78024.
11712                                  * The ordering of the exception clauses guarantees that we find the
11713                                  * innermost clause.
11714                                  */
11715                                 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) {
11716                                         MonoInst *exc_ins;
11717                                         MonoBasicBlock *dont_throw;
11718
11719                                         /*
11720                                           MonoInst *load;
11721
11722                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11723                                         */
11724
11725                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11726
11727                                         NEW_BBLOCK (cfg, dont_throw);
11728
11729                                         /*
11730                                          * Currently, we always rethrow the abort exception, despite the 
11731                                          * fact that this is not correct. See thread6.cs for an example. 
11732                                          * But propagating the abort exception is more important than 
11733                                          * getting the sematics right.
11734                                          */
11735                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11736                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11737                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11738
11739                                         MONO_START_BB (cfg, dont_throw);
11740                                 }
11741                         }
11742
11743 #ifdef ENABLE_LLVM
11744                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11745 #endif
11746
11747                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11748                                 GList *tmp;
11749                                 MonoExceptionClause *clause;
11750
11751                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11752                                         clause = (MonoExceptionClause *)tmp->data;
11753                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11754                                         g_assert (tblock);
11755                                         link_bblock (cfg, cfg->cbb, tblock);
11756                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11757                                         ins->inst_target_bb = tblock;
11758                                         ins->inst_eh_block = clause;
11759                                         MONO_ADD_INS (cfg->cbb, ins);
11760                                         cfg->cbb->has_call_handler = 1;
11761                                         if (COMPILE_LLVM (cfg)) {
11762                                                 MonoBasicBlock *target_bb;
11763
11764                                                 /* 
11765                                                  * Link the finally bblock with the target, since it will
11766                                                  * conceptually branch there.
11767                                                  */
11768                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11769                                                 GET_BBLOCK (cfg, target_bb, target);
11770                                                 link_bblock (cfg, tblock, target_bb);
11771                                         }
11772                                 }
11773                                 g_list_free (handlers);
11774                         } 
11775
11776                         MONO_INST_NEW (cfg, ins, OP_BR);
11777                         MONO_ADD_INS (cfg->cbb, ins);
11778                         GET_BBLOCK (cfg, tblock, target);
11779                         link_bblock (cfg, cfg->cbb, tblock);
11780                         ins->inst_target_bb = tblock;
11781
11782                         start_new_bblock = 1;
11783
11784                         if (*ip == CEE_LEAVE)
11785                                 ip += 5;
11786                         else
11787                                 ip += 2;
11788
11789                         break;
11790                 }
11791
11792                         /*
11793                          * Mono specific opcodes
11794                          */
11795                 case MONO_CUSTOM_PREFIX: {
11796
11797                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11798
11799                         CHECK_OPSIZE (2);
11800                         switch (ip [1]) {
11801                         case CEE_MONO_ICALL: {
11802                                 gpointer func;
11803                                 MonoJitICallInfo *info;
11804
11805                                 token = read32 (ip + 2);
11806                                 func = mono_method_get_wrapper_data (method, token);
11807                                 info = mono_find_jit_icall_by_addr (func);
11808                                 if (!info)
11809                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11810                                 g_assert (info);
11811
11812                                 CHECK_STACK (info->sig->param_count);
11813                                 sp -= info->sig->param_count;
11814
11815                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11816                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11817                                         *sp++ = ins;
11818
11819                                 ip += 6;
11820                                 inline_costs += 10 * num_calls++;
11821
11822                                 break;
11823                         }
11824                         case CEE_MONO_LDPTR_CARD_TABLE:
11825                         case CEE_MONO_LDPTR_NURSERY_START:
11826                         case CEE_MONO_LDPTR_NURSERY_BITS:
11827                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11828                                 CHECK_STACK_OVF (1);
11829
11830                                 switch (ip [1]) {
11831                                         case CEE_MONO_LDPTR_CARD_TABLE:
11832                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11833                                                 break;
11834                                         case CEE_MONO_LDPTR_NURSERY_START:
11835                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11836                                                 break;
11837                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11838                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11839                                                 break;
11840                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11841                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11842                                                 break;
11843                                 }
11844
11845                                 *sp++ = ins;
11846                                 ip += 2;
11847                                 inline_costs += 10 * num_calls++;
11848                                 break;
11849                         }
11850                         case CEE_MONO_LDPTR: {
11851                                 gpointer ptr;
11852
11853                                 CHECK_STACK_OVF (1);
11854                                 CHECK_OPSIZE (6);
11855                                 token = read32 (ip + 2);
11856
11857                                 ptr = mono_method_get_wrapper_data (method, token);
11858                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11859                                 *sp++ = ins;
11860                                 ip += 6;
11861                                 inline_costs += 10 * num_calls++;
11862                                 /* Can't embed random pointers into AOT code */
11863                                 DISABLE_AOT (cfg);
11864                                 break;
11865                         }
11866                         case CEE_MONO_JIT_ICALL_ADDR: {
11867                                 MonoJitICallInfo *callinfo;
11868                                 gpointer ptr;
11869
11870                                 CHECK_STACK_OVF (1);
11871                                 CHECK_OPSIZE (6);
11872                                 token = read32 (ip + 2);
11873
11874                                 ptr = mono_method_get_wrapper_data (method, token);
11875                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11876                                 g_assert (callinfo);
11877                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11878                                 *sp++ = ins;
11879                                 ip += 6;
11880                                 inline_costs += 10 * num_calls++;
11881                                 break;
11882                         }
11883                         case CEE_MONO_ICALL_ADDR: {
11884                                 MonoMethod *cmethod;
11885                                 gpointer ptr;
11886
11887                                 CHECK_STACK_OVF (1);
11888                                 CHECK_OPSIZE (6);
11889                                 token = read32 (ip + 2);
11890
11891                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11892
11893                                 if (cfg->compile_aot) {
11894                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11895                                                 /*
11896                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11897                                                  * before the call, its not needed when using direct pinvoke.
11898                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11899                                                  * on platforms which don't support dlopen ().
11900                                                  */
11901                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11902                                         } else {
11903                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11904                                         }
11905                                 } else {
11906                                         ptr = mono_lookup_internal_call (cmethod);
11907                                         g_assert (ptr);
11908                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11909                                 }
11910                                 *sp++ = ins;
11911                                 ip += 6;
11912                                 break;
11913                         }
11914                         case CEE_MONO_VTADDR: {
11915                                 MonoInst *src_var, *src;
11916
11917                                 CHECK_STACK (1);
11918                                 --sp;
11919
11920                                 // FIXME:
11921                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11922                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11923                                 *sp++ = src;
11924                                 ip += 2;
11925                                 break;
11926                         }
11927                         case CEE_MONO_NEWOBJ: {
11928                                 MonoInst *iargs [2];
11929
11930                                 CHECK_STACK_OVF (1);
11931                                 CHECK_OPSIZE (6);
11932                                 token = read32 (ip + 2);
11933                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11934                                 mono_class_init (klass);
11935                                 NEW_DOMAINCONST (cfg, iargs [0]);
11936                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11937                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11938                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11939                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11940                                 ip += 6;
11941                                 inline_costs += 10 * num_calls++;
11942                                 break;
11943                         }
11944                         case CEE_MONO_OBJADDR:
11945                                 CHECK_STACK (1);
11946                                 --sp;
11947                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11948                                 ins->dreg = alloc_ireg_mp (cfg);
11949                                 ins->sreg1 = sp [0]->dreg;
11950                                 ins->type = STACK_MP;
11951                                 MONO_ADD_INS (cfg->cbb, ins);
11952                                 *sp++ = ins;
11953                                 ip += 2;
11954                                 break;
11955                         case CEE_MONO_LDNATIVEOBJ:
11956                                 /*
11957                                  * Similar to LDOBJ, but instead load the unmanaged 
11958                                  * representation of the vtype to the stack.
11959                                  */
11960                                 CHECK_STACK (1);
11961                                 CHECK_OPSIZE (6);
11962                                 --sp;
11963                                 token = read32 (ip + 2);
11964                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11965                                 g_assert (klass->valuetype);
11966                                 mono_class_init (klass);
11967
11968                                 {
11969                                         MonoInst *src, *dest, *temp;
11970
11971                                         src = sp [0];
11972                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11973                                         temp->backend.is_pinvoke = 1;
11974                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11975                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
11976
11977                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11978                                         dest->type = STACK_VTYPE;
11979                                         dest->klass = klass;
11980
11981                                         *sp ++ = dest;
11982                                         ip += 6;
11983                                 }
11984                                 break;
11985                         case CEE_MONO_RETOBJ: {
11986                                 /*
11987                                  * Same as RET, but return the native representation of a vtype
11988                                  * to the caller.
11989                                  */
11990                                 g_assert (cfg->ret);
11991                                 g_assert (mono_method_signature (method)->pinvoke); 
11992                                 CHECK_STACK (1);
11993                                 --sp;
11994                                 
11995                                 CHECK_OPSIZE (6);
11996                                 token = read32 (ip + 2);    
11997                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11998
11999                                 if (!cfg->vret_addr) {
12000                                         g_assert (cfg->ret_var_is_local);
12001
12002                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
12003                                 } else {
12004                                         EMIT_NEW_RETLOADA (cfg, ins);
12005                                 }
12006                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
12007                                 
12008                                 if (sp != stack_start)
12009                                         UNVERIFIED;
12010                                 
12011                                 MONO_INST_NEW (cfg, ins, OP_BR);
12012                                 ins->inst_target_bb = end_bblock;
12013                                 MONO_ADD_INS (cfg->cbb, ins);
12014                                 link_bblock (cfg, cfg->cbb, end_bblock);
12015                                 start_new_bblock = 1;
12016                                 ip += 6;
12017                                 break;
12018                         }
12019                         case CEE_MONO_SAVE_LMF:
12020                         case CEE_MONO_RESTORE_LMF:
12021                                 ip += 2;
12022                                 break;
12023                         case CEE_MONO_CLASSCONST:
12024                                 CHECK_STACK_OVF (1);
12025                                 CHECK_OPSIZE (6);
12026                                 token = read32 (ip + 2);
12027                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
12028                                 *sp++ = ins;
12029                                 ip += 6;
12030                                 inline_costs += 10 * num_calls++;
12031                                 break;
12032                         case CEE_MONO_NOT_TAKEN:
12033                                 cfg->cbb->out_of_line = TRUE;
12034                                 ip += 2;
12035                                 break;
12036                         case CEE_MONO_TLS: {
12037                                 MonoTlsKey key;
12038
12039                                 CHECK_STACK_OVF (1);
12040                                 CHECK_OPSIZE (6);
12041                                 key = (MonoTlsKey)read32 (ip + 2);
12042                                 g_assert (key < TLS_KEY_NUM);
12043
12044                                 ins = mono_create_tls_get (cfg, key);
12045                                 g_assert (ins);
12046                                 ins->type = STACK_PTR;
12047                                 *sp++ = ins;
12048                                 ip += 6;
12049                                 break;
12050                         }
12051                         case CEE_MONO_DYN_CALL: {
12052                                 MonoCallInst *call;
12053
12054                                 /* It would be easier to call a trampoline, but that would put an
12055                                  * extra frame on the stack, confusing exception handling. So
12056                                  * implement it inline using an opcode for now.
12057                                  */
12058
12059                                 if (!cfg->dyn_call_var) {
12060                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12061                                         /* prevent it from being register allocated */
12062                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
12063                                 }
12064
12065                                 /* Has to use a call inst since it local regalloc expects it */
12066                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
12067                                 ins = (MonoInst*)call;
12068                                 sp -= 2;
12069                                 ins->sreg1 = sp [0]->dreg;
12070                                 ins->sreg2 = sp [1]->dreg;
12071                                 MONO_ADD_INS (cfg->cbb, ins);
12072
12073                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
12074
12075                                 ip += 2;
12076                                 inline_costs += 10 * num_calls++;
12077
12078                                 break;
12079                         }
12080                         case CEE_MONO_MEMORY_BARRIER: {
12081                                 CHECK_OPSIZE (6);
12082                                 emit_memory_barrier (cfg, (int)read32 (ip + 2));
12083                                 ip += 6;
12084                                 break;
12085                         }
12086                         case CEE_MONO_ATOMIC_STORE_I4: {
12087                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
12088
12089                                 CHECK_OPSIZE (6);
12090                                 CHECK_STACK (2);
12091                                 sp -= 2;
12092
12093                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
12094                                 ins->dreg = sp [0]->dreg;
12095                                 ins->sreg1 = sp [1]->dreg;
12096                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
12097                                 MONO_ADD_INS (cfg->cbb, ins);
12098
12099                                 ip += 6;
12100                                 break;
12101                         }
12102                         case CEE_MONO_JIT_ATTACH: {
12103                                 MonoInst *args [16], *domain_ins;
12104                                 MonoInst *ad_ins, *jit_tls_ins;
12105                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
12106
12107                                 g_assert (!mono_threads_is_coop_enabled ());
12108
12109                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12110
12111                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12112                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12113
12114                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12115                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
12116
12117                                 if (ad_ins && jit_tls_ins) {
12118                                         NEW_BBLOCK (cfg, next_bb);
12119                                         NEW_BBLOCK (cfg, call_bb);
12120
12121                                         if (cfg->compile_aot) {
12122                                                 /* AOT code is only used in the root domain */
12123                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12124                                         } else {
12125                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12126                                         }
12127                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12128                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12129
12130                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12131                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12132
12133                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12134                                         MONO_START_BB (cfg, call_bb);
12135                                 }
12136
12137                                 /* AOT code is only used in the root domain */
12138                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12139                                 if (cfg->compile_aot) {
12140                                         MonoInst *addr;
12141
12142                                         /*
12143                                          * This is called on unattached threads, so it cannot go through the trampoline
12144                                          * infrastructure. Use an indirect call through a got slot initialized at load time
12145                                          * instead.
12146                                          */
12147                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
12148                                         ins = mono_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
12149                                 } else {
12150                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12151                                 }
12152                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12153
12154                                 if (next_bb)
12155                                         MONO_START_BB (cfg, next_bb);
12156
12157                                 ip += 2;
12158                                 break;
12159                         }
12160                         case CEE_MONO_JIT_DETACH: {
12161                                 MonoInst *args [16];
12162
12163                                 /* Restore the original domain */
12164                                 dreg = alloc_ireg (cfg);
12165                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12166                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12167                                 ip += 2;
12168                                 break;
12169                         }
12170                         case CEE_MONO_CALLI_EXTRA_ARG: {
12171                                 MonoInst *addr;
12172                                 MonoMethodSignature *fsig;
12173                                 MonoInst *arg;
12174
12175                                 /*
12176                                  * This is the same as CEE_CALLI, but passes an additional argument
12177                                  * to the called method in llvmonly mode.
12178                                  * This is only used by delegate invoke wrappers to call the
12179                                  * actual delegate method.
12180                                  */
12181                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12182
12183                                 CHECK_OPSIZE (6);
12184                                 token = read32 (ip + 2);
12185
12186                                 ins = NULL;
12187
12188                                 cmethod = NULL;
12189                                 CHECK_STACK (1);
12190                                 --sp;
12191                                 addr = *sp;
12192                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12193                                 CHECK_CFG_ERROR;
12194
12195                                 if (cfg->llvm_only)
12196                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12197
12198                                 n = fsig->param_count + fsig->hasthis + 1;
12199
12200                                 CHECK_STACK (n);
12201
12202                                 sp -= n;
12203                                 arg = sp [n - 1];
12204
12205                                 if (cfg->llvm_only) {
12206                                         /*
12207                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12208                                          * cconv. This is set by mono_init_delegate ().
12209                                          */
12210                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12211                                                 MonoInst *callee = addr;
12212                                                 MonoInst *call, *localloc_ins;
12213                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12214                                                 int low_bit_reg = alloc_preg (cfg);
12215
12216                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12217                                                 NEW_BBLOCK (cfg, end_bb);
12218
12219                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12220                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12221                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12222
12223                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12224                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12225                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12226                                                 /*
12227                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12228                                                  */
12229                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12230                                                 ins->dreg = alloc_preg (cfg);
12231                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12232                                                 MONO_ADD_INS (cfg->cbb, ins);
12233                                                 localloc_ins = ins;
12234                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12235                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12236                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12237
12238                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12239                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12240
12241                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12242                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12243                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12244                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12245                                                 ins->dreg = call->dreg;
12246
12247                                                 MONO_START_BB (cfg, end_bb);
12248                                         } else {
12249                                                 /* Caller uses a normal calling conv */
12250
12251                                                 MonoInst *callee = addr;
12252                                                 MonoInst *call, *localloc_ins;
12253                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12254                                                 int low_bit_reg = alloc_preg (cfg);
12255
12256                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12257                                                 NEW_BBLOCK (cfg, end_bb);
12258
12259                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12260                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12261                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12262
12263                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12264                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12265                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12266                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12267                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12268                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12269                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12270                                                 MONO_ADD_INS (cfg->cbb, addr);
12271                                                 /*
12272                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12273                                                  */
12274                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12275                                                 ins->dreg = alloc_preg (cfg);
12276                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12277                                                 MONO_ADD_INS (cfg->cbb, ins);
12278                                                 localloc_ins = ins;
12279                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12280                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12281                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12282
12283                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12284                                                 ins->dreg = call->dreg;
12285                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12286
12287                                                 MONO_START_BB (cfg, end_bb);
12288                                         }
12289                                 } else {
12290                                         /* Same as CEE_CALLI */
12291                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12292                                                 /*
12293                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12294                                                  */
12295                                                 MonoInst *callee = addr;
12296
12297                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12298                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12299                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12300                                         } else {
12301                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12302                                         }
12303                                 }
12304
12305                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12306                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12307
12308                                 CHECK_CFG_EXCEPTION;
12309
12310                                 ip += 6;
12311                                 ins_flag = 0;
12312                                 constrained_class = NULL;
12313                                 break;
12314                         }
12315                         case CEE_MONO_LDDOMAIN:
12316                                 CHECK_STACK_OVF (1);
12317                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12318                                 ip += 2;
12319                                 *sp++ = ins;
12320                                 break;
12321                         case CEE_MONO_GET_LAST_ERROR:
12322                                 CHECK_OPSIZE (2);
12323                                 CHECK_STACK_OVF (1);
12324
12325                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
12326                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
12327                                 ins->type = STACK_I4;
12328                                 MONO_ADD_INS (cfg->cbb, ins);
12329
12330                                 ip += 2;
12331                                 *sp++ = ins;
12332                                 break;
12333                         default:
12334                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12335                                 break;
12336                         }
12337                         break;
12338                 }
12339
12340                 case CEE_PREFIX1: {
12341                         CHECK_OPSIZE (2);
12342                         switch (ip [1]) {
12343                         case CEE_ARGLIST: {
12344                                 /* somewhat similar to LDTOKEN */
12345                                 MonoInst *addr, *vtvar;
12346                                 CHECK_STACK_OVF (1);
12347                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12348
12349                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12350                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12351
12352                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12353                                 ins->type = STACK_VTYPE;
12354                                 ins->klass = mono_defaults.argumenthandle_class;
12355                                 *sp++ = ins;
12356                                 ip += 2;
12357                                 break;
12358                         }
12359                         case CEE_CEQ:
12360                         case CEE_CGT:
12361                         case CEE_CGT_UN:
12362                         case CEE_CLT:
12363                         case CEE_CLT_UN: {
12364                                 MonoInst *cmp, *arg1, *arg2;
12365
12366                                 CHECK_STACK (2);
12367                                 sp -= 2;
12368                                 arg1 = sp [0];
12369                                 arg2 = sp [1];
12370
12371                                 /*
12372                                  * The following transforms:
12373                                  *    CEE_CEQ    into OP_CEQ
12374                                  *    CEE_CGT    into OP_CGT
12375                                  *    CEE_CGT_UN into OP_CGT_UN
12376                                  *    CEE_CLT    into OP_CLT
12377                                  *    CEE_CLT_UN into OP_CLT_UN
12378                                  */
12379                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12380
12381                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12382                                 cmp->sreg1 = arg1->dreg;
12383                                 cmp->sreg2 = arg2->dreg;
12384                                 type_from_op (cfg, cmp, arg1, arg2);
12385                                 CHECK_TYPE (cmp);
12386                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12387                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12388                                         cmp->opcode = OP_LCOMPARE;
12389                                 else if (arg1->type == STACK_R4)
12390                                         cmp->opcode = OP_RCOMPARE;
12391                                 else if (arg1->type == STACK_R8)
12392                                         cmp->opcode = OP_FCOMPARE;
12393                                 else
12394                                         cmp->opcode = OP_ICOMPARE;
12395                                 MONO_ADD_INS (cfg->cbb, cmp);
12396                                 ins->type = STACK_I4;
12397                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12398                                 type_from_op (cfg, ins, arg1, arg2);
12399
12400                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12401                                         /*
12402                                          * The backends expect the fceq opcodes to do the
12403                                          * comparison too.
12404                                          */
12405                                         ins->sreg1 = cmp->sreg1;
12406                                         ins->sreg2 = cmp->sreg2;
12407                                         NULLIFY_INS (cmp);
12408                                 }
12409                                 MONO_ADD_INS (cfg->cbb, ins);
12410                                 *sp++ = ins;
12411                                 ip += 2;
12412                                 break;
12413                         }
12414                         case CEE_LDFTN: {
12415                                 MonoInst *argconst;
12416                                 MonoMethod *cil_method;
12417
12418                                 CHECK_STACK_OVF (1);
12419                                 CHECK_OPSIZE (6);
12420                                 n = read32 (ip + 2);
12421                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12422                                 CHECK_CFG_ERROR;
12423
12424                                 mono_class_init (cmethod->klass);
12425
12426                                 mono_save_token_info (cfg, image, n, cmethod);
12427
12428                                 context_used = mini_method_check_context_used (cfg, cmethod);
12429
12430                                 cil_method = cmethod;
12431                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12432                                         emit_method_access_failure (cfg, method, cil_method);
12433
12434                                 if (mono_security_core_clr_enabled ())
12435                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12436
12437                                 /* 
12438                                  * Optimize the common case of ldftn+delegate creation
12439                                  */
12440                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12441                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12442                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12443                                                 MonoInst *target_ins, *handle_ins;
12444                                                 MonoMethod *invoke;
12445                                                 int invoke_context_used;
12446
12447                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12448                                                 if (!invoke || !mono_method_signature (invoke))
12449                                                         LOAD_ERROR;
12450
12451                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12452
12453                                                 target_ins = sp [-1];
12454
12455                                                 if (mono_security_core_clr_enabled ())
12456                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12457
12458                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12459                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12460                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12461                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12462                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12463                                                         }
12464                                                 }
12465
12466                                                 /* FIXME: SGEN support */
12467                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12468                                                         ip += 6;
12469                                                         if (cfg->verbose_level > 3)
12470                                                                 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));
12471                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12472                                                                 sp --;
12473                                                                 *sp = handle_ins;
12474                                                                 CHECK_CFG_EXCEPTION;
12475                                                                 ip += 5;
12476                                                                 sp ++;
12477                                                                 break;
12478                                                         }
12479                                                         ip -= 6;
12480                                                 }
12481                                         }
12482                                 }
12483
12484                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12485                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12486                                 *sp++ = ins;
12487                                 
12488                                 ip += 6;
12489                                 inline_costs += 10 * num_calls++;
12490                                 break;
12491                         }
12492                         case CEE_LDVIRTFTN: {
12493                                 MonoInst *args [2];
12494
12495                                 CHECK_STACK (1);
12496                                 CHECK_OPSIZE (6);
12497                                 n = read32 (ip + 2);
12498                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12499                                 CHECK_CFG_ERROR;
12500
12501                                 mono_class_init (cmethod->klass);
12502  
12503                                 context_used = mini_method_check_context_used (cfg, cmethod);
12504
12505                                 if (mono_security_core_clr_enabled ())
12506                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12507
12508                                 /*
12509                                  * Optimize the common case of ldvirtftn+delegate creation
12510                                  */
12511                                 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)) {
12512                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12513                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12514                                                 MonoInst *target_ins, *handle_ins;
12515                                                 MonoMethod *invoke;
12516                                                 int invoke_context_used;
12517                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12518
12519                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12520                                                 if (!invoke || !mono_method_signature (invoke))
12521                                                         LOAD_ERROR;
12522
12523                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12524
12525                                                 target_ins = sp [-1];
12526
12527                                                 if (mono_security_core_clr_enabled ())
12528                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12529
12530                                                 /* FIXME: SGEN support */
12531                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12532                                                         ip += 6;
12533                                                         if (cfg->verbose_level > 3)
12534                                                                 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));
12535                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12536                                                                 sp -= 2;
12537                                                                 *sp = handle_ins;
12538                                                                 CHECK_CFG_EXCEPTION;
12539                                                                 ip += 5;
12540                                                                 sp ++;
12541                                                                 break;
12542                                                         }
12543                                                         ip -= 6;
12544                                                 }
12545                                         }
12546                                 }
12547
12548                                 --sp;
12549                                 args [0] = *sp;
12550
12551                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12552                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12553
12554                                 if (context_used)
12555                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12556                                 else
12557                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12558
12559                                 ip += 6;
12560                                 inline_costs += 10 * num_calls++;
12561                                 break;
12562                         }
12563                         case CEE_LDARG:
12564                                 CHECK_STACK_OVF (1);
12565                                 CHECK_OPSIZE (4);
12566                                 n = read16 (ip + 2);
12567                                 CHECK_ARG (n);
12568                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12569                                 *sp++ = ins;
12570                                 ip += 4;
12571                                 break;
12572                         case CEE_LDARGA:
12573                                 CHECK_STACK_OVF (1);
12574                                 CHECK_OPSIZE (4);
12575                                 n = read16 (ip + 2);
12576                                 CHECK_ARG (n);
12577                                 NEW_ARGLOADA (cfg, ins, n);
12578                                 MONO_ADD_INS (cfg->cbb, ins);
12579                                 *sp++ = ins;
12580                                 ip += 4;
12581                                 break;
12582                         case CEE_STARG:
12583                                 CHECK_STACK (1);
12584                                 --sp;
12585                                 CHECK_OPSIZE (4);
12586                                 n = read16 (ip + 2);
12587                                 CHECK_ARG (n);
12588                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12589                                         UNVERIFIED;
12590                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12591                                 ip += 4;
12592                                 break;
12593                         case CEE_LDLOC:
12594                                 CHECK_STACK_OVF (1);
12595                                 CHECK_OPSIZE (4);
12596                                 n = read16 (ip + 2);
12597                                 CHECK_LOCAL (n);
12598                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12599                                 *sp++ = ins;
12600                                 ip += 4;
12601                                 break;
12602                         case CEE_LDLOCA: {
12603                                 unsigned char *tmp_ip;
12604                                 CHECK_STACK_OVF (1);
12605                                 CHECK_OPSIZE (4);
12606                                 n = read16 (ip + 2);
12607                                 CHECK_LOCAL (n);
12608
12609                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12610                                         ip = tmp_ip;
12611                                         inline_costs += 1;
12612                                         break;
12613                                 }                       
12614                                 
12615                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12616                                 *sp++ = ins;
12617                                 ip += 4;
12618                                 break;
12619                         }
12620                         case CEE_STLOC:
12621                                 CHECK_STACK (1);
12622                                 --sp;
12623                                 CHECK_OPSIZE (4);
12624                                 n = read16 (ip + 2);
12625                                 CHECK_LOCAL (n);
12626                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12627                                         UNVERIFIED;
12628                                 emit_stloc_ir (cfg, sp, header, n);
12629                                 ip += 4;
12630                                 inline_costs += 1;
12631                                 break;
12632                         case CEE_LOCALLOC: {
12633                                 CHECK_STACK (1);
12634                                 MonoBasicBlock *non_zero_bb, *end_bb;
12635                                 int alloc_ptr = alloc_preg (cfg);
12636                                 --sp;
12637                                 if (sp != stack_start) 
12638                                         UNVERIFIED;
12639                                 if (cfg->method != method) 
12640                                         /* 
12641                                          * Inlining this into a loop in a parent could lead to 
12642                                          * stack overflows which is different behavior than the
12643                                          * non-inlined case, thus disable inlining in this case.
12644                                          */
12645                                         INLINE_FAILURE("localloc");
12646
12647                                 NEW_BBLOCK (cfg, non_zero_bb);
12648                                 NEW_BBLOCK (cfg, end_bb);
12649
12650                                 /* if size != zero */
12651                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12652                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12653
12654                                 //size is zero, so result is NULL
12655                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12656                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12657
12658                                 MONO_START_BB (cfg, non_zero_bb);
12659                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12660                                 ins->dreg = alloc_ptr;
12661                                 ins->sreg1 = sp [0]->dreg;
12662                                 ins->type = STACK_PTR;
12663                                 MONO_ADD_INS (cfg->cbb, ins);
12664
12665                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12666                                 if (init_locals)
12667                                         ins->flags |= MONO_INST_INIT;
12668
12669                                 MONO_START_BB (cfg, end_bb);
12670                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12671                                 ins->type = STACK_PTR;
12672
12673                                 *sp++ = ins;
12674                                 ip += 2;
12675                                 break;
12676                         }
12677                         case CEE_ENDFILTER: {
12678                                 MonoExceptionClause *clause, *nearest;
12679                                 int cc;
12680
12681                                 CHECK_STACK (1);
12682                                 --sp;
12683                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12684                                         UNVERIFIED;
12685                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12686                                 ins->sreg1 = (*sp)->dreg;
12687                                 MONO_ADD_INS (cfg->cbb, ins);
12688                                 start_new_bblock = 1;
12689                                 ip += 2;
12690
12691                                 nearest = NULL;
12692                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12693                                         clause = &header->clauses [cc];
12694                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12695                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12696                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12697                                                 nearest = clause;
12698                                 }
12699                                 g_assert (nearest);
12700                                 if ((ip - header->code) != nearest->handler_offset)
12701                                         UNVERIFIED;
12702
12703                                 break;
12704                         }
12705                         case CEE_UNALIGNED_:
12706                                 ins_flag |= MONO_INST_UNALIGNED;
12707                                 /* FIXME: record alignment? we can assume 1 for now */
12708                                 CHECK_OPSIZE (3);
12709                                 ip += 3;
12710                                 break;
12711                         case CEE_VOLATILE_:
12712                                 ins_flag |= MONO_INST_VOLATILE;
12713                                 ip += 2;
12714                                 break;
12715                         case CEE_TAIL_:
12716                                 ins_flag   |= MONO_INST_TAILCALL;
12717                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12718                                 /* Can't inline tail calls at this time */
12719                                 inline_costs += 100000;
12720                                 ip += 2;
12721                                 break;
12722                         case CEE_INITOBJ:
12723                                 CHECK_STACK (1);
12724                                 --sp;
12725                                 CHECK_OPSIZE (6);
12726                                 token = read32 (ip + 2);
12727                                 klass = mini_get_class (method, token, generic_context);
12728                                 CHECK_TYPELOAD (klass);
12729                                 if (generic_class_is_reference_type (cfg, klass))
12730                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12731                                 else
12732                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12733                                 ip += 6;
12734                                 inline_costs += 1;
12735                                 break;
12736                         case CEE_CONSTRAINED_:
12737                                 CHECK_OPSIZE (6);
12738                                 token = read32 (ip + 2);
12739                                 constrained_class = mini_get_class (method, token, generic_context);
12740                                 CHECK_TYPELOAD (constrained_class);
12741                                 ip += 6;
12742                                 break;
12743                         case CEE_CPBLK:
12744                         case CEE_INITBLK: {
12745                                 MonoInst *iargs [3];
12746                                 CHECK_STACK (3);
12747                                 sp -= 3;
12748
12749                                 /* Skip optimized paths for volatile operations. */
12750                                 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)) {
12751                                         mini_emit_memcpy (cfg, sp [0]->dreg, 0, sp [1]->dreg, 0, sp [2]->inst_c0, 0);
12752                                 } 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)) {
12753                                         /* emit_memset only works when val == 0 */
12754                                         mini_emit_memset (cfg, sp [0]->dreg, 0, sp [2]->inst_c0, sp [1]->inst_c0, 0);
12755                                 } else {
12756                                         MonoInst *call;
12757                                         iargs [0] = sp [0];
12758                                         iargs [1] = sp [1];
12759                                         iargs [2] = sp [2];
12760                                         if (ip [1] == CEE_CPBLK) {
12761                                                 /*
12762                                                  * FIXME: It's unclear whether we should be emitting both the acquire
12763                                                  * and release barriers for cpblk. It is technically both a load and
12764                                                  * store operation, so it seems like that's the sensible thing to do.
12765                                                  *
12766                                                  * FIXME: We emit full barriers on both sides of the operation for
12767                                                  * simplicity. We should have a separate atomic memcpy method instead.
12768                                                  */
12769                                                 MonoMethod *memcpy_method = get_memcpy_method ();
12770
12771                                                 if (ins_flag & MONO_INST_VOLATILE)
12772                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12773
12774                                                 call = mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
12775                                                 call->flags |= ins_flag;
12776
12777                                                 if (ins_flag & MONO_INST_VOLATILE)
12778                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12779                                         } else {
12780                                                 MonoMethod *memset_method = get_memset_method ();
12781                                                 if (ins_flag & MONO_INST_VOLATILE) {
12782                                                         /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
12783                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
12784                                                 }
12785                                                 call = mono_emit_method_call (cfg, memset_method, iargs, NULL);
12786                                                 call->flags |= ins_flag;
12787                                         }
12788                                 }
12789                                 ip += 2;
12790                                 ins_flag = 0;
12791                                 inline_costs += 1;
12792                                 break;
12793                         }
12794                         case CEE_NO_:
12795                                 CHECK_OPSIZE (3);
12796                                 if (ip [2] & 0x1)
12797                                         ins_flag |= MONO_INST_NOTYPECHECK;
12798                                 if (ip [2] & 0x2)
12799                                         ins_flag |= MONO_INST_NORANGECHECK;
12800                                 /* we ignore the no-nullcheck for now since we
12801                                  * really do it explicitly only when doing callvirt->call
12802                                  */
12803                                 ip += 3;
12804                                 break;
12805                         case CEE_RETHROW: {
12806                                 MonoInst *load;
12807                                 int handler_offset = -1;
12808
12809                                 for (i = 0; i < header->num_clauses; ++i) {
12810                                         MonoExceptionClause *clause = &header->clauses [i];
12811                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12812                                                 handler_offset = clause->handler_offset;
12813                                                 break;
12814                                         }
12815                                 }
12816
12817                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12818
12819                                 if (handler_offset == -1)
12820                                         UNVERIFIED;
12821
12822                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12823                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12824                                 ins->sreg1 = load->dreg;
12825                                 MONO_ADD_INS (cfg->cbb, ins);
12826
12827                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12828                                 MONO_ADD_INS (cfg->cbb, ins);
12829
12830                                 sp = stack_start;
12831                                 link_bblock (cfg, cfg->cbb, end_bblock);
12832                                 start_new_bblock = 1;
12833                                 ip += 2;
12834                                 break;
12835                         }
12836                         case CEE_SIZEOF: {
12837                                 guint32 val;
12838                                 int ialign;
12839
12840                                 CHECK_STACK_OVF (1);
12841                                 CHECK_OPSIZE (6);
12842                                 token = read32 (ip + 2);
12843                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12844                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12845                                         CHECK_CFG_ERROR;
12846
12847                                         val = mono_type_size (type, &ialign);
12848                                 } else {
12849                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12850                                         CHECK_TYPELOAD (klass);
12851
12852                                         val = mono_type_size (&klass->byval_arg, &ialign);
12853
12854                                         if (mini_is_gsharedvt_klass (klass))
12855                                                 GSHAREDVT_FAILURE (*ip);
12856                                 }
12857                                 EMIT_NEW_ICONST (cfg, ins, val);
12858                                 *sp++= ins;
12859                                 ip += 6;
12860                                 break;
12861                         }
12862                         case CEE_REFANYTYPE: {
12863                                 MonoInst *src_var, *src;
12864
12865                                 GSHAREDVT_FAILURE (*ip);
12866
12867                                 CHECK_STACK (1);
12868                                 --sp;
12869
12870                                 // FIXME:
12871                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12872                                 if (!src_var)
12873                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12874                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12875                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12876                                 *sp++ = ins;
12877                                 ip += 2;
12878                                 break;
12879                         }
12880                         case CEE_READONLY_:
12881                                 readonly = TRUE;
12882                                 ip += 2;
12883                                 break;
12884
12885                         case CEE_UNUSED56:
12886                         case CEE_UNUSED57:
12887                         case CEE_UNUSED70:
12888                         case CEE_UNUSED:
12889                         case CEE_UNUSED99:
12890                                 UNVERIFIED;
12891                                 
12892                         default:
12893                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12894                                 UNVERIFIED;
12895                         }
12896                         break;
12897                 }
12898                 case CEE_UNUSED58:
12899                 case CEE_UNUSED1:
12900                         UNVERIFIED;
12901
12902                 default:
12903                         g_warning ("opcode 0x%02x not handled", *ip);
12904                         UNVERIFIED;
12905                 }
12906         }
12907         if (start_new_bblock != 1)
12908                 UNVERIFIED;
12909
12910         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12911         if (cfg->cbb->next_bb) {
12912                 /* This could already be set because of inlining, #693905 */
12913                 MonoBasicBlock *bb = cfg->cbb;
12914
12915                 while (bb->next_bb)
12916                         bb = bb->next_bb;
12917                 bb->next_bb = end_bblock;
12918         } else {
12919                 cfg->cbb->next_bb = end_bblock;
12920         }
12921
12922         if (cfg->method == method && cfg->domainvar) {
12923                 MonoInst *store;
12924                 MonoInst *get_domain;
12925
12926                 cfg->cbb = init_localsbb;
12927
12928                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12929                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12930                 MONO_ADD_INS (cfg->cbb, store);
12931         }
12932
12933 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12934         if (cfg->compile_aot)
12935                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12936                 mono_get_got_var (cfg);
12937 #endif
12938
12939         if (cfg->method == method && cfg->got_var)
12940                 mono_emit_load_got_addr (cfg);
12941
12942         if (init_localsbb) {
12943                 cfg->cbb = init_localsbb;
12944                 cfg->ip = NULL;
12945                 for (i = 0; i < header->num_locals; ++i) {
12946                         emit_init_local (cfg, i, header->locals [i], init_locals);
12947                 }
12948         }
12949
12950         if (cfg->init_ref_vars && cfg->method == method) {
12951                 /* Emit initialization for ref vars */
12952                 // FIXME: Avoid duplication initialization for IL locals.
12953                 for (i = 0; i < cfg->num_varinfo; ++i) {
12954                         MonoInst *ins = cfg->varinfo [i];
12955
12956                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12957                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12958                 }
12959         }
12960
12961         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12962                 cfg->cbb = init_localsbb;
12963                 emit_push_lmf (cfg);
12964         }
12965
12966         cfg->cbb = init_localsbb;
12967         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12968
12969         if (seq_points) {
12970                 MonoBasicBlock *bb;
12971
12972                 /*
12973                  * Make seq points at backward branch targets interruptable.
12974                  */
12975                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12976                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12977                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12978         }
12979
12980         /* Add a sequence point for method entry/exit events */
12981         if (seq_points && cfg->gen_sdb_seq_points) {
12982                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12983                 MONO_ADD_INS (init_localsbb, ins);
12984                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12985                 MONO_ADD_INS (cfg->bb_exit, ins);
12986         }
12987
12988         /*
12989          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12990          * the code they refer to was dead (#11880).
12991          */
12992         if (sym_seq_points) {
12993                 for (i = 0; i < header->code_size; ++i) {
12994                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12995                                 MonoInst *ins;
12996
12997                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12998                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12999                         }
13000                 }
13001         }
13002
13003         cfg->ip = NULL;
13004
13005         if (cfg->method == method) {
13006                 MonoBasicBlock *bb;
13007                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13008                         if (bb == cfg->bb_init)
13009                                 bb->region = -1;
13010                         else
13011                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
13012                         if (cfg->spvars)
13013                                 mono_create_spvar_for_region (cfg, bb->region);
13014                         if (cfg->verbose_level > 2)
13015                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
13016                 }
13017         } else {
13018                 MonoBasicBlock *bb;
13019                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
13020                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
13021                         bb->real_offset = inline_offset;
13022                 }
13023         }
13024
13025         if (inline_costs < 0) {
13026                 char *mname;
13027
13028                 /* Method is too large */
13029                 mname = mono_method_full_name (method, TRUE);
13030                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
13031                 g_free (mname);
13032         }
13033
13034         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
13035                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
13036
13037         goto cleanup;
13038
13039 mono_error_exit:
13040         g_assert (!mono_error_ok (&cfg->error));
13041         goto cleanup;
13042  
13043  exception_exit:
13044         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
13045         goto cleanup;
13046
13047  unverified:
13048         set_exception_type_from_invalid_il (cfg, method, ip);
13049         goto cleanup;
13050
13051  cleanup:
13052         g_slist_free (class_inits);
13053         mono_basic_block_free (original_bb);
13054         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
13055         if (cfg->exception_type)
13056                 return -1;
13057         else
13058                 return inline_costs;
13059 }
13060
13061 static int
13062 store_membase_reg_to_store_membase_imm (int opcode)
13063 {
13064         switch (opcode) {
13065         case OP_STORE_MEMBASE_REG:
13066                 return OP_STORE_MEMBASE_IMM;
13067         case OP_STOREI1_MEMBASE_REG:
13068                 return OP_STOREI1_MEMBASE_IMM;
13069         case OP_STOREI2_MEMBASE_REG:
13070                 return OP_STOREI2_MEMBASE_IMM;
13071         case OP_STOREI4_MEMBASE_REG:
13072                 return OP_STOREI4_MEMBASE_IMM;
13073         case OP_STOREI8_MEMBASE_REG:
13074                 return OP_STOREI8_MEMBASE_IMM;
13075         default:
13076                 g_assert_not_reached ();
13077         }
13078
13079         return -1;
13080 }               
13081
13082 int
13083 mono_op_to_op_imm (int opcode)
13084 {
13085         switch (opcode) {
13086         case OP_IADD:
13087                 return OP_IADD_IMM;
13088         case OP_ISUB:
13089                 return OP_ISUB_IMM;
13090         case OP_IDIV:
13091                 return OP_IDIV_IMM;
13092         case OP_IDIV_UN:
13093                 return OP_IDIV_UN_IMM;
13094         case OP_IREM:
13095                 return OP_IREM_IMM;
13096         case OP_IREM_UN:
13097                 return OP_IREM_UN_IMM;
13098         case OP_IMUL:
13099                 return OP_IMUL_IMM;
13100         case OP_IAND:
13101                 return OP_IAND_IMM;
13102         case OP_IOR:
13103                 return OP_IOR_IMM;
13104         case OP_IXOR:
13105                 return OP_IXOR_IMM;
13106         case OP_ISHL:
13107                 return OP_ISHL_IMM;
13108         case OP_ISHR:
13109                 return OP_ISHR_IMM;
13110         case OP_ISHR_UN:
13111                 return OP_ISHR_UN_IMM;
13112
13113         case OP_LADD:
13114                 return OP_LADD_IMM;
13115         case OP_LSUB:
13116                 return OP_LSUB_IMM;
13117         case OP_LAND:
13118                 return OP_LAND_IMM;
13119         case OP_LOR:
13120                 return OP_LOR_IMM;
13121         case OP_LXOR:
13122                 return OP_LXOR_IMM;
13123         case OP_LSHL:
13124                 return OP_LSHL_IMM;
13125         case OP_LSHR:
13126                 return OP_LSHR_IMM;
13127         case OP_LSHR_UN:
13128                 return OP_LSHR_UN_IMM;
13129 #if SIZEOF_REGISTER == 8
13130         case OP_LREM:
13131                 return OP_LREM_IMM;
13132 #endif
13133
13134         case OP_COMPARE:
13135                 return OP_COMPARE_IMM;
13136         case OP_ICOMPARE:
13137                 return OP_ICOMPARE_IMM;
13138         case OP_LCOMPARE:
13139                 return OP_LCOMPARE_IMM;
13140
13141         case OP_STORE_MEMBASE_REG:
13142                 return OP_STORE_MEMBASE_IMM;
13143         case OP_STOREI1_MEMBASE_REG:
13144                 return OP_STOREI1_MEMBASE_IMM;
13145         case OP_STOREI2_MEMBASE_REG:
13146                 return OP_STOREI2_MEMBASE_IMM;
13147         case OP_STOREI4_MEMBASE_REG:
13148                 return OP_STOREI4_MEMBASE_IMM;
13149
13150 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13151         case OP_X86_PUSH:
13152                 return OP_X86_PUSH_IMM;
13153         case OP_X86_COMPARE_MEMBASE_REG:
13154                 return OP_X86_COMPARE_MEMBASE_IMM;
13155 #endif
13156 #if defined(TARGET_AMD64)
13157         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13158                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13159 #endif
13160         case OP_VOIDCALL_REG:
13161                 return OP_VOIDCALL;
13162         case OP_CALL_REG:
13163                 return OP_CALL;
13164         case OP_LCALL_REG:
13165                 return OP_LCALL;
13166         case OP_FCALL_REG:
13167                 return OP_FCALL;
13168         case OP_LOCALLOC:
13169                 return OP_LOCALLOC_IMM;
13170         }
13171
13172         return -1;
13173 }
13174
13175 static int
13176 ldind_to_load_membase (int opcode)
13177 {
13178         switch (opcode) {
13179         case CEE_LDIND_I1:
13180                 return OP_LOADI1_MEMBASE;
13181         case CEE_LDIND_U1:
13182                 return OP_LOADU1_MEMBASE;
13183         case CEE_LDIND_I2:
13184                 return OP_LOADI2_MEMBASE;
13185         case CEE_LDIND_U2:
13186                 return OP_LOADU2_MEMBASE;
13187         case CEE_LDIND_I4:
13188                 return OP_LOADI4_MEMBASE;
13189         case CEE_LDIND_U4:
13190                 return OP_LOADU4_MEMBASE;
13191         case CEE_LDIND_I:
13192                 return OP_LOAD_MEMBASE;
13193         case CEE_LDIND_REF:
13194                 return OP_LOAD_MEMBASE;
13195         case CEE_LDIND_I8:
13196                 return OP_LOADI8_MEMBASE;
13197         case CEE_LDIND_R4:
13198                 return OP_LOADR4_MEMBASE;
13199         case CEE_LDIND_R8:
13200                 return OP_LOADR8_MEMBASE;
13201         default:
13202                 g_assert_not_reached ();
13203         }
13204
13205         return -1;
13206 }
13207
13208 static int
13209 stind_to_store_membase (int opcode)
13210 {
13211         switch (opcode) {
13212         case CEE_STIND_I1:
13213                 return OP_STOREI1_MEMBASE_REG;
13214         case CEE_STIND_I2:
13215                 return OP_STOREI2_MEMBASE_REG;
13216         case CEE_STIND_I4:
13217                 return OP_STOREI4_MEMBASE_REG;
13218         case CEE_STIND_I:
13219         case CEE_STIND_REF:
13220                 return OP_STORE_MEMBASE_REG;
13221         case CEE_STIND_I8:
13222                 return OP_STOREI8_MEMBASE_REG;
13223         case CEE_STIND_R4:
13224                 return OP_STORER4_MEMBASE_REG;
13225         case CEE_STIND_R8:
13226                 return OP_STORER8_MEMBASE_REG;
13227         default:
13228                 g_assert_not_reached ();
13229         }
13230
13231         return -1;
13232 }
13233
13234 int
13235 mono_load_membase_to_load_mem (int opcode)
13236 {
13237         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13238 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13239         switch (opcode) {
13240         case OP_LOAD_MEMBASE:
13241                 return OP_LOAD_MEM;
13242         case OP_LOADU1_MEMBASE:
13243                 return OP_LOADU1_MEM;
13244         case OP_LOADU2_MEMBASE:
13245                 return OP_LOADU2_MEM;
13246         case OP_LOADI4_MEMBASE:
13247                 return OP_LOADI4_MEM;
13248         case OP_LOADU4_MEMBASE:
13249                 return OP_LOADU4_MEM;
13250 #if SIZEOF_REGISTER == 8
13251         case OP_LOADI8_MEMBASE:
13252                 return OP_LOADI8_MEM;
13253 #endif
13254         }
13255 #endif
13256
13257         return -1;
13258 }
13259
13260 static inline int
13261 op_to_op_dest_membase (int store_opcode, int opcode)
13262 {
13263 #if defined(TARGET_X86)
13264         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13265                 return -1;
13266
13267         switch (opcode) {
13268         case OP_IADD:
13269                 return OP_X86_ADD_MEMBASE_REG;
13270         case OP_ISUB:
13271                 return OP_X86_SUB_MEMBASE_REG;
13272         case OP_IAND:
13273                 return OP_X86_AND_MEMBASE_REG;
13274         case OP_IOR:
13275                 return OP_X86_OR_MEMBASE_REG;
13276         case OP_IXOR:
13277                 return OP_X86_XOR_MEMBASE_REG;
13278         case OP_ADD_IMM:
13279         case OP_IADD_IMM:
13280                 return OP_X86_ADD_MEMBASE_IMM;
13281         case OP_SUB_IMM:
13282         case OP_ISUB_IMM:
13283                 return OP_X86_SUB_MEMBASE_IMM;
13284         case OP_AND_IMM:
13285         case OP_IAND_IMM:
13286                 return OP_X86_AND_MEMBASE_IMM;
13287         case OP_OR_IMM:
13288         case OP_IOR_IMM:
13289                 return OP_X86_OR_MEMBASE_IMM;
13290         case OP_XOR_IMM:
13291         case OP_IXOR_IMM:
13292                 return OP_X86_XOR_MEMBASE_IMM;
13293         case OP_MOVE:
13294                 return OP_NOP;
13295         }
13296 #endif
13297
13298 #if defined(TARGET_AMD64)
13299         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13300                 return -1;
13301
13302         switch (opcode) {
13303         case OP_IADD:
13304                 return OP_X86_ADD_MEMBASE_REG;
13305         case OP_ISUB:
13306                 return OP_X86_SUB_MEMBASE_REG;
13307         case OP_IAND:
13308                 return OP_X86_AND_MEMBASE_REG;
13309         case OP_IOR:
13310                 return OP_X86_OR_MEMBASE_REG;
13311         case OP_IXOR:
13312                 return OP_X86_XOR_MEMBASE_REG;
13313         case OP_IADD_IMM:
13314                 return OP_X86_ADD_MEMBASE_IMM;
13315         case OP_ISUB_IMM:
13316                 return OP_X86_SUB_MEMBASE_IMM;
13317         case OP_IAND_IMM:
13318                 return OP_X86_AND_MEMBASE_IMM;
13319         case OP_IOR_IMM:
13320                 return OP_X86_OR_MEMBASE_IMM;
13321         case OP_IXOR_IMM:
13322                 return OP_X86_XOR_MEMBASE_IMM;
13323         case OP_LADD:
13324                 return OP_AMD64_ADD_MEMBASE_REG;
13325         case OP_LSUB:
13326                 return OP_AMD64_SUB_MEMBASE_REG;
13327         case OP_LAND:
13328                 return OP_AMD64_AND_MEMBASE_REG;
13329         case OP_LOR:
13330                 return OP_AMD64_OR_MEMBASE_REG;
13331         case OP_LXOR:
13332                 return OP_AMD64_XOR_MEMBASE_REG;
13333         case OP_ADD_IMM:
13334         case OP_LADD_IMM:
13335                 return OP_AMD64_ADD_MEMBASE_IMM;
13336         case OP_SUB_IMM:
13337         case OP_LSUB_IMM:
13338                 return OP_AMD64_SUB_MEMBASE_IMM;
13339         case OP_AND_IMM:
13340         case OP_LAND_IMM:
13341                 return OP_AMD64_AND_MEMBASE_IMM;
13342         case OP_OR_IMM:
13343         case OP_LOR_IMM:
13344                 return OP_AMD64_OR_MEMBASE_IMM;
13345         case OP_XOR_IMM:
13346         case OP_LXOR_IMM:
13347                 return OP_AMD64_XOR_MEMBASE_IMM;
13348         case OP_MOVE:
13349                 return OP_NOP;
13350         }
13351 #endif
13352
13353         return -1;
13354 }
13355
13356 static inline int
13357 op_to_op_store_membase (int store_opcode, int opcode)
13358 {
13359 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13360         switch (opcode) {
13361         case OP_ICEQ:
13362                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13363                         return OP_X86_SETEQ_MEMBASE;
13364         case OP_CNE:
13365                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13366                         return OP_X86_SETNE_MEMBASE;
13367         }
13368 #endif
13369
13370         return -1;
13371 }
13372
13373 static inline int
13374 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13375 {
13376 #ifdef TARGET_X86
13377         /* FIXME: This has sign extension issues */
13378         /*
13379         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13380                 return OP_X86_COMPARE_MEMBASE8_IMM;
13381         */
13382
13383         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13384                 return -1;
13385
13386         switch (opcode) {
13387         case OP_X86_PUSH:
13388                 return OP_X86_PUSH_MEMBASE;
13389         case OP_COMPARE_IMM:
13390         case OP_ICOMPARE_IMM:
13391                 return OP_X86_COMPARE_MEMBASE_IMM;
13392         case OP_COMPARE:
13393         case OP_ICOMPARE:
13394                 return OP_X86_COMPARE_MEMBASE_REG;
13395         }
13396 #endif
13397
13398 #ifdef TARGET_AMD64
13399         /* FIXME: This has sign extension issues */
13400         /*
13401         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13402                 return OP_X86_COMPARE_MEMBASE8_IMM;
13403         */
13404
13405         switch (opcode) {
13406         case OP_X86_PUSH:
13407                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13408                         return OP_X86_PUSH_MEMBASE;
13409                 break;
13410                 /* FIXME: This only works for 32 bit immediates
13411         case OP_COMPARE_IMM:
13412         case OP_LCOMPARE_IMM:
13413                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13414                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13415                 */
13416         case OP_ICOMPARE_IMM:
13417                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13418                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13419                 break;
13420         case OP_COMPARE:
13421         case OP_LCOMPARE:
13422                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13423                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13424                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13425                         return OP_AMD64_COMPARE_MEMBASE_REG;
13426                 break;
13427         case OP_ICOMPARE:
13428                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13429                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13430                 break;
13431         }
13432 #endif
13433
13434         return -1;
13435 }
13436
13437 static inline int
13438 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13439 {
13440 #ifdef TARGET_X86
13441         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13442                 return -1;
13443         
13444         switch (opcode) {
13445         case OP_COMPARE:
13446         case OP_ICOMPARE:
13447                 return OP_X86_COMPARE_REG_MEMBASE;
13448         case OP_IADD:
13449                 return OP_X86_ADD_REG_MEMBASE;
13450         case OP_ISUB:
13451                 return OP_X86_SUB_REG_MEMBASE;
13452         case OP_IAND:
13453                 return OP_X86_AND_REG_MEMBASE;
13454         case OP_IOR:
13455                 return OP_X86_OR_REG_MEMBASE;
13456         case OP_IXOR:
13457                 return OP_X86_XOR_REG_MEMBASE;
13458         }
13459 #endif
13460
13461 #ifdef TARGET_AMD64
13462         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13463                 switch (opcode) {
13464                 case OP_ICOMPARE:
13465                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13466                 case OP_IADD:
13467                         return OP_X86_ADD_REG_MEMBASE;
13468                 case OP_ISUB:
13469                         return OP_X86_SUB_REG_MEMBASE;
13470                 case OP_IAND:
13471                         return OP_X86_AND_REG_MEMBASE;
13472                 case OP_IOR:
13473                         return OP_X86_OR_REG_MEMBASE;
13474                 case OP_IXOR:
13475                         return OP_X86_XOR_REG_MEMBASE;
13476                 }
13477         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13478                 switch (opcode) {
13479                 case OP_COMPARE:
13480                 case OP_LCOMPARE:
13481                         return OP_AMD64_COMPARE_REG_MEMBASE;
13482                 case OP_LADD:
13483                         return OP_AMD64_ADD_REG_MEMBASE;
13484                 case OP_LSUB:
13485                         return OP_AMD64_SUB_REG_MEMBASE;
13486                 case OP_LAND:
13487                         return OP_AMD64_AND_REG_MEMBASE;
13488                 case OP_LOR:
13489                         return OP_AMD64_OR_REG_MEMBASE;
13490                 case OP_LXOR:
13491                         return OP_AMD64_XOR_REG_MEMBASE;
13492                 }
13493         }
13494 #endif
13495
13496         return -1;
13497 }
13498
13499 int
13500 mono_op_to_op_imm_noemul (int opcode)
13501 {
13502         switch (opcode) {
13503 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13504         case OP_LSHR:
13505         case OP_LSHL:
13506         case OP_LSHR_UN:
13507                 return -1;
13508 #endif
13509 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13510         case OP_IDIV:
13511         case OP_IDIV_UN:
13512         case OP_IREM:
13513         case OP_IREM_UN:
13514                 return -1;
13515 #endif
13516 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13517         case OP_IMUL:
13518                 return -1;
13519 #endif
13520         default:
13521                 return mono_op_to_op_imm (opcode);
13522         }
13523 }
13524
13525 /**
13526  * mono_handle_global_vregs:
13527  *
13528  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13529  * for them.
13530  */
13531 void
13532 mono_handle_global_vregs (MonoCompile *cfg)
13533 {
13534         gint32 *vreg_to_bb;
13535         MonoBasicBlock *bb;
13536         int i, pos;
13537
13538         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13539
13540 #ifdef MONO_ARCH_SIMD_INTRINSICS
13541         if (cfg->uses_simd_intrinsics)
13542                 mono_simd_simplify_indirection (cfg);
13543 #endif
13544
13545         /* Find local vregs used in more than one bb */
13546         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13547                 MonoInst *ins = bb->code;       
13548                 int block_num = bb->block_num;
13549
13550                 if (cfg->verbose_level > 2)
13551                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13552
13553                 cfg->cbb = bb;
13554                 for (; ins; ins = ins->next) {
13555                         const char *spec = INS_INFO (ins->opcode);
13556                         int regtype = 0, regindex;
13557                         gint32 prev_bb;
13558
13559                         if (G_UNLIKELY (cfg->verbose_level > 2))
13560                                 mono_print_ins (ins);
13561
13562                         g_assert (ins->opcode >= MONO_CEE_LAST);
13563
13564                         for (regindex = 0; regindex < 4; regindex ++) {
13565                                 int vreg = 0;
13566
13567                                 if (regindex == 0) {
13568                                         regtype = spec [MONO_INST_DEST];
13569                                         if (regtype == ' ')
13570                                                 continue;
13571                                         vreg = ins->dreg;
13572                                 } else if (regindex == 1) {
13573                                         regtype = spec [MONO_INST_SRC1];
13574                                         if (regtype == ' ')
13575                                                 continue;
13576                                         vreg = ins->sreg1;
13577                                 } else if (regindex == 2) {
13578                                         regtype = spec [MONO_INST_SRC2];
13579                                         if (regtype == ' ')
13580                                                 continue;
13581                                         vreg = ins->sreg2;
13582                                 } else if (regindex == 3) {
13583                                         regtype = spec [MONO_INST_SRC3];
13584                                         if (regtype == ' ')
13585                                                 continue;
13586                                         vreg = ins->sreg3;
13587                                 }
13588
13589 #if SIZEOF_REGISTER == 4
13590                                 /* In the LLVM case, the long opcodes are not decomposed */
13591                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13592                                         /*
13593                                          * Since some instructions reference the original long vreg,
13594                                          * and some reference the two component vregs, it is quite hard
13595                                          * to determine when it needs to be global. So be conservative.
13596                                          */
13597                                         if (!get_vreg_to_inst (cfg, vreg)) {
13598                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13599
13600                                                 if (cfg->verbose_level > 2)
13601                                                         printf ("LONG VREG R%d made global.\n", vreg);
13602                                         }
13603
13604                                         /*
13605                                          * Make the component vregs volatile since the optimizations can
13606                                          * get confused otherwise.
13607                                          */
13608                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13609                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13610                                 }
13611 #endif
13612
13613                                 g_assert (vreg != -1);
13614
13615                                 prev_bb = vreg_to_bb [vreg];
13616                                 if (prev_bb == 0) {
13617                                         /* 0 is a valid block num */
13618                                         vreg_to_bb [vreg] = block_num + 1;
13619                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13620                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13621                                                 continue;
13622
13623                                         if (!get_vreg_to_inst (cfg, vreg)) {
13624                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13625                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13626
13627                                                 switch (regtype) {
13628                                                 case 'i':
13629                                                         if (vreg_is_ref (cfg, vreg))
13630                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13631                                                         else
13632                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13633                                                         break;
13634                                                 case 'l':
13635                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13636                                                         break;
13637                                                 case 'f':
13638                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13639                                                         break;
13640                                                 case 'v':
13641                                                 case 'x':
13642                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13643                                                         break;
13644                                                 default:
13645                                                         g_assert_not_reached ();
13646                                                 }
13647                                         }
13648
13649                                         /* Flag as having been used in more than one bb */
13650                                         vreg_to_bb [vreg] = -1;
13651                                 }
13652                         }
13653                 }
13654         }
13655
13656         /* If a variable is used in only one bblock, convert it into a local vreg */
13657         for (i = 0; i < cfg->num_varinfo; i++) {
13658                 MonoInst *var = cfg->varinfo [i];
13659                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13660
13661                 switch (var->type) {
13662                 case STACK_I4:
13663                 case STACK_OBJ:
13664                 case STACK_PTR:
13665                 case STACK_MP:
13666                 case STACK_VTYPE:
13667 #if SIZEOF_REGISTER == 8
13668                 case STACK_I8:
13669 #endif
13670 #if !defined(TARGET_X86)
13671                 /* Enabling this screws up the fp stack on x86 */
13672                 case STACK_R8:
13673 #endif
13674                         if (mono_arch_is_soft_float ())
13675                                 break;
13676
13677                         /*
13678                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13679                                 break;
13680                         */
13681
13682                         /* Arguments are implicitly global */
13683                         /* Putting R4 vars into registers doesn't work currently */
13684                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13685                         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) {
13686                                 /* 
13687                                  * Make that the variable's liveness interval doesn't contain a call, since
13688                                  * that would cause the lvreg to be spilled, making the whole optimization
13689                                  * useless.
13690                                  */
13691                                 /* This is too slow for JIT compilation */
13692 #if 0
13693                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13694                                         MonoInst *ins;
13695                                         int def_index, call_index, ins_index;
13696                                         gboolean spilled = FALSE;
13697
13698                                         def_index = -1;
13699                                         call_index = -1;
13700                                         ins_index = 0;
13701                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13702                                                 const char *spec = INS_INFO (ins->opcode);
13703
13704                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13705                                                         def_index = ins_index;
13706
13707                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13708                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13709                                                         if (call_index > def_index) {
13710                                                                 spilled = TRUE;
13711                                                                 break;
13712                                                         }
13713                                                 }
13714
13715                                                 if (MONO_IS_CALL (ins))
13716                                                         call_index = ins_index;
13717
13718                                                 ins_index ++;
13719                                         }
13720
13721                                         if (spilled)
13722                                                 break;
13723                                 }
13724 #endif
13725
13726                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13727                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13728                                 var->flags |= MONO_INST_IS_DEAD;
13729                                 cfg->vreg_to_inst [var->dreg] = NULL;
13730                         }
13731                         break;
13732                 }
13733         }
13734
13735         /* 
13736          * Compress the varinfo and vars tables so the liveness computation is faster and
13737          * takes up less space.
13738          */
13739         pos = 0;
13740         for (i = 0; i < cfg->num_varinfo; ++i) {
13741                 MonoInst *var = cfg->varinfo [i];
13742                 if (pos < i && cfg->locals_start == i)
13743                         cfg->locals_start = pos;
13744                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13745                         if (pos < i) {
13746                                 cfg->varinfo [pos] = cfg->varinfo [i];
13747                                 cfg->varinfo [pos]->inst_c0 = pos;
13748                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13749                                 cfg->vars [pos].idx = pos;
13750 #if SIZEOF_REGISTER == 4
13751                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13752                                         /* Modify the two component vars too */
13753                                         MonoInst *var1;
13754
13755                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13756                                         var1->inst_c0 = pos;
13757                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13758                                         var1->inst_c0 = pos;
13759                                 }
13760 #endif
13761                         }
13762                         pos ++;
13763                 }
13764         }
13765         cfg->num_varinfo = pos;
13766         if (cfg->locals_start > cfg->num_varinfo)
13767                 cfg->locals_start = cfg->num_varinfo;
13768 }
13769
13770 /*
13771  * mono_allocate_gsharedvt_vars:
13772  *
13773  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13774  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13775  */
13776 void
13777 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13778 {
13779         int i;
13780
13781         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13782
13783         for (i = 0; i < cfg->num_varinfo; ++i) {
13784                 MonoInst *ins = cfg->varinfo [i];
13785                 int idx;
13786
13787                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13788                         if (i >= cfg->locals_start) {
13789                                 /* Local */
13790                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13791                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13792                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13793                                 ins->inst_imm = idx;
13794                         } else {
13795                                 /* Arg */
13796                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13797                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13798                         }
13799                 }
13800         }
13801 }
13802
13803 /**
13804  * mono_spill_global_vars:
13805  *
13806  *   Generate spill code for variables which are not allocated to registers, 
13807  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13808  * code is generated which could be optimized by the local optimization passes.
13809  */
13810 void
13811 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13812 {
13813         MonoBasicBlock *bb;
13814         char spec2 [16];
13815         int orig_next_vreg;
13816         guint32 *vreg_to_lvreg;
13817         guint32 *lvregs;
13818         guint32 i, lvregs_len, lvregs_size;
13819         gboolean dest_has_lvreg = FALSE;
13820         MonoStackType stacktypes [128];
13821         MonoInst **live_range_start, **live_range_end;
13822         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13823
13824         *need_local_opts = FALSE;
13825
13826         memset (spec2, 0, sizeof (spec2));
13827
13828         /* FIXME: Move this function to mini.c */
13829         stacktypes ['i'] = STACK_PTR;
13830         stacktypes ['l'] = STACK_I8;
13831         stacktypes ['f'] = STACK_R8;
13832 #ifdef MONO_ARCH_SIMD_INTRINSICS
13833         stacktypes ['x'] = STACK_VTYPE;
13834 #endif
13835
13836 #if SIZEOF_REGISTER == 4
13837         /* Create MonoInsts for longs */
13838         for (i = 0; i < cfg->num_varinfo; i++) {
13839                 MonoInst *ins = cfg->varinfo [i];
13840
13841                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13842                         switch (ins->type) {
13843                         case STACK_R8:
13844                         case STACK_I8: {
13845                                 MonoInst *tree;
13846
13847                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13848                                         break;
13849
13850                                 g_assert (ins->opcode == OP_REGOFFSET);
13851
13852                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13853                                 g_assert (tree);
13854                                 tree->opcode = OP_REGOFFSET;
13855                                 tree->inst_basereg = ins->inst_basereg;
13856                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13857
13858                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13859                                 g_assert (tree);
13860                                 tree->opcode = OP_REGOFFSET;
13861                                 tree->inst_basereg = ins->inst_basereg;
13862                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13863                                 break;
13864                         }
13865                         default:
13866                                 break;
13867                         }
13868                 }
13869         }
13870 #endif
13871
13872         if (cfg->compute_gc_maps) {
13873                 /* registers need liveness info even for !non refs */
13874                 for (i = 0; i < cfg->num_varinfo; i++) {
13875                         MonoInst *ins = cfg->varinfo [i];
13876
13877                         if (ins->opcode == OP_REGVAR)
13878                                 ins->flags |= MONO_INST_GC_TRACK;
13879                 }
13880         }
13881                 
13882         /* FIXME: widening and truncation */
13883
13884         /*
13885          * As an optimization, when a variable allocated to the stack is first loaded into 
13886          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13887          * the variable again.
13888          */
13889         orig_next_vreg = cfg->next_vreg;
13890         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13891         lvregs_size = 1024;
13892         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13893         lvregs_len = 0;
13894
13895         /* 
13896          * These arrays contain the first and last instructions accessing a given
13897          * variable.
13898          * Since we emit bblocks in the same order we process them here, and we
13899          * don't split live ranges, these will precisely describe the live range of
13900          * the variable, i.e. the instruction range where a valid value can be found
13901          * in the variables location.
13902          * The live range is computed using the liveness info computed by the liveness pass.
13903          * We can't use vmv->range, since that is an abstract live range, and we need
13904          * one which is instruction precise.
13905          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13906          */
13907         /* FIXME: Only do this if debugging info is requested */
13908         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13909         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13910         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13911         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13912         
13913         /* Add spill loads/stores */
13914         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13915                 MonoInst *ins;
13916
13917                 if (cfg->verbose_level > 2)
13918                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13919
13920                 /* Clear vreg_to_lvreg array */
13921                 for (i = 0; i < lvregs_len; i++)
13922                         vreg_to_lvreg [lvregs [i]] = 0;
13923                 lvregs_len = 0;
13924
13925                 cfg->cbb = bb;
13926                 MONO_BB_FOR_EACH_INS (bb, ins) {
13927                         const char *spec = INS_INFO (ins->opcode);
13928                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13929                         gboolean store, no_lvreg;
13930                         int sregs [MONO_MAX_SRC_REGS];
13931
13932                         if (G_UNLIKELY (cfg->verbose_level > 2))
13933                                 mono_print_ins (ins);
13934
13935                         if (ins->opcode == OP_NOP)
13936                                 continue;
13937
13938                         /* 
13939                          * We handle LDADDR here as well, since it can only be decomposed
13940                          * when variable addresses are known.
13941                          */
13942                         if (ins->opcode == OP_LDADDR) {
13943                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13944
13945                                 if (var->opcode == OP_VTARG_ADDR) {
13946                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13947                                         MonoInst *vtaddr = var->inst_left;
13948                                         if (vtaddr->opcode == OP_REGVAR) {
13949                                                 ins->opcode = OP_MOVE;
13950                                                 ins->sreg1 = vtaddr->dreg;
13951                                         }
13952                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13953                                                 ins->opcode = OP_LOAD_MEMBASE;
13954                                                 ins->inst_basereg = vtaddr->inst_basereg;
13955                                                 ins->inst_offset = vtaddr->inst_offset;
13956                                         } else
13957                                                 NOT_IMPLEMENTED;
13958                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13959                                         /* gsharedvt arg passed by ref */
13960                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13961
13962                                         ins->opcode = OP_LOAD_MEMBASE;
13963                                         ins->inst_basereg = var->inst_basereg;
13964                                         ins->inst_offset = var->inst_offset;
13965                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13966                                         MonoInst *load, *load2, *load3;
13967                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13968                                         int reg1, reg2, reg3;
13969                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13970                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13971
13972                                         /*
13973                                          * gsharedvt local.
13974                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13975                                          */
13976
13977                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13978
13979                                         g_assert (info_var);
13980                                         g_assert (locals_var);
13981
13982                                         /* Mark the instruction used to compute the locals var as used */
13983                                         cfg->gsharedvt_locals_var_ins = NULL;
13984
13985                                         /* Load the offset */
13986                                         if (info_var->opcode == OP_REGOFFSET) {
13987                                                 reg1 = alloc_ireg (cfg);
13988                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13989                                         } else if (info_var->opcode == OP_REGVAR) {
13990                                                 load = NULL;
13991                                                 reg1 = info_var->dreg;
13992                                         } else {
13993                                                 g_assert_not_reached ();
13994                                         }
13995                                         reg2 = alloc_ireg (cfg);
13996                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13997                                         /* Load the locals area address */
13998                                         reg3 = alloc_ireg (cfg);
13999                                         if (locals_var->opcode == OP_REGOFFSET) {
14000                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
14001                                         } else if (locals_var->opcode == OP_REGVAR) {
14002                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
14003                                         } else {
14004                                                 g_assert_not_reached ();
14005                                         }
14006                                         /* Compute the address */
14007                                         ins->opcode = OP_PADD;
14008                                         ins->sreg1 = reg3;
14009                                         ins->sreg2 = reg2;
14010
14011                                         mono_bblock_insert_before_ins (bb, ins, load3);
14012                                         mono_bblock_insert_before_ins (bb, load3, load2);
14013                                         if (load)
14014                                                 mono_bblock_insert_before_ins (bb, load2, load);
14015                                 } else {
14016                                         g_assert (var->opcode == OP_REGOFFSET);
14017
14018                                         ins->opcode = OP_ADD_IMM;
14019                                         ins->sreg1 = var->inst_basereg;
14020                                         ins->inst_imm = var->inst_offset;
14021                                 }
14022
14023                                 *need_local_opts = TRUE;
14024                                 spec = INS_INFO (ins->opcode);
14025                         }
14026
14027                         if (ins->opcode < MONO_CEE_LAST) {
14028                                 mono_print_ins (ins);
14029                                 g_assert_not_reached ();
14030                         }
14031
14032                         /*
14033                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
14034                          * src register.
14035                          * FIXME:
14036                          */
14037                         if (MONO_IS_STORE_MEMBASE (ins)) {
14038                                 tmp_reg = ins->dreg;
14039                                 ins->dreg = ins->sreg2;
14040                                 ins->sreg2 = tmp_reg;
14041                                 store = TRUE;
14042
14043                                 spec2 [MONO_INST_DEST] = ' ';
14044                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14045                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14046                                 spec2 [MONO_INST_SRC3] = ' ';
14047                                 spec = spec2;
14048                         } else if (MONO_IS_STORE_MEMINDEX (ins))
14049                                 g_assert_not_reached ();
14050                         else
14051                                 store = FALSE;
14052                         no_lvreg = FALSE;
14053
14054                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
14055                                 printf ("\t %.3s %d", spec, ins->dreg);
14056                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
14057                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
14058                                         printf (" %d", sregs [srcindex]);
14059                                 printf ("\n");
14060                         }
14061
14062                         /***************/
14063                         /*    DREG     */
14064                         /***************/
14065                         regtype = spec [MONO_INST_DEST];
14066                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
14067                         prev_dreg = -1;
14068
14069                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
14070                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
14071                                 MonoInst *store_ins;
14072                                 int store_opcode;
14073                                 MonoInst *def_ins = ins;
14074                                 int dreg = ins->dreg; /* The original vreg */
14075
14076                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
14077
14078                                 if (var->opcode == OP_REGVAR) {
14079                                         ins->dreg = var->dreg;
14080                                 } 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)) {
14081                                         /* 
14082                                          * Instead of emitting a load+store, use a _membase opcode.
14083                                          */
14084                                         g_assert (var->opcode == OP_REGOFFSET);
14085                                         if (ins->opcode == OP_MOVE) {
14086                                                 NULLIFY_INS (ins);
14087                                                 def_ins = NULL;
14088                                         } else {
14089                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
14090                                                 ins->inst_basereg = var->inst_basereg;
14091                                                 ins->inst_offset = var->inst_offset;
14092                                                 ins->dreg = -1;
14093                                         }
14094                                         spec = INS_INFO (ins->opcode);
14095                                 } else {
14096                                         guint32 lvreg;
14097
14098                                         g_assert (var->opcode == OP_REGOFFSET);
14099
14100                                         prev_dreg = ins->dreg;
14101
14102                                         /* Invalidate any previous lvreg for this vreg */
14103                                         vreg_to_lvreg [ins->dreg] = 0;
14104
14105                                         lvreg = 0;
14106
14107                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14108                                                 regtype = 'l';
14109                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14110                                         }
14111
14112                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14113
14114 #if SIZEOF_REGISTER != 8
14115                                         if (regtype == 'l') {
14116                                                 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));
14117                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14118                                                 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));
14119                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14120                                                 def_ins = store_ins;
14121                                         }
14122                                         else
14123 #endif
14124                                         {
14125                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14126
14127                                                 /* Try to fuse the store into the instruction itself */
14128                                                 /* FIXME: Add more instructions */
14129                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14130                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14131                                                         ins->inst_imm = ins->inst_c0;
14132                                                         ins->inst_destbasereg = var->inst_basereg;
14133                                                         ins->inst_offset = var->inst_offset;
14134                                                         spec = INS_INFO (ins->opcode);
14135                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14136                                                         ins->opcode = store_opcode;
14137                                                         ins->inst_destbasereg = var->inst_basereg;
14138                                                         ins->inst_offset = var->inst_offset;
14139
14140                                                         no_lvreg = TRUE;
14141
14142                                                         tmp_reg = ins->dreg;
14143                                                         ins->dreg = ins->sreg2;
14144                                                         ins->sreg2 = tmp_reg;
14145                                                         store = TRUE;
14146
14147                                                         spec2 [MONO_INST_DEST] = ' ';
14148                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14149                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14150                                                         spec2 [MONO_INST_SRC3] = ' ';
14151                                                         spec = spec2;
14152                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14153                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14154                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14155                                                         ins->dreg = -1;
14156                                                         ins->inst_basereg = var->inst_basereg;
14157                                                         ins->inst_offset = var->inst_offset;
14158                                                         spec = INS_INFO (ins->opcode);
14159                                                 } else {
14160                                                         /* printf ("INS: "); mono_print_ins (ins); */
14161                                                         /* Create a store instruction */
14162                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14163
14164                                                         /* Insert it after the instruction */
14165                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14166
14167                                                         def_ins = store_ins;
14168
14169                                                         /* 
14170                                                          * We can't assign ins->dreg to var->dreg here, since the
14171                                                          * sregs could use it. So set a flag, and do it after
14172                                                          * the sregs.
14173                                                          */
14174                                                         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)))
14175                                                                 dest_has_lvreg = TRUE;
14176                                                 }
14177                                         }
14178                                 }
14179
14180                                 if (def_ins && !live_range_start [dreg]) {
14181                                         live_range_start [dreg] = def_ins;
14182                                         live_range_start_bb [dreg] = bb;
14183                                 }
14184
14185                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14186                                         MonoInst *tmp;
14187
14188                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14189                                         tmp->inst_c1 = dreg;
14190                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14191                                 }
14192                         }
14193
14194                         /************/
14195                         /*  SREGS   */
14196                         /************/
14197                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14198                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14199                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14200                                 sreg = sregs [srcindex];
14201
14202                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14203                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14204                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14205                                         MonoInst *use_ins = ins;
14206                                         MonoInst *load_ins;
14207                                         guint32 load_opcode;
14208
14209                                         if (var->opcode == OP_REGVAR) {
14210                                                 sregs [srcindex] = var->dreg;
14211                                                 //mono_inst_set_src_registers (ins, sregs);
14212                                                 live_range_end [sreg] = use_ins;
14213                                                 live_range_end_bb [sreg] = bb;
14214
14215                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14216                                                         MonoInst *tmp;
14217
14218                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14219                                                         /* var->dreg is a hreg */
14220                                                         tmp->inst_c1 = sreg;
14221                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14222                                                 }
14223
14224                                                 continue;
14225                                         }
14226
14227                                         g_assert (var->opcode == OP_REGOFFSET);
14228                                                 
14229                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14230
14231                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14232
14233                                         if (vreg_to_lvreg [sreg]) {
14234                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14235
14236                                                 /* The variable is already loaded to an lvreg */
14237                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14238                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14239                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14240                                                 //mono_inst_set_src_registers (ins, sregs);
14241                                                 continue;
14242                                         }
14243
14244                                         /* Try to fuse the load into the instruction */
14245                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14246                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14247                                                 sregs [0] = var->inst_basereg;
14248                                                 //mono_inst_set_src_registers (ins, sregs);
14249                                                 ins->inst_offset = var->inst_offset;
14250                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14251                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14252                                                 sregs [1] = var->inst_basereg;
14253                                                 //mono_inst_set_src_registers (ins, sregs);
14254                                                 ins->inst_offset = var->inst_offset;
14255                                         } else {
14256                                                 if (MONO_IS_REAL_MOVE (ins)) {
14257                                                         ins->opcode = OP_NOP;
14258                                                         sreg = ins->dreg;
14259                                                 } else {
14260                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14261
14262                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14263
14264                                                         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) {
14265                                                                 if (var->dreg == prev_dreg) {
14266                                                                         /*
14267                                                                          * sreg refers to the value loaded by the load
14268                                                                          * emitted below, but we need to use ins->dreg
14269                                                                          * since it refers to the store emitted earlier.
14270                                                                          */
14271                                                                         sreg = ins->dreg;
14272                                                                 }
14273                                                                 g_assert (sreg != -1);
14274                                                                 vreg_to_lvreg [var->dreg] = sreg;
14275                                                                 if (lvregs_len >= lvregs_size) {
14276                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14277                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14278                                                                         lvregs = new_lvregs;
14279                                                                         lvregs_size *= 2;
14280                                                                 }
14281                                                                 lvregs [lvregs_len ++] = var->dreg;
14282                                                         }
14283                                                 }
14284
14285                                                 sregs [srcindex] = sreg;
14286                                                 //mono_inst_set_src_registers (ins, sregs);
14287
14288 #if SIZEOF_REGISTER != 8
14289                                                 if (regtype == 'l') {
14290                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14291                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14292                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14293                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14294                                                         use_ins = load_ins;
14295                                                 }
14296                                                 else
14297 #endif
14298                                                 {
14299 #if SIZEOF_REGISTER == 4
14300                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14301 #endif
14302                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14303                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14304                                                         use_ins = load_ins;
14305                                                 }
14306                                         }
14307
14308                                         if (var->dreg < orig_next_vreg) {
14309                                                 live_range_end [var->dreg] = use_ins;
14310                                                 live_range_end_bb [var->dreg] = bb;
14311                                         }
14312
14313                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14314                                                 MonoInst *tmp;
14315
14316                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14317                                                 tmp->inst_c1 = var->dreg;
14318                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14319                                         }
14320                                 }
14321                         }
14322                         mono_inst_set_src_registers (ins, sregs);
14323
14324                         if (dest_has_lvreg) {
14325                                 g_assert (ins->dreg != -1);
14326                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14327                                 if (lvregs_len >= lvregs_size) {
14328                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14329                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14330                                         lvregs = new_lvregs;
14331                                         lvregs_size *= 2;
14332                                 }
14333                                 lvregs [lvregs_len ++] = prev_dreg;
14334                                 dest_has_lvreg = FALSE;
14335                         }
14336
14337                         if (store) {
14338                                 tmp_reg = ins->dreg;
14339                                 ins->dreg = ins->sreg2;
14340                                 ins->sreg2 = tmp_reg;
14341                         }
14342
14343                         if (MONO_IS_CALL (ins)) {
14344                                 /* Clear vreg_to_lvreg array */
14345                                 for (i = 0; i < lvregs_len; i++)
14346                                         vreg_to_lvreg [lvregs [i]] = 0;
14347                                 lvregs_len = 0;
14348                         } else if (ins->opcode == OP_NOP) {
14349                                 ins->dreg = -1;
14350                                 MONO_INST_NULLIFY_SREGS (ins);
14351                         }
14352
14353                         if (cfg->verbose_level > 2)
14354                                 mono_print_ins_index (1, ins);
14355                 }
14356
14357                 /* Extend the live range based on the liveness info */
14358                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14359                         for (i = 0; i < cfg->num_varinfo; i ++) {
14360                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14361
14362                                 if (vreg_is_volatile (cfg, vi->vreg))
14363                                         /* The liveness info is incomplete */
14364                                         continue;
14365
14366                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14367                                         /* Live from at least the first ins of this bb */
14368                                         live_range_start [vi->vreg] = bb->code;
14369                                         live_range_start_bb [vi->vreg] = bb;
14370                                 }
14371
14372                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14373                                         /* Live at least until the last ins of this bb */
14374                                         live_range_end [vi->vreg] = bb->last_ins;
14375                                         live_range_end_bb [vi->vreg] = bb;
14376                                 }
14377                         }
14378                 }
14379         }
14380         
14381         /*
14382          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14383          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14384          */
14385         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14386                 for (i = 0; i < cfg->num_varinfo; ++i) {
14387                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14388                         MonoInst *ins;
14389
14390                         if (live_range_start [vreg]) {
14391                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14392                                 ins->inst_c0 = i;
14393                                 ins->inst_c1 = vreg;
14394                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14395                         }
14396                         if (live_range_end [vreg]) {
14397                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14398                                 ins->inst_c0 = i;
14399                                 ins->inst_c1 = vreg;
14400                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14401                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14402                                 else
14403                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14404                         }
14405                 }
14406         }
14407
14408         if (cfg->gsharedvt_locals_var_ins) {
14409                 /* Nullify if unused */
14410                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14411                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14412         }
14413
14414         g_free (live_range_start);
14415         g_free (live_range_end);
14416         g_free (live_range_start_bb);
14417         g_free (live_range_end_bb);
14418 }
14419
14420
14421 /**
14422  * FIXME:
14423  * - use 'iadd' instead of 'int_add'
14424  * - handling ovf opcodes: decompose in method_to_ir.
14425  * - unify iregs/fregs
14426  *   -> partly done, the missing parts are:
14427  *   - a more complete unification would involve unifying the hregs as well, so
14428  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14429  *     would no longer map to the machine hregs, so the code generators would need to
14430  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14431  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14432  *     fp/non-fp branches speeds it up by about 15%.
14433  * - use sext/zext opcodes instead of shifts
14434  * - add OP_ICALL
14435  * - get rid of TEMPLOADs if possible and use vregs instead
14436  * - clean up usage of OP_P/OP_ opcodes
14437  * - cleanup usage of DUMMY_USE
14438  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14439  *   stack
14440  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14441  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14442  * - make sure handle_stack_args () is called before the branch is emitted
14443  * - when the new IR is done, get rid of all unused stuff
14444  * - COMPARE/BEQ as separate instructions or unify them ?
14445  *   - keeping them separate allows specialized compare instructions like
14446  *     compare_imm, compare_membase
14447  *   - most back ends unify fp compare+branch, fp compare+ceq
14448  * - integrate mono_save_args into inline_method
14449  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14450  * - handle long shift opts on 32 bit platforms somehow: they require 
14451  *   3 sregs (2 for arg1 and 1 for arg2)
14452  * - make byref a 'normal' type.
14453  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14454  *   variable if needed.
14455  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14456  *   like inline_method.
14457  * - remove inlining restrictions
14458  * - fix LNEG and enable cfold of INEG
14459  * - generalize x86 optimizations like ldelema as a peephole optimization
14460  * - add store_mem_imm for amd64
14461  * - optimize the loading of the interruption flag in the managed->native wrappers
14462  * - avoid special handling of OP_NOP in passes
14463  * - move code inserting instructions into one function/macro.
14464  * - try a coalescing phase after liveness analysis
14465  * - add float -> vreg conversion + local optimizations on !x86
14466  * - figure out how to handle decomposed branches during optimizations, ie.
14467  *   compare+branch, op_jump_table+op_br etc.
14468  * - promote RuntimeXHandles to vregs
14469  * - vtype cleanups:
14470  *   - add a NEW_VARLOADA_VREG macro
14471  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14472  *   accessing vtype fields.
14473  * - get rid of I8CONST on 64 bit platforms
14474  * - dealing with the increase in code size due to branches created during opcode
14475  *   decomposition:
14476  *   - use extended basic blocks
14477  *     - all parts of the JIT
14478  *     - handle_global_vregs () && local regalloc
14479  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14480  * - sources of increase in code size:
14481  *   - vtypes
14482  *   - long compares
14483  *   - isinst and castclass
14484  *   - lvregs not allocated to global registers even if used multiple times
14485  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14486  *   meaningful.
14487  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14488  * - add all micro optimizations from the old JIT
14489  * - put tree optimizations into the deadce pass
14490  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14491  *   specific function.
14492  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14493  *   fcompare + branchCC.
14494  * - create a helper function for allocating a stack slot, taking into account 
14495  *   MONO_CFG_HAS_SPILLUP.
14496  * - merge r68207.
14497  * - merge the ia64 switch changes.
14498  * - optimize mono_regstate2_alloc_int/float.
14499  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14500  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14501  *   parts of the tree could be separated by other instructions, killing the tree
14502  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14503  *   instructions if the result of the load is used multiple times ?
14504  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14505  * - LAST MERGE: 108395.
14506  * - when returning vtypes in registers, generate IR and append it to the end of the
14507  *   last bb instead of doing it in the epilog.
14508  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14509  */
14510
14511 /*
14512
14513 NOTES
14514 -----
14515
14516 - When to decompose opcodes:
14517   - earlier: this makes some optimizations hard to implement, since the low level IR
14518   no longer contains the neccessary information. But it is easier to do.
14519   - later: harder to implement, enables more optimizations.
14520 - Branches inside bblocks:
14521   - created when decomposing complex opcodes. 
14522     - branches to another bblock: harmless, but not tracked by the branch 
14523       optimizations, so need to branch to a label at the start of the bblock.
14524     - branches to inside the same bblock: very problematic, trips up the local
14525       reg allocator. Can be fixed by spitting the current bblock, but that is a
14526       complex operation, since some local vregs can become global vregs etc.
14527 - Local/global vregs:
14528   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14529     local register allocator.
14530   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14531     structure, created by mono_create_var (). Assigned to hregs or the stack by
14532     the global register allocator.
14533 - When to do optimizations like alu->alu_imm:
14534   - earlier -> saves work later on since the IR will be smaller/simpler
14535   - later -> can work on more instructions
14536 - Handling of valuetypes:
14537   - When a vtype is pushed on the stack, a new temporary is created, an 
14538     instruction computing its address (LDADDR) is emitted and pushed on
14539     the stack. Need to optimize cases when the vtype is used immediately as in
14540     argument passing, stloc etc.
14541 - Instead of the to_end stuff in the old JIT, simply call the function handling
14542   the values on the stack before emitting the last instruction of the bb.
14543 */
14544
14545 #else /* !DISABLE_JIT */
14546
14547 MONO_EMPTY_SOURCE_FILE (method_to_ir);
14548
14549 #endif /* !DISABLE_JIT */